Skip to content

Crossing the day cap stops running work, not only the next turn - #2364

Merged
AbirAbbas merged 31 commits into
app/v3from
c52/hard-cap-stop
Nov 11, 2026
Merged

AbirAbbas merged 31 commits into
app/v3from
c52/hard-cap-stop

Conversation

@santoshkumarradha

@santoshkumarradha santoshkumarradha commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Draft for the owner's review: this rule decides how much money a daily cap can let through.

What a person sees

When today's recorded spending reaches the daily cap (/budget day), every chat and crew stops together:

  • No new model calls start. A message sent after the cap is refused with no model call: "daily limit reached · $X spent of $Y · /budget day changes it".
  • Calls already replying finish. Their full cost is recorded. Cutting a call mid-reply saves nothing, because the provider bills it in full, and it left tool calls with no result in the transcript.
  • Calls still waiting for their first token are cancelled at $0.
  • Every chat whose work was stopped shows the daily limit notice once. That includes a chat that was idle while only its crew was working, and a crew whose planner finished without a worker.
  • A raise resumes work. After /budget day is raised, the chat takes a new message, and its transcript is valid: every tool call has its result.
  • Lowering the cap below today's spending while crews work stops new calls within one 100 ms poll.

A job budget and a person's Stop are unchanged: they still cut work at once.

How

  • Admission checks recorded daily spending before every model call: turns, retries, errands, crew workers and helper calls.
  • When the cap is crossed, a call that has had its first reply token is left to finish. The provider reports the first token through provider.WithReplyStarted.
  • A call that hasn't started replying is cancelled, and its cancel reason is the limit itself. Owned work (crews, tasks, background commands) then stops through the existing stop path.
  • The stop records the notice once, after the work has finished stopping.
  • The budget watcher polls the ledger only while capped work is moving. Starting a model call, a tool, a background command, a crew, a task step, a test harness run or a task belt wakes it.
  • An idle chat holds no timer, and a chat with no cap never polls.
  • The ledger's writer only bumps a counter, so it never sends into another goroutine's channel.

Idle cost

Measured on one machine, one run each: 5 minutes, four idle crews (each finished, nothing in flight), fake model, no network. CPU is measured in 10 ms steps.

Revision Caps set CPU seconds Context switches (voluntary/involuntary) Watcher wakeups
app/v3 job and daily 1.01 60963/185 12000
this PR job and daily 0.01 90/32 0
app/v3 none 0.01 98/0 0
this PR none 0.01 105/0 0

Live evidence

Each run: four chats, one crew each, all on deepseek/deepseek-v4.1-flash through OpenRouter for every role, with no fallbacks. The run is sealed in a fresh home and profile, with a $0.50 emergency limit and an outside stop line at $0.30. "Provider billed" is the provider's own receipt for each call, fetched by generation id.

Run Cap Recorded Provider billed Over the cap Calls cut Result
3 $0.02 $0.024757 $0.024757 $0.004757 0 mid-reply Every call stopped. One chat had no notice; that fault is fixed (planner finished without a worker).
4 $0.02 $0.031643 $0.031643 $0.007345 0 mid-reply, 0 before reply All four chats showed the notice. The chat resumed after a raise. Two crews were still planning at the crossing.
5 $0.009269, set once all four crews had a worker $0.026227 $0.026227 $0.000005 0 mid-reply All four chats showed the notice. Each of the 20 calls matched its receipt exactly.

Overshoot is the remaining cost of calls already replying when the cap was crossed. Up to 8 calls ran at once.

Fake tests, in internal/session and the fake path of cmd/codeaf/hard_cap_live_e2e_test.go:

  • One call waiting and one mid-reply at the crossing: the waiting call is cancelled at $0, and the replying one finishes and is recorded.
  • The cap is lowered while crews work, and when nothing is running.
  • A crew ends before its worker starts, before its planner call, and with its planner finished.
  • The notice appears once, and the chat resumes after a raise.

Limits

  • Overshoot has no fixed dollar bound. It is the remaining cost of every call already replying at the crossing, each up to its own token limit. In the four-call fixture that is $0.45 recorded against a $0.24 cap, a token-limit worst case. The live runs went over by $0.000005 to $0.007345.
  • A stalled reply can delay the stop by up to 2 minutes. The existing stream idle watchdog cuts it at that point.
  • A ledger write is noticed up to 100 ms late, while capped work is moving.
  • Usage reported mid-stream doesn't count; only recorded spending closes admission. The interim-usage overshoot ($0.31 over in TestInterimUsageStreamOvershootIsTheKnownLimit) stays as a pinned known limit.
  • The cap can reopen for up to 70 s on a resume while a receipt is pending. During that time the chat shows $0.00 recorded and stays "working". It says "everything running here was stopped, the reply with it", with no pending-receipt warning. When the receipt settles, the chat stops with the daily limit line.
  • The live test can't always arm the cap, because the planner sometimes plans no worker. In run 6, crew 2's planner ended with no nodes, so the cap never armed (177 s, $0.0915 recorded). In run 7, three crews had no worker at 60 s and two had ended with no nodes. Spend stopped at $0.028254 against an armed $0.033254, so the cap was never crossed. Spend matched the provider in run 7: $0.028254, with all 29 receipts found.
    • Runs 5 to 7 use the same product code; only the test changed. This is reported separately with a write-scope glob bug (planner scopes like crew-0-*.md match no file).
  • Whole-package test runs: internal/session still fails five tests that fail on app/v3 too: TestNoRoadInTheTaskEngineHasMoreEndingsThanItsLedgerRow, TestNoRoadInTheMemoryEngineHasMoreEndingsThanTheCeiling, TestTheFixedPrefixStaysUnderItsBudget, TestTheLeanPrefixStaysUnderItsBudget and TestProgramHoldClassifiesEveryRegisteredChatTool.

🤖 Generated with Claude Code

santoshkumarradha and others added 23 commits November 4, 2026 11:33
Retain measured spend until pending receipts settle and cancel detached
summary calls through StopWork. Re-read adaptive workers' owner day limit,
keep live stage samples provisional, and admit known-free helpers.

Preserve selected task authority and settled round refusals. Keep all
supplied regression assertions under plain test names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Retire measured progress when legacy billing banks it, retain each reading’s
local day for daily admission, and check the resolved HTTP model at the
transport gate so known-free helpers pass without admitting paid substitutes.

Preserve all six supplied regression assertions. Restore the date fixture’s
local zone after receipt and server cleanup to avoid a test data race.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Retire interim readings after legacy banking returns and track each later day from its prior cumulative reading. Preserve regression assertions and use a locked reading clock for race-safe midnight coverage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A ledger notification could latch workStopped before a turn admitted its
first provider call. An idle child also counted its parent task graph as
owned work, making Submit return a synchronous error depending on timing.

Watch active calls, tools and owned producers rather than the turn running
flag, and inspect only the agent own task graph. Deterministic Submit tests
cover both paths without provider calls. Keep existing cancellation timing
for running calls, crews and background commands.

Validation: focused reproduction count=30, new tests race count=3, go vet,
remaining hard-cap and wall-clock tests, source and packed manual checks.
Changelog check retains the branch existing two missing PR-number errors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove live readings while preserving ledger notifications, call cancellation and settlement. The unchanged measurement remains $0.07 past cap across five runs; retained HTTP day/job tests expose $0.31 overshoot when streams remain open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tool starts wake the budget watcher after a ledger crossing fell between a completed call and tool dispatch. Keep idle and pre-admission behavior without reading the daily ledger on the job clock. Pin interim-stream and pending-receipt limits, use final-chunk cancellation fixtures, and consolidate PR 2364 documentation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Share the nonblocking work-start wake between tool dispatch and successful
command reruns. An idle ledger wake can be consumed before a rerun starts;
the fresh wake checks recorded spending without polling the daily ledger.
Preserve the supplied rerun regression and document the corrected behavior.

Start-path audit: ordinary background commands, keep-running fallback,
watches, video and music render starts pass through executeTool. Bash
promotion adopts a process already started through that tool boundary.
Task children, quick workers, checkers, merge helpers and belt seats use
guarded provider admission with the selected daily authority. Adaptive
crews check admission before launch and again at their provider boundaries;
child-owned crews retain their own cancellation watcher. Kept services
transfer ownership to the service manager rather than remaining chat jobs.

Validation: supplied regression failed before the fix and passed after it;
requested focused group passed three repetitions without stalling; session
vet and focused packed-manual/visible-string checks passed. No live model
calls, whole-tree tests or pushes were performed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s it

Hard cap checks the caller's context before each rung, so an errand cut by
its caller's deadline returned before the ladder wrote its failure row.
Write the row at that check; a cancel and a cap refusal still write none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ility

A crew whose first call the cap cut at $0 still ran; at least two crews must
have paid. Receipts are retried until the run's own deadline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cancel calls still waiting for their first reply token, drain replies before parent cancellation, and persist budget notices through the shared stop route. Propagate child budget refusals before an idle owner can discard its wake.

Correct receipt reporting after the run deadline and distinguish tool-result display rows from unanswered calls. Cover four fake v3 crews, interrupted transcripts, and resumption after a raise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Memory fixtures started process writers outside their bubbles while agents registered bubble-owned watcher channels. The usage-close fixture had the same mismatch. Keep memory writers private to each bubble, and construct the shared-writer fixture's agent outside while closing it and cleaning it up inside. Preserve all existing assertions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
santoshkumarradha and others added 6 commits November 5, 2026 05:01
Wake the idempotent watcher at every owned producer's start while keeping
process-wide ledger notifications atomic-only. Retain each observed owner's
epoch-bound daily stop across reply drain, including its cancellation cause.

Start owned work before the stale-sample test and preserve known-free model
exemptions in progress tracking. Leave cancellation to the provider transport
so uncapped helpers keep their existing cleanup path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A finished adaptive run becomes idle before the budget watcher can observe a
recorded crossing. A four-crew fake reproduced an empty transcript for the
owner whose planner finished without a worker.

Check recorded daily spending when the run returns, using its captured work
epoch and the existing stop path. Keep reply draining, notice deduplication,
and idle watcher sleep unchanged. Cover worker and planner admission refusal,
finished planners, and submission after raising the cap. Add per-chat transcript
tails and orchestration snapshots to the live wait's failure diagnostics.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rd-cap-simple

# Conflicts:
#	internal/session/job_budget.go
#	internal/session/stopwork.go
Start the live profile at $0.40, then lower its daily cap to ledger spend plus $0.005 after every crew has an admitted worker call. Record the armed cap and time for crossing checks and receipts, and exercise the shared arming path with the local recorder fixture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remember the selected daily cap in the active budget watcher so profile-only decreases trigger the existing recorded-spend check without another receipt. Keep idle polling disabled and preserve first-token draining.

Add fake-clock crew and idle regressions using profile writes, provider admission timestamps, cancellation, one-time settlement, owner notices, and resumed messages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
One shared receipt window let the first slow receipt use it up, so later
receipts were reported missing although the provider had billed them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
santoshkumarradha and others added 2 commits November 5, 2026 06:35
A planner may plan no worker; that is the model's choice. Arm once three crews
have an admitted worker call or after 60 s. A crew whose run already ended must
refuse its next message at the daily limit without a model call; at most one
crew may lack a worker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@AbirAbbas
AbirAbbas merged commit 70df24f into app/v3 Nov 11, 2026
1 check passed
@AbirAbbas
AbirAbbas deleted the c52/hard-cap-stop branch November 11, 2026 17:42
AbirAbbas added a commit that referenced this pull request Nov 11, 2026
…16 of 22) (#2597)

* app tests: B2 recovery must show its worker's answer, not only a settled state (#2198)

* Typing into your own idle chat reopens it instead of saying it's available (#2469)

* app: answered receipts and quiet notices disappear after relaunch (#2586)

* A big move from the hosted relay goes through; a move sync answered with an error says so (#2366)

* tests: FIFO and Unix-helper cases build for Windows; make vet checks the Windows test build (#2192)

* session: split the task and memory roads back under the endings ceiling (#2149)

* Book a tool completion once when the process dies between seal and WAL cleanup (#2377)

* Keep waiting job actions from going stale on bookkeeping (#2463)

* factory: keep close revision checks strict after action history merge

* Spending: daily rollup for date-only spend.report (#2269)

* Retain Library activity in the rollup byte budget during replay

* Keep billing facts and missing receipts when taking a chat (#2386)

* Retain the Library receipt helper while replaying the billing merge

* session: retain Library activity on sealed missing-receipt rows

* An idle job chat stops reading every job ten times a second (#2358)

* Set the explicit Memory-off premise in the idle discovery fixture

* agentdid: add encrypted custody, purpose-bound signing and v1 identity documents (#2090)

* Idle factory workers wait for changes instead of re-decoding the store (#1931)

* store: distinguish file identity stamps from shared cache stamps

* factory: bind retained caches to complete file identity and avoid duplicate pull beats

* Count unchanged-floor settlement passes without decoding jobs

* Recover usage rows after a crash without changing charges (#2387)

* session: keep journal appends in the usage funnel and back off by delay

* Crossing the day cap stops running work, not only the next turn (#2364)

* session: sample the opening job budget before idle admission

* Factory: compare failing Go tests with the base, and Accept as is (#2570)

* factory: retain strict revision guard when pausing recovery

* app: release the recovery-chat host lock through defer

* Keep explicit test completion rules and conflict ownership

* docs: record the local app/v3 integration wave

* tests: open the Knowledge offer with Memory explicitly off

* session: let the journal own projection durability until compaction

* tests: join routed receipt settlement before inspecting its charge

* tests: request the job-vault discovery passes that the fixture checks

* tests: arm the admission ledger probe after the startup snapshot

* fix(session): preserve free helper admission through shared daily gates (#2364)

* fix(factory): compare pinned failures through the command fence (#2570)

* changes: the app/v3 open-PR wave names its pull request

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* test(sync): pair shared fixtures before #2090 custody saves a solo identity

Custody now creates a quiet local profile on first save. Establish the shared fixtures paired premise before that save so Ensure does not preserve an unintended solo marker. Keep every notice, read-count, ownership, and explicit solo assertion.

* fix(factory): invalidate #2358 handover look before stale admission

The new cheap stop watcher saw a stopped job handed to a chat while the retained full admission memo trusted an older floor for 100 ms. Revalidate the shared floor identity before reuse. Keep unchanged document reads at zero and retain all allocation caps.

* test(factory): keep #2570 belt fixture outside its profile ancestor

The new PR-base tool test put codeaf state under its requested workspace, so dev correctly refused the Factory chat before any tool ran. Give the profile its own temporary directory while preserving the real tool call and repair assertions.

* fix(session): keep #2387 journal sync in its process writer scope

The durable journal created batch channels on recording callers, but the shared usage writer could send to them after that caller scope ended. The projection-fsync follow-up exposed fatal synctest sends in dev Memory cases. Start synchronizers from a separately joined writer-owned loop, retain independent batching under stalled projection, and keep all existing assertions and shutdown ceilings.

* fix(session): route #2570 base-sync arguments through the shared decoder

The new tool decoded its own arguments directly, violating dev’s common argument-decoder law. Reuse decodeToolArguments while preserving its empty-object and bound-checkout checks, existing refusal text, and every assertion. Existing structural and carried tool tests pass, with unchanged 208-byte/4-allocation successful calls.

* test(session): initialize stalled journal fixtures through the writer owner

The journal-scope repair made the process writer own a joined synchronizer. Three dev fixtures still built raw writers and skipped that initialization, panicking at close. Reuse the existing constructor before installing their projection blockers. Keep every assertion, shutdown ceiling, and all 200 by 4 close/flush race iterations; no production source changes.

* test(app): end the stray child portably so the Windows test build vets (#2192)

#2192 makes `make vet` check the Windows test build. The one-engine test
that landed with app/v3 ended its stray child with syscall.Kill, which
does not exist on Windows, so the new vet step failed on dev's tree.
os.Process.Kill sends the same signal on Unix and builds everywhere.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
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.

2 participants