feat(graph): enforce USD budget at each agent invocation with pre-flight gate #79
Closed
CoreRasurae
wants to merge 1 commits from
feature/76-budget-pre-flight into master
pull from: feature/76-budget-pre-flight
merge into: cleveragents:master
cleveragents:master
cleveragents:feature/m2-file-read-offset
cleveragents:feature/m2-tool-timeout-awareness
cleveragents:feature/17-public-api
cleveragents:feature/m1-registry-http-client
cleveragents:master-backup
Labels
Clear labels
auto/blocked-by-deps
auto/ci-timeout
auto/claimed-implementer
auto/claimed-merge
auto/claimed-reviewer
auto/driver-down
auto/invariant-violation
auto/last-attempt-tier-0
auto/last-attempt-tier-1
auto/last-attempt-tier-2
auto/last-attempt-tier-min
Automation Tracking
auto/needs-conflict-resolution
auto/needs-implementer
auto/postmortem
auto/ready-to-merge
auto/restart-throttled
auto/revert
auto/sentinel
auto/stale-inactivity
auto/unstable
Blocked
Needs Feedback
Signed-off: Owner
Signed-off: Scrum Master
Signed-off: Tech Lead
Spike
PR blocked by an open issue dependency. Operator must close the dep (or remove the dependency link) before the merge driver can act. Auto-cleared by merge_drive when no open deps remain.
Most recent merge cycle hit CI timeout. Driver excludes this PR while last merge_cycle row is < 30 min old; label persists thereafter as visible history.
Currently being processed by an implementer worker.
Currently being processed by the merge driver.
Currently being processed by a reviewer worker.
Merge driver heartbeat stale; pipeline halted. Closed automatically on next clean tick.
Detected master commit violating the strict merge invariant. Tracked as an issue (not a PR label); kept here for label completeness.
In-cycle escalation: most recent attempt ran at the Tier 0 slot (`tier-0`). Slot's model defined in .opencode/models/tiers.yaml.
In-cycle escalation: most recent attempt ran at the Tier 1 slot (`tier-1`). Slot's model defined in .opencode/models/tiers.yaml.
In-cycle escalation: most recent attempt ran at the Tier 2 slot (`tier-2`). Slot's model defined in .opencode/models/tiers.yaml. Gated behind IMPLEMENTER_ESCALATION_TIER2_ENABLED.
In-cycle escalation: most recent attempt ran at the Tier -1 slot (`tier-min`). Slot's model defined in .opencode/models/tiers.yaml. Suffix is ``-min`` (not ``--1``) so the Forgejo UI reads naturally.
Tracking issues used by the AI Automation system for agents to communicate and report.
Rebase conflict needs LLM conflict-resolver.
Failing CI needs implementer attention.
Documenting a driver incident or rollback.
Reviewer has APPROVED this PR and no later REQUEST_CHANGES is outstanding. The merge driver requires this label to even consider a PR for merging. Set by the reviewer worker on APPROVE; cleared on REQUEST_CHANGES.
Train repeatedly lost master-tempo races. Driver excludes via merge_cycle until cooldown elapses; label persists as visible history.
Revert PR backing out an invariant violation. Fast-tracked through the merge driver.
Sentinel PR duplicated from upstream into a personal fork by tools/duplicate_prs_to_fork.py for pipeline testing. Lives only in the fork; the canonical pipeline never sees it.
No implementer activity for N days. Flagged for human review. Auto-cleared on next push to head branch.
Repeatedly fails on current master (>= 3 ci-fail-on-rebased-sha releases in 12 h). Excluded from driver until human triage.
A ticket in a blocked state and unable to complete until some other task is completed first.
Bounty
$100
A bounty of $100 for any open-source contributor who provides a MR that solves this issue
Bounty
$1000
A bounty of $1000 for any open-source contributor who provides a MR that solves this issue
Bounty
$10000
A bounty of $10000 for any open-source contributor who provides a MR that solves this issue
Bounty
$20
A bounty of $20 for any open-source contributor who provides a MR that solves this issue
Bounty
$2000
A bounty of $2000 for any open-source contributor who provides a MR that solves this issue
Bounty
$250
A bounty of $250 for any open-source contributor who provides a MR that solves this issue
Bounty
$50
A bounty of $50 for any open-source contributor who provides a MR that solves this issue
Bounty
$500
A bounty of $500 for any open-source contributor who provides a MR that solves this issue
Bounty
$5000
A bounty of $5000 for any open-source contributor who provides a MR that solves this issue
Bounty
$750
A bounty of $750 for any open-source contributor who provides a MR that solves this issue
MoSCoW
Could have
Could have feature in order to satisfy the epic/legendary.
MoSCoW
Must have
Must have feature in order to satisfy the epic/legendary.
MoSCoW
Should have
Should have feature in order to satisfy the epic/legendary.
There are questions in the ticket that can not be completed until the project owner provides clarity.
Points
1
1 man-hours worth of work for an expert with no learning curve.
Points
13
13 man-hours worth of work for an expert with no learning curve.
Points
2
2 man-hours worth of work for an expert with no learning curve.
Points
21
21 man-hours worth of work for an expert with no learning curve.
Points
3
3 man-hours worth of work for an expert with no learning curve.
Points
34
34 man-hours worth of work for an expert with no learning curve.
Points
5
5 man-hours worth of work for an expert with no learning curve.
Points
55
55 man-hours worth of work for an expert with no learning curve.
Points
8
8 man-hours worth of work for an expert with no learning curve.
Points
88
88 man-hours worth of work for an expert with no learning curve.
Priority
Backlog
This ticket has backlogged priority and is not to be worked on yet
Priority
CI Blocker
Critical priority issue that blocks CI/CD pipeline and prevents PR merges
Priority
Critical
The priority is critical
Priority
High
The priority is high
Priority
Low
The priority is low
Priority
Medium
The priority is medium
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
A ticket for learning a tool or technology that is needed to be able to do future planning and design.
State
Completed
The ticket has been fully implemented, completed, and merged with the source code. This label should only be applied once a ticket is closed.
State
Duplicate
A ticket that represents the same content as an existing ticket.
State
In Progress
A ticket that is actively being developed.
State
In Review
A ticket that has had some code completed to implement but is waiting to pass peer review and is not yet merged in.
State
Paused
This ticket's work started but wasn't finished. It's on hold (likely in a feature branch) and will be resumed later, either due to a blocker or a delay.
State
Unverified
All new tickets start in this state. A developer may set it to show the ticket is unverified. This means we haven't agreed to work on it. It will either move to a verified state or be closed as wontdo.
State
Verified
The issue has been verified by a developer as legitimate. It will be worked on and verified tickets are now considered part of the backlog.
State
Wont Do
This ticket has been decided it wont be done. This may mean the bug has been determined to not be real (cant verify) or the feature is one we have decided we dont want to adopt.
Type
Automation
Any edits or discussion about the AI automated coding system.
Type
Bug
Something that doesnt work as intended.
Type
Discussion
Anytime a ticket represents a discussion about a subject and doesnt fall into one of the other categories.
Type
Documentation
An error or improvement needed in the documentation.
Type
Epic
Any first tier epic. That is, an epic which contains only issues as children and will not have sub-epics.
Type
Feature
Some new functionality not present.
Type
Legendary
A type of Epic which will contain other Epics.
Type
Refactor
A code change that restructures existing code without changing its external behavior.
Type
Support
Someone needs help using the project.
Type
Task
A generic task that doesnt fit into the other type categories.
Type
Testing
Work exclusively focusing on fixing or expanding testing.
No Label
Type
Bug
Milestone
No items
No Milestone
Projects
Clear projects
No project
Assignees
aditya (Aditya Chhabra)
aleenaumair (Aleena Umair)
brent.edwards (Brent Edwards)
CoreRasurae (Luis Mendes)
drew (Drew Morris)
eugen.thaci (Eugen Thaci)
freemo (Jeffrey Phillips Freeman)
HAL9000 (HAL 9000)
HAL9001 (HAL9001)
hamza.khyari (Hamza Khyari)
hurui200320 (Rui Hu)
justin.morris
khird (Kyle Hird)
org.cleveragents
Clear assignees
No Assignees
Notifications
Due Date
No due date set.
Dependencies
No dependencies set.
Reference: cleveragents/cleveractors-core#79
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Delete Branch "feature/76-budget-pre-flight"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Enforces the USD budget (
max_cost_usd) as a hard pre-flight gate before every node execution and at each main-agentainvokeround inside the multi-turn tool loop, with pruning passes silently skipped when the budget is exhausted.Key changes
pure_graph.py):_check_budget_pre_flight()raisesExecutionError(kind="cost", reason="budget_exhausted")immediately before node execution in both_execute_from_nodeand all three branches of_stream_from_node.llm.py):_check_budget_before_invoke()gates every_retry_ainvoke()call. Pruning passes are skipped via_should_skip_pruning()when the budget is exhausted.retry.py,pure_graph.py):current_accumulated_costandcurrent_max_cost_usdContextVars carry per-node budget intoLLMAgent, always reset infinallyblocks.features/execution_limits.featureverify pre-flight failure on zero budget and on second-node exhaustion.Quality gates
nox -s lint— passnox -s format -- --check— passnox -s typecheck— pass (0 errors)nox -s security_scan— pass (0 findings)nox -s dead_code— passnox -s unit_tests— 2748/2748 scenarios passnox -s coverage_report— 96.7% (threshold: 96.5%)Closes #76
PR Review: !79 (Ticket #76)
Verdict: Request Changes
The pre-flight USD budget enforcement is wired consistently across all three executor paths and pruning is correctly guarded, but the budget ContextVars are not reset in
finallyblocks in the three streaming branches as the PR claims. On anyExecutionError(or wrapped exception re-raised asExecutionError) the ContextVars leak for the remainder of the task, which contradicts the stated safety design and can leave stale budget state behind.Critical Issues
None.
Major Issues
_stream_from_nodesrc/cleveractors/langgraph/pure_graph.pytry/exceptblocks, not insidefinally. Whenexcept ExecutionError: raiseorexcept Exception: raise ExecutionError(...)fires, control propagates out of the method before_reset_budget_contextruns. This leavescurrent_accumulated_costandcurrent_max_cost_usdset to the values from the failed node.try/finallythat resets the ContextVars, mirroring_execute_from_node(line 1077). For example, in the terminal AGENT branch move_reset_budget_context(_bcost_tok_t, _bmax_tok_t)into afinallyclause attached to the existingtry/except.Minor Issues
No-tools LLM invocations are not gated by
_check_budget_before_invokesrc/cleveractors/agents/llm.pyprocess_messageno-toolsainvoke), 1914 (stream_messageno-toolsastream)_retry_ainvoke()inside_execute_tool_loop, but the plain single-shot paths used whenself._lc_toolsisNone(or LangChain unavailable) bypass the in-node budget check. While the node-level pre-flight gate catches zero/negative balance before the node starts, this leaves an inconsistency with the stated goal of gating every main-agent LLM invocation._check_budget_before_invoke("main")immediately before the no-toolsainvokeandastreamcalls, or document why these paths are intentionally exempt.In-node checks cannot detect budget exhaustion caused by the current node
src/cleveractors/agents/retry.py,src/cleveractors/langgraph/pure_graph.py,src/cleveractors/agents/llm.pyretry.py:35–40(ContextVar defaults),pure_graph.py:543–572(_set_budget_context_for_node),llm.py:501–548(budget helpers)current_accumulated_costis set once to the graph’s pre-node_accumulated_costand is never updated as the node spends tokens. Consequently_check_budget_before_invokeand_should_skip_pruningonly catch budget exhaustion from previous nodes, not from earlier invocations within the same node. This means acceptance criterion (c) — “budget tripped mid tool-loop → no further pruning for that node” — is not literally satisfied for intra-node spend.Nits
Logging level inconsistency for the same condition
src/cleveractors/agents/llm.py:513,src/cleveractors/langgraph/pure_graph.py:594_check_budget_before_invokelogs atlogger.errorwhile_check_budget_pre_flightlogs atlogger.warningfor the same “budget already exhausted” situation.warningis probably more appropriate since budget exhaustion is a state/limit condition rather than a code fault.Duplicated
max_cost_usdparsing logicsrc/cleveractors/langgraph/pure_graph.py_set_budget_context_for_nodeand_check_budget_pre_flightboth parseself._limits.get("max_cost_usd")with identical bool-guard and float-conversion logic._get_max_cost_usd_limit() -> float | Noneto remove the duplication and reduce the chance of the two sites diverging.Summary
The PR correctly adds a hard pre-flight budget gate in
PureLangGraphfor all execution paths and wires pruning-skip logic intoLLMAgent. The core logic is sound and matches the ticket’s explicit scope for pruning-gate + zero-balance pre-flight. However, the streaming branches fail to reset the budget ContextVars infinallyblocks, which is a real state-hygiene bug that should be fixed before merge. Once the streaming reset is moved intofinallyand ideally the no-tools paths are also gated, the PR should be ready for approval.Pull request closed