Skip to content

Hierarchical budgets: min(child, parent) with forced wrap-up (off by default) - #206

Merged
BaaRai merged 3 commits into
mainfrom
feat/hierarchical-budgets
Nov 12, 2026
Merged

BaaRai merged 3 commits into
mainfrom
feat/hierarchical-budgets

Conversation

@BaaRai

@BaaRai BaaRai commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Design

  • Calculator: agent.EffectiveBudget(own, parentRemaining Budget) Budget (agent/budget.go), the per-dimension min. Budget{Tokens, Turns}, where Unlimited (= math.MaxInt64) means no cap. A child gets min(own budget, parent remaining above the wrap-up reserve).
  • Levels:
    • Task: tokens and turns. One in-memory BudgetLedger per task, in Engine.budgets.
    • Intent / worker run: an IntentMeter. Its effective budget is min(per-intent budget, task remaining above the reserve), re-evaluated on every call.
    • Planner round: its calls are counted inside the task.
  • Counting: the Recorder feeds a ctx usage sink (llmrec.WithUsageSink) with the same llm.Usage value it writes to llm_usage, at the same point, so the counters see the calls that get a row, and also calls with no recorder (the sink runs before the PostgreSQL check). Each metered call is one turn. Tokens = input + output. norma's normalized InputTokens already contains the cache read/write buckets, so those buckets are not added again and each token is counted once.
  • Enforcement points:
    • server/engine.go: plannerLoop/runRound → Engine.budgetStop. It logs the remaining budget at every round. Once no worker is affordable, it starts the forced wrap-up exactly once (BudgetLedger.BeginWrapup) through the existing settle sequence: settleTask(ctx, t, budget=true).
    • server/engine.go: workerLoop → Engine.budgetBlocksClaim. No new worker is dispatched (no intent claimed) while the budget does not allow one.
    • server/engine.go: runIntent → Engine.budgetIntent meters the run and caps it two ways:
      • Turns: the worker's MaxTurns is clamped to the run's effective remaining turns (Worker.turnCap), so the existing settlement wrap-up runs when the cap is hit.
      • Tokens: once the run is exhausted, steerHooks.PreToolUse refuses every tool except record_fact/insert_assets/report_finding and returns a wrap-up instruction. The worker records its facts and ends with its summary; there is no hard cut.
  • Wrap-up reserve: max(5% of the task budget, floor) with BudgetMarginPercent = 5, BudgetMarginMinTokens = 20_000, BudgetMarginMinTurns = 2. At or under the reserve, dispatch stops. The final planner round gets a code-owned wrap-up instruction appended to its situational block, the same way the endgame tc.Final words are (plannerBudgetBlock): final goal judgment, no new intents, one-line summary.
  • Planner dispatch rule: no worker is dispatched when the remaining task budget is below the cost estimate of one worker run. The estimate is the average spend of the finished worker runs in this task. Before any worker has finished it is the conservative constant DefaultWorkerEstimateTokens = 50_000 / DefaultWorkerEstimateTurns = 10. It is never above the per-intent cap.
  • Planner context: one line every round, e.g. [Task budget] remaining: tokens 120000 of 500000, turns unlimited (wrap-up reserve: 25000 tokens, 0 turns). The same line is logged as [budget] task N planner round: ....
  • End state: the run ends with one system activity Task run budget exhausted: forced wrap-up done, task stopped. The persisted task status reuses the existing terminal states: done if the final judgment met the goals, otherwise timeout. No new status value is added.
  • Env: ARTEX_TASK_BUDGET_TOKENS, ARTEX_TASK_BUDGET_TURNS, ARTEX_INTENT_BUDGET_TOKENS, ARTEX_INTENT_BUDGET_TURNS. The default is 0 or unset, which means unlimited. With all four unset, no ledger is created and every hook is a no-op: no behaviour change.

What is NOT done

  • No UI.
  • No defaults chosen. The defaults will be decided after measurement.
  • No persistence. The ledger is in memory: a process restart (or a revive of a finished task) starts a fresh budget. No table was added and none was needed for this scope.
  • No dedicated budget_exhausted task status. It would touch about 8 SQL status lists, revival and notifications, and the UI type. As a result, a budget-exhausted run that did not meet its goals shows as timeout and fires the existing timeout notification.
  • No turn clamp on a planner round itself. Its calls are counted and stopped at the round boundary.
  • A tool call that is already running when the wrap-up starts is not interrupted. The existing 90 s settle drain grace applies.
  • Not verified end to end with a real LLM. The quality of the wrap-up is not measured.

Tests

  • TestEffectiveBudgetNeverExceedsParent (agent): the calculator never exceeds the parent's or its own budget, including the unlimited and exhausted cases. Through the meter, a 100k intent budget is cut to the task's remaining above the reserve, and the worker MaxTurns is clamped to the intent's turns.
  • TestWrapupMarginTriggersOnceAndStopsDispatch (agent): the reserve is 5% or the floor. One token above the reserve, dispatch is on; at the reserve, dispatch stops. Repeated wake-ups start the wrap-up exactly once. A running worker is then held to its write-back tools. The planner wrap-up block contains the instruction exactly once, plus the remaining line.
  • TestDispatchStopsUnderOneWorkerEstimate (agent): dispatch stops one token under the default estimate, and one token under the average of finished worker runs, while still above the reserve.
  • TestBudgetUnsetIsPassthrough (agent): unset, 0 or invalid env gives no ledger. The planner round input is byte-identical with and without the budget path, and worker MaxTurns is unchanged.
  • TestEngineBudgetPassthroughAndGate (server): with the env unset, no round is stopped, no claim is blocked, contexts are returned untouched and no tool call is refused. With a task budget set, the claim is blocked below one worker's estimate and an exhausted run gets the wrap-up instruction while record_fact stays allowed.
  • TestBudgetCountsMatchUsageFixture (agent): the token and turn counters match a fixture of usage rows (cache buckets counted once, an errored zero-usage row counted as a turn), along with the per-worker estimate and the remaining budget.
  • TestUsageSinkSeesMeteredCalls (llmrec): the sink receives each streamed and non-streamed call once, with the same usage the llm_usage row gets. A zero-token call with no model is not seen (no row, no sink call).

Review fixes (commit 4cde1a8)

  • Revive after a budget wrap-up: a done/failed task revived to running cleared only the timeout path's settle state, so its old settling flag and wrap-up ledger still gated the planner and the workers. resetSettledRun now clears settling and the ledger; resetTimeoutRevival calls it, and server/goals.go calls it for any wasTerminal revive. Test: TestResetSettledRunRestartsBudget.
  • Config: docker-compose.yml passes the four variables through (they were dropped by the explicit environment list). .env.example and README document them.
  • llmrec: the usage sink runs before the PostgreSQL check, so it also sees calls with no recorder. The comment said otherwise; corrected.
  • BudgetWrapupBlocks allows update_finding_report, so a worker can amend a finding during the wrap-up.

Config

Variable Meaning
ARTEX_TASK_BUDGET_TOKENS, ARTEX_TASK_BUDGET_TURNS Cap on the whole task (planner rounds and all workers).
ARTEX_INTENT_BUDGET_TOKENS, ARTEX_INTENT_BUDGET_TURNS Cap on one worker run.

Unset or 0 is unlimited. Practical floor: a worker is estimated at 50000 tokens / 10 turns, and the wrap-up reserve is max(5%, 20000 tokens) / 2 turns. Below 50000 tokens a task starts no worker; from 50000 to about 70000 it typically gets one worker, then the wrap-up. Budgets live in memory: a restart or a revive starts a fresh budget.

Note on the test list above: TestUsageSinkSeesMeteredCalls covers the zero-token, no-model filter (such calls skip both the sink and the row). It does not cover r.pg == nil.

… by default)

Per-level token/turn budgets: task -> intent (worker run) -> planner round
(counted inside the task). A child's effective budget is
min(own budget, parent's remaining above the wrap-up reserve). When the task
can no longer afford one worker, workers stop claiming intents and the task
settles through one forced wrap-up planner round (the existing settle
sequence, budget words instead of the timeout words).

Config: ARTEX_TASK_BUDGET_TOKENS, ARTEX_TASK_BUDGET_TURNS,
ARTEX_INTENT_BUDGET_TOKENS, ARTEX_INTENT_BUDGET_TURNS. 0 or unset = unlimited;
with all four unset nothing changes.
…e_finding_report in wrap-up

- resetSettledRun clears settling and the budget ledger; a done/failed task
  revived to running now plans and claims again (was gated by the old wrap-up).
  resetTimeoutRevival calls it. Test: TestResetSettledRunRestartsBudget.
- docker-compose.yml passes the four ARTEX_*_BUDGET_* variables through.
- .env.example and README document the variables, the wrap-up, the in-memory
  ledger and the practical floor.
- llmrec: the usage sink runs even without a PostgreSQL recorder; comment fixed.
- BudgetWrapupBlocks allows update_finding_report.
@BaaRai
BaaRai merged commit afa6f4f into main Nov 12, 2026
3 checks passed
wxcvm referenced this pull request in wxcvm/ARTEX Nov 14, 2026
…ration (#86)

* feat(runtime): optional hierarchical budgets and knowledge binding migration

Adapt upstream #206 to the fork's transition lock, deadline settlement and revival semantics. Default unlimited; retain existing tool bindings except legacy enabled defaults.

* test(runtime): cover budget lifecycle and legacy binding migration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant