Repository navigation
Conversation
A worker session is one Ticket in docs/dsh-super-agent.md, but the MCP
surface re-granted AGENTDESCENT_MAX_CALLS to every start: with the ceiling
at 1, two starts each ran one call and the Ticket billed two.
The server now counts the calls its earlier runs charged (calls plus
pending_calls, read from the store) against the ceiling, clamps a second
start to the remainder, reports call_limit.ticket {ceiling, spent,
remaining} when there is earlier spend, and refuses a start once the
Ticket's ceiling is spent, naming the variable and the arithmetic.
Shape stability: a fresh session's first run reports exactly the payload it
reported before this key existed; a caller's own max_calls=0 is not the
spent-Ticket case.
The server reported what the Ticket had left but launched the child with the caller's raw cap, and `runstore.launch` clamps only against the full operator ceiling (`_clamped_max_calls`), never against the remainder -- so a second `start` ran the ceiling again while the reply said "1 left" (#1082). `resume` never consulted the Ticket at all: no clamp, no registration, no charge. Both entry points now share one gate under a lock: read the spend, clamp to the remainder, launch with the number the reply shows, and register the run so it is charged until it reports. A launched run holds its cap as a reservation, because `pending_calls` is 0 until the child writes status and two overlapping starts would otherwise both take the remainder. For a resumed run the cap is the ledger plus the remainder, since the child counts the ledger it resumes. `runstore.cancel` also clears `pending_calls` with the cancelled state, so a run stopped mid-call no longer holds a phantom charge against its Ticket.
Names the two limits the fix relies on: a run the server did not start is not charged to the Ticket unless it is resumed here, and AGENTDESCENT_MAX_CALLS is the only operator ceiling, per Ticket, while a caller's max_calls / max_usd stay per-run flags (#1082).
`_ticket_spent` counted a run whose status cannot be read as 0 calls, so a store that lost one run handed the next run the whole remainder -- the same overspend the Ticket exists to stop. It now raises, naming that run, and both `start` and `resume` answer with the sentence instead of granting a remainder computed over an unknown ledger (#1082). `_ticket_open` also catches the `SpecError` from `_call_limit_payload` again: moving the read under the lock had put it outside `start`'s own `except SpecError`, so `max_usd` without `usd_per_call` escaped as a traceback instead of the `ok: false` refusal `#1196` specifies.
…iling `resume` added the run's ledger to the Ticket remainder unconditionally. For a run this server started that ledger is already inside `spent`, so the sum stays inside the ceiling -- but a run it did not start is not in `spent`, so the reply said `remaining + ledger` (4 for a ceiling of 3), `launch` clamped the child back to the ceiling, and the two disagreed: the grant mismatch this branch removes for `start`, re-entered through `resume`. With one call of this server's own already spent, the resumed external run could then bill the ceiling twice (Ticket 4 of 3). `_ticket_open` now takes `registered`: a known run is relaunched with its ledger plus what is left, an unknown one with the remainder itself, its earlier calls counted inside that number, and it is refused by name when that ledger already fills the remainder. The reservation is the grant, so the external run is charged from the remainder rather than from remainder plus ledger (#1082). The docs and the changelog fragment say the same, including that a resumed external run's whole ledger becomes charged.
`resume` reads the run's status in its pre-gates (`require_resume_not_solved`, `require_resume_not_quota_exhausted`, `require_resume_host_on_path`) before the Ticket gate does, so a corrupt `status.json` raised `JSONDecodeError` straight out of `Tools.resume` -- while the docs and this branch's body say `start` and `resume` both answer `ok: false` when a run cannot be accounted. Those reads now turn `ValueError`/`OSError` into the same refusal sentence `_ticket_spent` raises, naming the run; a missing run stays a `RunStoreError` as before. The remedy in that sentence is corrected too: deleting the run directory does not free the budget, because `runstore.get` then reports no run and the Ticket refuses for the rest of the session. It now says to restore a valid `status.json` or start a new server session, and the docs say the same for `start`, `plan` and `resume`.
The wrap that turns an unreadable status into a refusal also caught the gates' own SpecError, which subclasses ValueError: a solved run, a spent quota and a missing plugin host were rewritten as "cannot be accounted" and told to restore a status.json that was fine. Re-raise SpecError before the (ValueError, OSError) branch in both wraps so it keeps its sentence.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1213.
What changed
The first tip of this branch carried two different faults. This PR fixes the
first and records what the second was checked to be.
(a) Grant mismatch — the fault this PR fixes. The reply said what the Ticket
had left, but
Tools.startlaunched the child with the caller's rawmax_calls(
agentdescent/mcp.py:873-875at115edc74), andrunstore.launchclamps onlyagainst the full operator ceiling, never against the remainder
(
_clamped_max_calls,agentdescent/runstore.py:153-171). With a ceiling of 3and 1 call spent, the reply said
remaining: 2while the child's--max-callswas 3, so the Ticket billed 4.resume(mcp.py:930-950at thattip) never consulted the Ticket at all: no clamp, no registration, no charge.
(b) Accounting — checked, single-counted.
_ticket_spentsumscalls + pending_calls(mcp.py:570-598), and the two are disjoint:pending_callsislen(Usage._inflight)(agentdescent/agents.py:93-95) andUsage.recordincrementscallsonce per call (agents.py:166-191), withrunstore's_progresswriting both from the sameUsage. So the "Ticket 4of 3" figure reported for
startis the consequence of (a), not a secondaccounting error. The other path that could reach it —
resumegranting a runremaining + ledgerwhen that ledger is not inspent— is closed in this PRtoo: (a) has two entry points,
startandresume, and neither can grant morethan the ceiling now. (b) stays checked and single-counted.
Both entry points now share one gate:
Tools._ticket_lock,_ticket_openreads the spend and returns theenforced cap —
min(caller, remaining), orremainingwhen the caller namesnone — and the child is launched with that number, so the reply and the child
cannot disagree.
call_limit.sourcestill namesAGENTDESCENT_MAX_CALLSwhen the ceiling bound the run,max_calls_requestedstill carries the caller's number, and the run's own
stop_detailsays thesame thing.
_ticket_reserveregisters a run and the calls it holds: an unfinished runcounts as at least its applied cap (two overlapping starts can no longer both
take the remainder), and a finished run is charged what it used, giving the
rest of the Ticket back. A resumed run is relaunched with
ledger + remaining, because the child counts the ledger it resumes, and registrationis idempotent (membership check, not a bare append) so one run is never
summed twice.
resumeis gated the same way: a spent Ticket refuses it with the samesentence as
startinstead of relaunching at the full ceiling. A run thisserver started is relaunched with its ledger plus the remainder
(
_ticket_open(..., registered=True): that ledger is already inspent, sothe number stays under the ceiling and the reply matches the child). A run it
did not start is relaunched with the remainder itself, its earlier calls
counted inside that number (
registered=False), and refused by name when thatledger already fills the remainder — otherwise the reply would say
remaining + ledgerwhilelaunchclamps the child back to the ceiling, thesame mismatch this PR fixes for
start. Behaviour change: an external run isregistered into the Ticket when it is resumed here and its whole ledger is
charged from then on; its grant is the remainder itself, and a ledger that
already fills the remainder is refused by name instead of relaunched.
runstore.cancelwritespending_calls=0with the cancelled state, so a runstopped mid-call no longer holds a phantom charge against its Ticket
(one-line fold, reported by Reviewer).
_ticket_spentraises, naming that run, and both
startandresumeanswerok: falsewiththat sentence instead of granting a remainder computed over an unknown ledger.
A store that lost one run must not hand the next run a budget that may already
be gone.
resume's own pre-gates read the run's status before the Ticket gatedoes, so they turn a corrupt
status.jsoninto the same refusal instead of aJSONDecodeError, and the remedy line says to restore that file or start a newsession -- deleting the run directory does not free the budget. A run the
store can read keeps its own refusal: a solved run, a spent quota or a
missing plugin host still answers with that reason, because the gates'
SpecErroris re-raised ahead of the unreadable-status catch instead ofbeing rewritten as
cannot be accounted.max_usd-without-usd_per_callrefusal is raised inside the lock andcaught by
_ticket_open, sostartandresumeboth returnok: false,behaviour identical to
#1196(planalready caught it).The ceiling is the session's, and shape stability holds: a fresh session's first
run returns exactly the payload it returned before
call_limit.ticketexisted.Not in this PR: the store as the Ticket (a store-wide aggregate would cap
campaign and pilot runs that legitimately share one),
max_concurrency, and theUSD ceiling question —
AGENTDESCENT_MAX_CALLSis the only operator ceiling andit is per-Ticket, while a caller's
max_usdstays a per-run flag. A run theserver did not start and never resumes is not charged to the Ticket, so mixing
CLI and MCP runs inside one session is outside this accounting. Those stay open
on
#1082.7 files, +837/−41. The doc sentences the fix relies on are in
docs/dsh-super-agent.md: only the runs this server started are charged (anunregistered run is outside the accounting unless it is resumed here, and once
resumed its whole ledger is charged while the child stays clamped by the
absolute ceiling),
resumeis held to the same remainder with the two grantshapes named, and
AGENTDESCENT_MAX_CALLSis the only operator ceiling, perTicket, while a caller's
max_calls/max_usdstay per-run flags.Reads at this tip
Two independent reads name
18c333d935e0aed1cde07fb6e89ab267ed62156c. They are recorded here because neither is posted on GitHub.AgentDescent Test) —Blocking: none. Fresh clone at the tip (repo=tip,prev=27de7b67,base=1aa816e0). New file 14 rows 14 passed; the same file on27de7b67gives 3 failed, 11 passed, exactly the three external-resume rows. Twelve-file focused sweep 220 passed. Probes: external resume at ceiling 3 with 1 call already made -> replymax_calls: 3== child cap3, two new calls,count(rid)==1,_ticket_spent()==3equal to a hand sum; a ledger that already fills the remainder -> refused by name with nopidand the run directory 1 -> 1; registered resume -> reply2== child2, total3; destroyedstatus.json->startandplanbothok:false, naming the run, containingcannot be accounted, directory 1 -> 1;max_usdwithoutusd_per_call-> refused with the argument named and the store not created. CI at the tip: 10 of 10 (fivetestlegs,build,otel-wire, two report-only),deployskipped.AgentDescent Security) —Blocking: none. Delta27de7b67->tip: 1 commit, 2 files+49/-0(mcp.py +10/-0=except SpecError: raiseahead of the(ValueError, OSError)wrap in both gates;+39/-0of tests, two rows). Regression R1-R4: a solved run, a spentQuotaExhausted,SubscriptionInactiveand a missing plugin host each return their own sentence word-for-word, none containingcannot be accounted; the same detector is red 4 of 4 at27de7b67. Numbers at the tip: S12/2/3, S22/2/3, S32+1, S4 reply2/ child delta1/ spent3, S7 duplicate reserve is a no-op then the second resume is refused (3 calls over 2 runs), E1 reply3== child3, E2 and E3 refused by name with the run untouched, S8startandplanok:false, S9resumeok:falsewith the status file's bytes andst_mtime_nsunchanged, C1 says restore a validstatus.jsonor start a new session and does not say "remove that run directory". Delta hygiene: no env, secret, installer or workflow line; no newenviron/getenv/subprocess. Repo rows at the tip:test_mcp_ticket_cap.py17 passed,test_runstore_cli.py51 passed.The third read is outstanding, and these two are not a substitute for it.
Verification
Tip SHA:
18c333d935e0aed1cde07fb6e89ab267ed62156c(branchagent/1082-ticket-cap, no force-push).Red first, at
115edc74with only this branch's test files present:6 failed, 3 passedintests/test_mcp_ticket_cap.py. The six are the overrunassertions, not reply equality:
test_second_run_is_clamped_to_what_the_ticket_has_left—assert 2 <= 1:the child runs 2 calls where 1 was left, so a ceiling of 2 bills 3.
test_a_second_start_with_no_cap_spends_only_the_remainder—assert 3 <= 2: a secondstartwith no cap of its own runs 3 of a2-call remainder, so a ceiling of 3 bills 4.
test_a_started_run_reserves_its_cap_before_it_spends—assert 0 >= 3:_ticket_spent()is 0 right after a start, before the child writes status.test_a_finished_run_gives_back_what_it_did_not_spend—assert 0 == 20.test_two_starts_at_once_cannot_both_take_the_remainder—assert 2 == 1:both concurrent starts are admitted and hold the full ceiling each.
The Ticket total is asserted on its own, separately from the per-child cap:
assert total == 3after both threads join intest_two_starts_at_once_cannot_both_take_the_remainder(tests/test_mcp_ticket_cap.py),i.e. one session's accounting can never exceed the ceiling no matter how many
runs it admits — the per-child
--max-callsassertion and this one failindependently.
test_a_resumed_run_is_charged_to_the_ticket—KeyError: 'call_limit',then the resumed child relaunches at the ceiling: A goes 1 → 3 and the
Ticket bills 4 of 3.
tests/test_runstore_cli.py::test_cancel_clears_a_pending_callat115edc74:assert 1 == 0, the cancelled run keeps its in-flight call.Two more rows are red at the previous tip,
a0b073b37076ab0653de4dbc686e4f2f45839a11:test_an_unreadable_run_refuses_instead_of_granting_the_rest(new in thistip) —
assert refused["ok"] is False: with one run'sstatus.jsondeleted,startreturnsok: trueand grantsmax_calls: 3, the whole ceiling, overa run whose spend nobody can read;
planreports the same remainder.tests/test_max_usd_refusal_hint.py::test_a_tool_refusal_names_the_argument_it_can_pass— red on
a0b073b370's CI (test (3.11),test (3.12)):SpecErrorescapedTools.startas a traceback instead of theok: falserefusal whose messagenames
usd_per_call. Moving the_call_limit_payloadread under the lock hadput it outside
start's ownexcept SpecError.Three more rows are red at
8ee4d7da806d3cdf88073ef1cc67174743108d69:test_a_resumed_external_run_cannot_exceed_the_ceiling(new) —assert resumed["call_limit"]["max_calls"] == 3->{'max_calls': 4, ...}/assert 4 == 3: the reply adds a ledger that is not inspent, whilelaunchclamps the child to the 3-call ceiling.test_a_resumed_external_run_is_charged_inside_the_ceiling(new) —assert resumed["call_limit"]["max_calls"] == 2->{'max_calls': 3, ..., 'ticket': {'ceiling': 3, 'spent': 1, 'remaining': 2}}; the resumed childthen spends 2 more and
_ticket_spent()is 4, so the Ticket bills 4 of 3.test_a_resumed_external_run_with_no_room_is_refused(new) —assert refused.get("ok") is False-> a relaunch dict carryingcall_limit.max_calls: 6: a run whose ledger already fills the remainder isrelaunched instead of refused.
Two more rows are red at
bb08b16e4125228400dbf4e377c6e3e71ed99c22:test_resume_refuses_when_the_run_status_cannot_be_read(new) —Tools.resume(rid)raisedjson.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)out of the callinstead of an
ok: falserefusal naming the run.test_an_unreadable_run_refuses_instead_of_granting_the_rest(control lineadded in this tip) — after
rmtreeof a spent run's directory the refusalstill said "Fix or remove that run directory, then retry"; it has to say to
restore a valid
status.jsonor start a new server session, because deletingthe directory leaves the Ticket unable to verify the freed budget.
Two more rows are red at
27de7b67124cdc6ad7764e81e7ffbeac3eaae333:test_a_solved_run_still_refuses_as_solved_not_unreadable(new) —assert 'cannot be accounted' not in 'run … cannot be accounted: its status cannot be read (cannot resume …: it already reached its target (done [target_reward]) …) … Restore a valid status.json, or start a new server session.'— the solved-run refusal was rewritten as an unreadable store,naming the wrong cause and the wrong remedy; the file is readable.
test_a_quota_spent_run_still_refuses_as_quota_not_unreadable(new) —same rewrite for
failed on QuotaExhausted …. Both refusals areSpecError,which subclasses
ValueError(evolvespec.py:213), so the wrap for anunreadable status had caught them.
Ran at the tip:
pytest -q tests/test_mcp_ticket_cap.py-> 17 passedtests/test_mcp_ticket_cap.py+tests/test_resume_solved_run.py+tests/test_resume_host_cli.py-> 30 passedtests/test_resume.py+tests/test_mcp.py+tests/test_runstore_cli.py->90 passed, 6 skipped
tests/test_resume_quota_exhausted.py+tests/test_mcp_call_limit.py+tests/test_max_usd_refusal_hint.py+tests/test_quota_exhausted.py->28 passed
python -m tools.gen_api_docs --check->docs/api.mdis up to datepython -m tools.changelog_fragments check-> 15 changelog fragment(s) OKmkdocs build --strict-> rc 0 in 11.62 s with thesocialplugincard rendering off on this host; CI's
buildjob runs the unmodified configNot run:
offline run is 8000+ cases; the earlier first-tip run reported its red set as
identical to base. The twelve-file
test_mcp*+ resume sweep (236 passed,9 skipped) was run at the previous tip
27de7b67; this tip changes only thetwo
exceptclauses, and the four groups above cover every gate they wrapskill_dirfixture