From 22d848697a87e2ebc1e013252408ebba4663624b Mon Sep 17 00:00:00 2001 From: HugoXK Date: Sat, 21 Nov 2026 01:39:52 +0000 Subject: [PATCH 1/7] feat(mcp): spend the operator ceiling per Ticket, not per run (#1082) 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. --- agentdescent/mcp.py | 86 ++++++++++++++++++--- changelog.d/1082-ticket-call-cap.md | 5 ++ docs/dsh-super-agent.md | 6 ++ docs/plugin-design.md | 7 +- tests/test_mcp_ticket_cap.py | 115 ++++++++++++++++++++++++++++ 5 files changed, 206 insertions(+), 13 deletions(-) create mode 100644 changelog.d/1082-ticket-call-cap.md create mode 100644 tests/test_mcp_ticket_cap.py diff --git a/agentdescent/mcp.py b/agentdescent/mcp.py index c5d879de..9d66e4a2 100644 --- a/agentdescent/mcp.py +++ b/agentdescent/mcp.py @@ -33,7 +33,7 @@ import json import os import secrets -from typing import Annotated, Any, Dict, Optional, Sequence, Tuple +from typing import Annotated, Any, Dict, List, Optional, Sequence, Tuple from . import __version__, runstore from .cli import (NESTED_ENV, NESTED_REFUSAL, apply_with_target, demo_payload, @@ -432,8 +432,9 @@ def _with_probe(payload: Dict[str, Any], spec: EvolveSpec) -> Dict[str, Any]: def _call_limit_payload(max_calls: Optional[int], max_usd: Optional[float], - usd_per_call: Optional[float]) -> Optional[Dict[str, Any]]: - """The run-level cap an MCP ``plan`` / ``start`` will enforce, or ``None`` (#1184). + usd_per_call: Optional[float], *, + spent: int = 0) -> Optional[Dict[str, Any]]: + """The cap an MCP ``plan`` / ``start`` will enforce, or ``None`` (#1184, #1082). Validated by the same :func:`~agentdescent.evolvespec.build_call_limit` the CLI and the run store use, so a bad number -- and a ``max_usd`` with no @@ -446,6 +447,13 @@ def _call_limit_payload(max_calls: Optional[int], max_usd: Optional[float], binds, the same distinction ``AGENTDESCENT_MAX_CALLS_REQUESTED`` carries into the child: without them a host cannot tell "the ceiling lowered your 9 to 2" from "you asked for 2". + + ``spent`` is what this Ticket's earlier runs already charged (``#1082`` + row 2). The ceiling is a Ticket budget, not a per-run number the worker can + ask for again: the second run of one worker session is clamped to what is + left, and ``ticket`` reports the arithmetic so the host can show it. A + worker that runs outside an MCP server -- a plain CLI ``evolve`` -- passes + no ``spent`` and keeps the per-run ceiling ``runstore.launch`` applies. """ limit = build_call_limit(max_calls=max_calls, max_usd=max_usd, usd_per_call=usd_per_call) @@ -455,13 +463,22 @@ def _call_limit_payload(max_calls: Optional[int], max_usd: Optional[float], enforced = None if limit is None else limit.max_calls payload: Dict[str, Any] = {"max_calls": enforced, "max_usd": None if limit is None else limit.max_usd} - if ceiling is not None and (enforced is None or ceiling < enforced): - # A run that names no cap still gets the ceiling -- and then the reply - # has to say so, or `start` would look unbounded while it is capped. - payload["max_calls"] = ceiling - payload["source"] = runstore.OPERATOR_MAX_CALLS_ENV - if max_calls is not None: - payload["max_calls_requested"] = int(max_calls) + if ceiling is not None: + remaining = max(0, int(ceiling) - max(0, int(spent))) + if spent > 0: + # Shape stability: a fresh session's first run hears exactly what it + # heard before this key existed; only a Ticket with earlier spend + # reports the arithmetic nobody could otherwise see. + payload["ticket"] = {"ceiling": int(ceiling), "spent": int(spent), + "remaining": remaining} + if enforced is None or remaining < enforced: + # A run that names no cap still gets the ceiling -- and then the + # reply has to say so, or `start` would look unbounded while it is + # capped. Same for what earlier runs of this Ticket left. + payload["max_calls"] = remaining + payload["source"] = runstore.OPERATOR_MAX_CALLS_ENV + if max_calls is not None: + payload["max_calls_requested"] = int(max_calls) return payload @@ -502,6 +519,10 @@ def __init__(self, store: Optional[str] = None, *, #: The host's own CLI (`claude_code`, `codex`, `dsh`, `opencode`), from #: the name it sent at `initialize`. The fallback route for `host_model`. self.host_cli: Optional[str] = None + #: Runs this server started: one worker session is one Ticket, so the + #: operator ceiling is spent across them instead of re-granted per run + #: (#1082 row 2). Empty on a fresh server. + self._ticket_runs: List[str] = [] def host_model_env(self) -> Dict[str, str]: """What a launched run needs to reach the host's model, by either route. @@ -519,6 +540,26 @@ def host_model_env(self) -> Dict[str, str]: return {HOST_CLI_ENV: self.host_cli} return {} + def _ticket_spent(self) -> int: + """Model calls this Ticket's earlier runs already charged (#1082 row 2). + + One worker session is one Ticket (``docs/dsh-super-agent.md``), so the + operator ceiling is that session's budget: a second ``start`` hears the + remainder, not the ceiling again. ``pending_calls`` counts as spent + while a run is still in flight -- work already started is not budget + the next run may hand out twice. A run whose status cannot be read + counts as 0, so a store that lost one run does not make the Ticket + unstartable forever. + """ + spent = 0 + for run_id in self._ticket_runs: + try: + st = runstore.get(run_id, store=self.store).status() + except (runstore.RunStoreError, ValueError, OSError): + continue + spent += int(st.calls) + int(st.pending_calls) + return spent + # -- read-only ------------------------------------------------------------- def demo(self, algorithm: Optional[str] = None, @@ -715,7 +756,8 @@ def plan(self, spec: Dict[str, Any], usd_per_call: Optional[float] = None, es = EvolveSpec.from_dict(spec).absolutise() payload = plan_payload(es, usd_per_call=usd_per_call, budget_usd=budget_usd) - limit = _call_limit_payload(max_calls, max_usd, usd_per_call) + limit = _call_limit_payload(max_calls, max_usd, usd_per_call, + spent=self._ticket_spent()) except SpecError as e: return {"ok": False, "error": str(e)} except runstore.RunStoreError as e: @@ -770,11 +812,28 @@ def start(self, spec: Dict[str, Any], budget_usd: Optional[float] = None, runstore.require_budget_pair(budget_usd, usd_per_call) # A bad cap is a refusal too, not a run whose log.txt explains it # later; same sentence the CLI prints (#1184). - limit = _call_limit_payload(max_calls, max_usd, usd_per_call) + limit = _call_limit_payload(max_calls, max_usd, usd_per_call, + spent=self._ticket_spent()) except SpecError as e: return {"ok": False, "error": str(e)} except runstore.RunStoreError as e: return {"ok": False, "error": str(e)} + ticket = (limit or {}).get("ticket") or {} + if ticket.get("remaining") == 0: + # The ceiling is spent: refuse before a run exists, with the + # arithmetic in the sentence, instead of starting one that cannot + # charge a single call or, worse, one that treats 0 as "no cap". + # A caller's own `max_calls=0` is not this case and keeps its + # existing path. + return {"ok": False, "error": ( + f"{runstore.OPERATOR_MAX_CALLS_ENV}={ticket['ceiling']} is " + f"already spent by this worker's Ticket ({ticket['spent']} " + f"call{'s' if ticket['spent'] != 1 else ''} over " + f"{len(self._ticket_runs)} run" + f"{'s' if len(self._ticket_runs) != 1 else ''}); no run may " + "start. Start the next Ticket in a new server session, or " + "raise the ceiling."), + "call_limit": limit} if os.environ.get(NESTED_ENV): # This server is running inside a worker of another run (the plugin # that hosts it is being evolved). The transcript should still show @@ -814,6 +873,9 @@ def start(self, spec: Dict[str, Any], budget_usd: Optional[float] = None, env=self.host_model_env()) except runstore.RunStoreError as e: return {"ok": False, "error": str(e), "run_id": rd.run_id, "dir": rd.path} + # The Ticket's spend is read from the store, so this only has to name + # the runs it may count; a resumed or CLI-started run is not one. + self._ticket_runs.append(rd.run_id) out = {"ok": True, "run_id": rd.run_id, "state": st.state, "pid": st.pid, "dir": rd.path, "notes": rd.status().notes, # Whether a `host_model` reference in this spec can work. A run diff --git a/changelog.d/1082-ticket-call-cap.md b/changelog.d/1082-ticket-call-cap.md new file mode 100644 index 00000000..b85d5caf --- /dev/null +++ b/changelog.d/1082-ticket-call-cap.md @@ -0,0 +1,5 @@ +Fixed +`AGENTDESCENT_MAX_CALLS` is now a budget for one worker session, not a number +each run may ask for again: an MCP `start` after earlier runs is clamped to +what the Ticket has left, reports `call_limit.ticket` with ceiling/spent/ +remaining, and refuses outright once the ceiling is spent (#1082). diff --git a/docs/dsh-super-agent.md b/docs/dsh-super-agent.md index 9aa4fdbc..13e26341 100644 --- a/docs/dsh-super-agent.md +++ b/docs/dsh-super-agent.md @@ -108,6 +108,12 @@ your tree, under the operator's write allowlist). the Ticket. - `plan` is the budget line: it estimates cost without executing. Read it before `start`, and put the number in the Ticket. +- A Ticket's ceiling is the session's, not the run's. With + `AGENTDESCENT_MAX_CALLS` set, the server spends it across the runs it starts: + a second `start` is clamped to the remainder, its reply says + `ticket: {ceiling, spent, remaining}`, and once the ceiling is spent `start` + refuses. Start the next Ticket in a new server session (or raise the + ceiling) rather than reusing the spent one (#1082). - A detached run no longer inherits the worker session: `launch` drops the host-session markers it lists, except the four host config roots it keeps (`DETACHED_KEEP_VARS`: `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `DSH_HOME`, diff --git a/docs/plugin-design.md b/docs/plugin-design.md index 20eb1e56..a6e5c159 100644 --- a/docs/plugin-design.md +++ b/docs/plugin-design.md @@ -604,7 +604,12 @@ Two guards keep this from folding in on itself: the environment, not by review. The MCP surface takes the same numbers — `plan` / `start` accept `max_calls` / `max_usd` and report `call_limit` with what was asked for and what will be enforced, so a host sees a request of 9 - come back as 2 with `source: AGENTDESCENT_MAX_CALLS` (#1184). + come back as 2 with `source: AGENTDESCENT_MAX_CALLS` (#1184). One worker + session is one Ticket, so the server does not hand the ceiling out again per + run: a second `start` is clamped to what the Ticket has left, `call_limit` + then carries `ticket: {ceiling, spent, remaining}`, and a spent Ticket + refuses another `start` instead of launching a run that cannot charge a + single call (#1082). * **The controller never hot-swaps itself.** A self-evolved plugin reaches the user's real installation only through `apply`, which is a human decision on a diff, after an L1 oracle gate, with a backup. The loop can improve its own diff --git a/tests/test_mcp_ticket_cap.py b/tests/test_mcp_ticket_cap.py new file mode 100644 index 00000000..2487f075 --- /dev/null +++ b/tests/test_mcp_ticket_cap.py @@ -0,0 +1,115 @@ +"""One worker session is one Ticket: the operator ceiling is spent, not re-granted (#1082). + +``AGENTDESCENT_MAX_CALLS`` caps a *run* in ``runstore.launch`` / ``execute``. A +host worker that starts a second run from the same MCP server asks again and +gets the same ceiling back, so one Ticket spends twice the number the operator +set: with ``AGENTDESCENT_MAX_CALLS=1`` two ``start`` calls each run one model +call and the Ticket bills two. The server process is the worker's session -- +one Ticket in ``docs/dsh-super-agent.md`` -- so the ceiling has to hold across +the runs that server starts, and a spent Ticket refuses another start instead +of silently starting an uncapped one. +""" + +from __future__ import annotations + +import time + +import pytest + +from agentdescent import runstore +from agentdescent.mcp import Tools + +from tests.test_evolvespec import _dir_spec # noqa: F401 + + +@pytest.fixture +def store(tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_HOME", str(tmp_path / "home")) + monkeypatch.setenv("AGENTDESCENT_SURFACE_WRITE_DIRS", str(tmp_path)) + return str(tmp_path / "runs") + + +def _wait(rd, timeout=120): + deadline = time.time() + timeout + while time.time() < deadline: + st = rd.status() + if st.state in ("done", "failed", "cancelled"): + return st + time.sleep(0.2) + raise AssertionError(rd.status()) + + +def _start_in(tmp_path, tools, name, **kwargs): + sub = tmp_path / name + sub.mkdir() + started = tools.start(_dir_spec(str(sub)).to_dict(), **kwargs) + assert started["ok"] is True, started + return started + + +def test_second_run_is_clamped_to_what_the_ticket_has_left(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "2") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=1) + st = _wait(runstore.get(first["run_id"], store=store)) + assert st.state == "done", st + assert st.calls == 1, st + + second = _start_in(tmp_path, tools, "t1", max_calls=5) + # One call is already spent, so the Ticket has one left -- not five, and + # not the untouched ceiling of two the run-level clamp would hand back. + assert second["call_limit"]["max_calls"] == 1, second["call_limit"] + assert second["call_limit"]["source"] == runstore.OPERATOR_MAX_CALLS_ENV + assert second["call_limit"]["max_calls_requested"] == 5 + assert second["call_limit"]["ticket"] == {"ceiling": 2, "spent": 1, "remaining": 1} + _wait(runstore.get(second["run_id"], store=store)) + + +def test_a_spent_ticket_refuses_another_start(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "1") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=1) + st = _wait(runstore.get(first["run_id"], store=store)) + assert st.state == "done", st + assert st.calls == 1, st + + sub = tmp_path / "t1" + sub.mkdir() + refused = tools.start(_dir_spec(str(sub)).to_dict()) + assert refused["ok"] is False, refused + assert "AGENTDESCENT_MAX_CALLS" in refused["error"], refused["error"] + assert "1" in refused["error"], refused["error"] + # Nothing was created: a spent Ticket is refused before the run exists. + assert len(runstore.list_runs(store=store)) == 1 + + +def test_plan_reports_what_the_ticket_has_left(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=1) + st = _wait(runstore.get(first["run_id"], store=store)) + assert st.calls == 1, st + + sub = tmp_path / "t1" + sub.mkdir() + plan = tools.plan(_dir_spec(str(sub)).to_dict(), max_calls=9) + assert plan["ok"] is True, plan + # What `start` would enforce, so the host shows the number the user agrees + # to -- 1 call left of 3, not the ceiling of 3 or the requested 9. + assert plan["call_limit"]["max_calls"] == 2, plan["call_limit"] + assert plan["call_limit"]["ticket"] == {"ceiling": 3, "spent": 1, + "remaining": 2} + + +def test_a_callers_own_zero_cap_is_not_the_spent_ticket_refusal(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "2") + tools = Tools(store) + sub = tmp_path / "t0" + sub.mkdir() + plan = tools.plan(_dir_spec(str(sub)).to_dict(), max_calls=0) + assert plan["ok"] is True, plan + # The caller asked for zero calls with a ceiling that is untouched: that is + # its own number, not "the Ticket is spent", so it must not carry the + # ticket arithmetic or the refusal. + assert plan["call_limit"]["max_calls"] == 0, plan["call_limit"] + assert "ticket" not in plan["call_limit"], plan["call_limit"] From 138036b61572670c5d517ea51140f9ffa03a5381 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Sun, 22 Nov 2026 09:26:48 +0000 Subject: [PATCH 2/7] fix(mcp): start and resume both spend one Ticket's call ceiling 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. --- agentdescent/mcp.py | 211 +++++++++++++++++++++------- agentdescent/runstore.py | 8 +- changelog.d/1082-ticket-call-cap.md | 5 +- tests/test_mcp_ticket_cap.py | 145 ++++++++++++++++++- tests/test_runstore_cli.py | 17 +++ 5 files changed, 335 insertions(+), 51 deletions(-) diff --git a/agentdescent/mcp.py b/agentdescent/mcp.py index 9c178b83..f0f989d0 100644 --- a/agentdescent/mcp.py +++ b/agentdescent/mcp.py @@ -33,6 +33,7 @@ import json import os import secrets +import threading from typing import Annotated, Any, Dict, List, Optional, Sequence, Tuple from . import __version__, runstore @@ -525,6 +526,17 @@ def __init__(self, store: Optional[str] = None, *, #: operator ceiling is spent across them instead of re-granted per run #: (#1082 row 2). Empty on a fresh server. self._ticket_runs: List[str] = [] + #: Floor of calls each of those runs will have spent before it reports: + #: for a fresh run the cap it was launched with, for a resumed one what + #: its ledger already holds plus that cap. Without it a run that has + #: written no status yet (`calls` and `pending_calls` still 0) lets a + #: second, overlapping `start` take the same remainder (#1082). + self._ticket_reserved: Dict[str, int] = {} + #: One lock around "read the spend -> reserve -> launch -> register": + #: `start` and `resume` run in worker threads + #: (`anyio.to_thread.run_sync`), so two of them in the same tick would + #: otherwise read the same remainder and both take it (#1082). + self._ticket_lock = threading.Lock() def host_model_env(self) -> Dict[str, str]: """What a launched run needs to reach the host's model, by either route. @@ -549,19 +561,109 @@ def _ticket_spent(self) -> int: operator ceiling is that session's budget: a second ``start`` hears the remainder, not the ceiling again. ``pending_calls`` counts as spent while a run is still in flight -- work already started is not budget - the next run may hand out twice. A run whose status cannot be read - counts as 0, so a store that lost one run does not make the Ticket - unstartable forever. + the next run may hand out twice. ``self._ticket_reserved`` goes + further: a run that was launched but has written no status yet holds + the cap it was started with, so two overlapping starts cannot both take + the same remainder. A finished run is charged what it used, so an + under-spending run gives the rest of the Ticket back. A run whose + status cannot be read counts as 0, so a store that lost one run does + not make the Ticket unstartable forever. """ spent = 0 for run_id in self._ticket_runs: + reserved = max(0, int(self._ticket_reserved.get(run_id, 0))) try: st = runstore.get(run_id, store=self.store).status() except (runstore.RunStoreError, ValueError, OSError): continue - spent += int(st.calls) + int(st.pending_calls) + charged = int(st.calls) + int(st.pending_calls) + if st.state in ("done", "failed", "cancelled"): + spent += charged + else: + # Launched, not finished: its cap is already committed. + spent += max(charged, reserved) return spent + def _ticket_refusal(self, ticket: Dict[str, Any], + limit: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """The reply for a spent Ticket, shared by ``start`` and ``resume``. + + One sentence for both entry points: a resumed run would otherwise take + the full ceiling again, which is the same bypass a second ``start`` was + (#1082). + """ + return {"ok": False, "error": ( + f"{runstore.OPERATOR_MAX_CALLS_ENV}={ticket['ceiling']} is " + f"already spent by this worker's Ticket ({ticket['spent']} " + f"call{'s' if ticket['spent'] != 1 else ''} over " + f"{len(self._ticket_runs)} run" + f"{'s' if len(self._ticket_runs) != 1 else ''}); no run may " + "start. Start the next Ticket in a new server session, or " + "raise the ceiling."), + "call_limit": limit} + + def _ticket_open(self, max_calls: Optional[int], max_usd: Optional[float], + usd_per_call: Optional[float], *, + prior_calls: int = 0) -> Tuple[ + Optional[Dict[str, Any]], Optional[int], Optional[Dict[str, Any]]]: + """``(limit, applied, refusal)`` for one ``start`` / ``resume`` (#1082). + + Caller holds :attr:`_ticket_lock`: the spend read and the reservation + that follows it have to be one step, or two runs in the same tick both + take the same remainder. ``applied`` is the enforced number the child is + started with -- ``min(caller, remaining)``, ``remaining`` when the caller + named none, the caller's own number with no ceiling, ``None`` when + neither -- and the refusal is the spent-Ticket reply. + + ``prior_calls`` is the ledger a resumed run already carries. The child's + cap counts that ledger (``execute`` seeds ``Usage`` from it), so the + number it is relaunched with is ``prior + remaining``: passing the + remainder alone would stop it at once having "reached" a cap it already + went past. The reply says the same number it gave the child. + """ + limit = _call_limit_payload(max_calls, max_usd, usd_per_call, + spent=self._ticket_spent()) + ticket = (limit or {}).get("ticket") or {} + if ticket.get("remaining") == 0: + return limit, None, self._ticket_refusal(ticket, limit) + applied = None if limit is None else limit.get("max_calls") + if applied is not None and prior_calls > 0: + applied += max(0, int(prior_calls)) + limit = {**(limit or {}), "max_calls": applied} + return limit, applied, None + + def _ticket_reserve(self, run_id: str, applied: Optional[int], + prior_calls: int = 0) -> None: + """Register a run and the calls it holds until it reports (#1082). + + ``prior_calls`` is what the ledger already holds: a resumed run is + charged for the calls it spent before this relaunch plus the cap it is + relaunched with. Registering a run this server already knows must not + list it twice, or the Ticket would charge it twice. + """ + held = max(0, int(applied or 0)) + max(0, int(prior_calls)) + if run_id not in self._ticket_runs: + self._ticket_runs.append(run_id) + self._ticket_reserved[run_id] = max(self._ticket_reserved.get(run_id, 0), held) + + def _ticket_env(self, limit: Optional[Dict[str, Any]], + max_calls: Optional[int]) -> Dict[str, str]: + """The child environment, carrying what the caller asked for (#1184). + + Because ``start`` launches the run with the enforced number rather than + the caller's, ``launch`` cannot recover the request and would stop + labelling the run ``AGENTDESCENT_MAX_CALLS`` when the ceiling bound it. + The reply still says so, so the run's own ``stop_detail`` has to as + well: write the request into the variable that label is read from, + exactly as ``launch`` does for a per-run clamp ("" = none named). + """ + env = self.host_model_env() + if limit is not None and limit.get("source") == runstore.OPERATOR_MAX_CALLS_ENV: + env = {**env, runstore.OPERATOR_MAX_CALLS_REQUESTED_ENV: + "" if max_calls is None else str(int(max_calls))} + return env + + # -- read-only ------------------------------------------------------------- def demo(self, algorithm: Optional[str] = None, @@ -812,30 +914,10 @@ def start(self, spec: Dict[str, Any], budget_usd: Optional[float] = None, # Before create: same rule as CLI -- budget without price must not # return ok/started and then fail only in log.txt (#342). runstore.require_budget_pair(budget_usd, usd_per_call) - # A bad cap is a refusal too, not a run whose log.txt explains it - # later; same sentence the CLI prints (#1184). - limit = _call_limit_payload(max_calls, max_usd, usd_per_call, - spent=self._ticket_spent()) except SpecError as e: return {"ok": False, "error": str(e)} except runstore.RunStoreError as e: return {"ok": False, "error": str(e)} - ticket = (limit or {}).get("ticket") or {} - if ticket.get("remaining") == 0: - # The ceiling is spent: refuse before a run exists, with the - # arithmetic in the sentence, instead of starting one that cannot - # charge a single call or, worse, one that treats 0 as "no cap". - # A caller's own `max_calls=0` is not this case and keeps its - # existing path. - return {"ok": False, "error": ( - f"{runstore.OPERATOR_MAX_CALLS_ENV}={ticket['ceiling']} is " - f"already spent by this worker's Ticket ({ticket['spent']} " - f"call{'s' if ticket['spent'] != 1 else ''} over " - f"{len(self._ticket_runs)} run" - f"{'s' if len(self._ticket_runs) != 1 else ''}); no run may " - "start. Start the next Ticket in a new server session, or " - "raise the ceiling."), - "call_limit": limit} if os.environ.get(NESTED_ENV): # This server is running inside a worker of another run (the plugin # that hosts it is being evolved). The transcript should still show @@ -858,26 +940,38 @@ def start(self, spec: Dict[str, Any], budget_usd: Optional[float] = None, # plan still hear that budget_usd only binds between rounds. budget_warn = budget_round_overshoot_warning( estimate(comp, usd_per_call=usd_per_call), budget_usd, usd_per_call) - rd = runstore.create(es.to_dict(), store=self.store) - # Recorded before the child is up, so the reply below and the first - # `status` poll carry what `plan` said -- a too-small held-out set among - # it -- instead of an empty list until the child has composed (#414). - rd.update_status(notes=comp.notes) - try: - # The run is a detached process, so a `host_model` reference in the - # spec resolves there, not here -- it needs the bridge's address in - # its environment or it has no session to borrow. - # The caller's own numbers go in, not `limit`'s clamped ones: - # `launch` applies the same min and is what records what was asked - # for across the detach boundary (#1184). - st = runstore.launch(rd, budget_usd=budget_usd, usd_per_call=usd_per_call, - max_calls=max_calls, max_usd=max_usd, - env=self.host_model_env()) - except runstore.RunStoreError as e: - return {"ok": False, "error": str(e), "run_id": rd.run_id, "dir": rd.path} - # The Ticket's spend is read from the store, so this only has to name - # the runs it may count; a resumed or CLI-started run is not one. - self._ticket_runs.append(rd.run_id) + # The gate is one step with the launch it authorises (#1082): `start` + # runs in a worker thread, so two calls in the same tick would otherwise + # read the same remainder, both take it, and bill the ceiling twice. + # Under the lock: read the spend, reserve the cap, hand the child the + # reserved number (not the caller's, which `launch` clamps only against + # the full ceiling), then register the run so it holds that number + # until it reports. The number is `limit`'s enforced one, so the reply + # and the child cannot disagree; a caller's own `max_usd` stays per run, + # because the operator ceiling is the only per-Ticket budget. + with self._ticket_lock: + limit, applied, refused = self._ticket_open(max_calls, max_usd, + usd_per_call) + if refused is not None: + return refused + rd = runstore.create(es.to_dict(), store=self.store) + # Recorded before the child is up, so the reply below and the first + # `status` poll carry what `plan` said -- a too-small held-out set + # among it -- instead of an empty list until the child has composed + # (#414). + rd.update_status(notes=comp.notes) + try: + # The run is a detached process, so a `host_model` reference in + # the spec resolves there, not here -- it needs the bridge's + # address in its environment or it has no session to borrow. + st = runstore.launch(rd, budget_usd=budget_usd, + usd_per_call=usd_per_call, + max_calls=applied, max_usd=max_usd, + env=self._ticket_env(limit, max_calls)) + except runstore.RunStoreError as e: + return {"ok": False, "error": str(e), "run_id": rd.run_id, + "dir": rd.path} + self._ticket_reserve(rd.run_id, applied) out = {"ok": True, "run_id": rd.run_id, "state": st.state, "pid": st.pid, "dir": rd.path, "notes": rd.status().notes, # Whether a `host_model` reference in this spec can work. A run @@ -943,9 +1037,32 @@ def resume(self, run_id: str, budget_usd: Optional[float] = None, if not force: require_resume_not_quota_exhausted(run_id, store=self.store) require_resume_host_on_path(run_id, store=self.store) - return runstore.resume(run_id, store=self.store, budget_usd=budget_usd, - usd_per_call=usd_per_call, - env=self.host_model_env()).to_dict() + # One gate for both entry points (#1082): a resumed run belongs to + # this Ticket too, so it is clamped to what is left and charged for + # what it spends. It already carries a ledger, so the reservation is + # what that ledger holds plus the cap it is relaunched with -- the + # number the child gets, for the same reason `start` hands over the + # enforced one: `launch` clamps only against the full ceiling. + with self._ticket_lock: + before = runstore.get(run_id, store=self.store).status() + prior = int(before.calls) + int(before.pending_calls) + limit, applied, refused = self._ticket_open(None, None, + usd_per_call, + prior_calls=prior) + if refused is not None: + return refused + st = runstore.resume( + run_id, store=self.store, budget_usd=budget_usd, + usd_per_call=usd_per_call, max_calls=applied, + env=self._ticket_env(limit, None)) + # `applied` already carries the ledger when it is bounded; with + # no ceiling the ledger is all this run holds. + self._ticket_reserve(run_id, applied, + 0 if applied is not None else prior) + out = st.to_dict() + if limit is not None: + out["call_limit"] = limit + return out except (runstore.RunStoreError, SpecError) as e: return {"error": str(e)} diff --git a/agentdescent/runstore.py b/agentdescent/runstore.py index daa628fa..f6fd3761 100644 --- a/agentdescent/runstore.py +++ b/agentdescent/runstore.py @@ -816,7 +816,11 @@ def cancel(run_id: str, *, store: Optional[str] = None, grace: float = 5.0) -> R st = rd.status() if st.pid is None or not st.alive(): if st.state == "running": - st = rd.update_status(state="cancelled", finished=time.time()) + # Clear `pending_calls` with the state: a cancelled run that kept a + # call in flight would hold a phantom charge against its Ticket + # forever (#1082). + st = rd.update_status(state="cancelled", finished=time.time(), + pending_calls=0) return st pgid = None try: @@ -830,7 +834,7 @@ def cancel(run_id: str, *, store: Optional[str] = None, grace: float = 5.0) -> R if st.alive(): _signal(st.pid, pgid, getattr(signal, "SIGKILL", signal.SIGTERM)) return rd.update_status(state="cancelled", finished=time.time(), - stop_reason="cancelled") + stop_reason="cancelled", pending_calls=0) def _signal(pid: int, pgid: Optional[int], sig: int) -> None: diff --git a/changelog.d/1082-ticket-call-cap.md b/changelog.d/1082-ticket-call-cap.md index b85d5caf..fa58ef1b 100644 --- a/changelog.d/1082-ticket-call-cap.md +++ b/changelog.d/1082-ticket-call-cap.md @@ -2,4 +2,7 @@ Fixed `AGENTDESCENT_MAX_CALLS` is now a budget for one worker session, not a number each run may ask for again: an MCP `start` after earlier runs is clamped to what the Ticket has left, reports `call_limit.ticket` with ceiling/spent/ -remaining, and refuses outright once the ceiling is spent (#1082). +remaining, and refuses outright once the ceiling is spent (#1082). The clamp is +what the run is actually started with, not just what the reply says, and a +started run holds its cap until it reports, so two overlapping starts cannot +both take the remainder (#1082). diff --git a/tests/test_mcp_ticket_cap.py b/tests/test_mcp_ticket_cap.py index 2487f075..7dcc387d 100644 --- a/tests/test_mcp_ticket_cap.py +++ b/tests/test_mcp_ticket_cap.py @@ -12,6 +12,7 @@ from __future__ import annotations +import threading import time import pytest @@ -39,6 +40,17 @@ def _wait(rd, timeout=120): raise AssertionError(rd.status()) +def _wait_more(rd, before_calls, timeout=120): + """Wait for a resumed run to stop again, past the calls it already had.""" + deadline = time.time() + timeout + while time.time() < deadline: + st = rd.status() + if st.state in ("done", "failed", "cancelled") and st.calls > before_calls: + return st + time.sleep(0.2) + return rd.status() + + def _start_in(tmp_path, tools, name, **kwargs): sub = tmp_path / name sub.mkdir() @@ -62,7 +74,13 @@ def test_second_run_is_clamped_to_what_the_ticket_has_left(store, tmp_path, monk assert second["call_limit"]["source"] == runstore.OPERATOR_MAX_CALLS_ENV assert second["call_limit"]["max_calls_requested"] == 5 assert second["call_limit"]["ticket"] == {"ceiling": 2, "spent": 1, "remaining": 1} - _wait(runstore.get(second["run_id"], store=store)) + st2 = _wait(runstore.get(second["run_id"], store=store)) + # The reply is not the enforcement: the child has to be launched with the + # same number, or the run-level clamp hands it the whole ceiling again and + # this Ticket bills 3 against a ceiling of 2. + assert st2.state == "done", st2 + assert st2.calls <= 1, st2 + assert st.calls + st2.calls <= 2, (st.calls, st2.calls) def test_a_spent_ticket_refuses_another_start(store, tmp_path, monkeypatch): @@ -83,6 +101,68 @@ def test_a_spent_ticket_refuses_another_start(store, tmp_path, monkeypatch): assert len(runstore.list_runs(store=store)) == 1 +def test_a_second_start_with_no_cap_spends_only_the_remainder(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=1) + st1 = _wait(runstore.get(first["run_id"], store=store)) + assert st1.calls == 1, st1 + + # A host that names no cap of its own is the wider hole: the run-level + # clamp turns "no number" into the full ceiling, so the remainder has to be + # the number that crosses the detach boundary. + second = _start_in(tmp_path, tools, "t1") + assert second["call_limit"]["max_calls"] == 2, second["call_limit"] + assert second["call_limit"]["source"] == runstore.OPERATOR_MAX_CALLS_ENV + assert "max_calls_requested" not in second["call_limit"], second["call_limit"] + st2 = _wait(runstore.get(second["run_id"], store=store)) + # The child, not the reply: it has to stop at the 2 calls that are left. At + # `115edc74` it runs the full ceiling of 3 and this Ticket bills 4 of 3, + # which is the overrun this test exists to pin. + assert st2.calls == 2, st2 + assert st2.stop_reason == "budget", st2 + assert st1.calls + st2.calls == 3, (st1.calls, st2.calls) + + +def test_a_started_run_reserves_its_cap_before_it_spends(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=3) + # A run that has been launched but has not written status yet has charged + # nothing, so two overlapping starts would both take the remainder and the + # Ticket would spend twice the ceiling. The cap it was launched with is the + # reservation until the run reports. + assert tools._ticket_spent() >= 3, tools._ticket_spent() + + sub = tmp_path / "t1" + sub.mkdir() + second = tools.start(_dir_spec(str(sub)).to_dict()) + assert second["ok"] is False, second + assert "AGENTDESCENT_MAX_CALLS" in second["error"], second["error"] + st1 = _wait(runstore.get(first["run_id"], store=store)) + assert st1.calls <= 3, st1 + # Refused before a run existed: one run, not two. + assert len(runstore.list_runs(store=store)) == 1 + + +def test_a_finished_run_gives_back_what_it_did_not_spend(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "20") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=20) + # The reservation is the launched cap; this spec finishes well below it. + assert tools._ticket_spent() == 20, tools._ticket_spent() + st1 = _wait(runstore.get(first["run_id"], store=store)) + assert st1.calls < 20, st1 + # A finished run is charged what it actually used, not what it reserved: + # otherwise an under-spending run would burn the rest of the Ticket. + assert tools._ticket_spent() == st1.calls, (tools._ticket_spent(), st1.calls) + + second = _start_in(tmp_path, tools, "t1") + assert second["call_limit"]["max_calls"] == 20 - st1.calls, second["call_limit"] + st2 = _wait(runstore.get(second["run_id"], store=store)) + assert st1.calls + st2.calls <= 20, (st1.calls, st2.calls) + + def test_plan_reports_what_the_ticket_has_left(store, tmp_path, monkeypatch): monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") tools = Tools(store) @@ -113,3 +193,66 @@ def test_a_callers_own_zero_cap_is_not_the_spent_ticket_refusal(store, tmp_path, # ticket arithmetic or the refusal. assert plan["call_limit"]["max_calls"] == 0, plan["call_limit"] assert "ticket" not in plan["call_limit"], plan["call_limit"] + + +def test_two_starts_at_once_cannot_both_take_the_remainder(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + subs = [] + for name in ("t0", "t1"): + sub = tmp_path / name + sub.mkdir() + subs.append(sub) + out = [] + + def go(sub): + out.append(tools.start(_dir_spec(str(sub)).to_dict())) + + # `start` is dispatched off the event loop (`anyio.to_thread.run_sync`), so + # two hosts calling it in the same tick is a real interleaving, not a + # hypothetical: without one locked gate both read `spent: 0`, both take the + # ceiling, and the Ticket bills twice it (#1082). + threads = [threading.Thread(target=go, args=(sub,)) for sub in subs] + for t in threads: + t.start() + for t in threads: + t.join() + ok = [r for r in out if r["ok"]] + refused = [r for r in out if not r["ok"]] + assert len(ok) == 1, out + assert refused and "AGENTDESCENT_MAX_CALLS" in refused[0]["error"], refused + assert sum(r["call_limit"]["max_calls"] for r in ok) == 3, out + total = sum(_wait(runstore.get(r["run_id"], store=store)).calls for r in ok) + # One of the two took the whole ceiling and the other was refused: at + # `115edc74` both are admitted and the Ticket bills 6 of 3. + assert total == 3, total + + +def test_a_resumed_run_is_charged_to_the_ticket(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=1) + st_a = _wait(runstore.get(first["run_id"], store=store)) + second = _start_in(tmp_path, tools, "t1", max_calls=1) + st_b = _wait(runstore.get(second["run_id"], store=store)) + assert st_a.calls + st_b.calls == 2, (st_a.calls, st_b.calls) + + # `resume` is the second entry point to the same ceiling: relaunching a run + # is not a new Ticket, so it is clamped to the one call that is left and + # charged for what it spends. Left ungated it got the full ceiling and was + # never counted -- one `resume` and this Ticket billed 4 of 3 (#1082). + resumed = tools.resume(first["run_id"]) + # The child's cap counts the ledger it resumes (1 call already made), so the + # number it is relaunched with is 1 + 1 -- and the reply quotes the same + # number, not the remainder it would then stop at immediately. + assert resumed["call_limit"]["max_calls"] == 2, resumed + assert resumed["call_limit"]["source"] == runstore.OPERATOR_MAX_CALLS_ENV + assert resumed["call_limit"]["ticket"] == {"ceiling": 3, "spent": 2, + "remaining": 1} + st_a2 = _wait_more(runstore.get(first["run_id"], store=store), st_a.calls) + assert st_a2.state == "done", st_a2 + # The resumed child stops at the one call that is left. At `115edc74` it + # relaunches with the full ceiling of 3, so this run reaches 3 and the + # Ticket bills 4 of 3. + assert st_a2.calls - st_a.calls == 1, (st_a.calls, st_a2.calls) + assert st_a2.calls + st_b.calls == 3, (st_a2.calls, st_b.calls) diff --git a/tests/test_runstore_cli.py b/tests/test_runstore_cli.py index 3498a56a..9e4e68b0 100644 --- a/tests/test_runstore_cli.py +++ b/tests/test_runstore_cli.py @@ -317,6 +317,23 @@ def test_cancel_kills_the_run_and_its_workers(store, tmp_path): assert not [l for l in out.splitlines() if "time.sleep(60)" in l], out +def test_cancel_clears_a_pending_call(store, tmp_path): + # A run cancelled mid-call keeps `pending_calls` set in its last write; a + # cancelled run that keeps it would hold a phantom charge against its MCP + # Ticket forever, because the Ticket counts a call in flight as spent + # (#1082). Its own session, so `cancel` kills the child and not the suite. + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"], + start_new_session=True) + try: + rd = runstore.create(_spec_file(tmp_path)[1].to_dict(), store=store) + rd.update_status(state="running", pid=child.pid, calls=1, pending_calls=1) + st = runstore.cancel(rd.run_id, store=store, grace=2.0) + finally: + child.wait(10) + assert st.state == "cancelled", st + assert st.pending_calls == 0, st + + def test_resume_continues_on_the_same_ledger(store, tmp_path): _, spec = _spec_file(tmp_path) rd = runstore.create(spec.to_dict(), store=store) From a0b073b37076ab0653de4dbc686e4f2f45839a11 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Sun, 22 Nov 2026 09:34:44 +0000 Subject: [PATCH 3/7] docs(mcp): the Ticket counts only the runs this server started 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). --- docs/dsh-super-agent.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/dsh-super-agent.md b/docs/dsh-super-agent.md index 13e26341..fdac4841 100644 --- a/docs/dsh-super-agent.md +++ b/docs/dsh-super-agent.md @@ -112,8 +112,15 @@ your tree, under the operator's write allowlist). `AGENTDESCENT_MAX_CALLS` set, the server spends it across the runs it starts: a second `start` is clamped to the remainder, its reply says `ticket: {ceiling, spent, remaining}`, and once the ceiling is spent `start` - refuses. Start the next Ticket in a new server session (or raise the - ceiling) rather than reusing the spent one (#1082). + refuses, and `resume` is held to the same remainder. Start the next Ticket in + a new server session (or raise the ceiling) rather than reusing the spent one + (#1082). + Only the runs this server started are charged: a run it did not start (a CLI + `evolve`, a run from another process) is outside the accounting unless it is + resumed here, so mixing CLI and MCP runs inside one session is not covered. + `AGENTDESCENT_MAX_CALLS` is the only operator ceiling and it is per-Ticket; a + caller's `max_calls` and `max_usd` stay per-run flags, and only `max_calls` is + clamped by what the Ticket has left (#1082). - A detached run no longer inherits the worker session: `launch` drops the host-session markers it lists, except the four host config roots it keeps (`DETACHED_KEEP_VARS`: `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `DSH_HOME`, From 8ee4d7da806d3cdf88073ef1cc67174743108d69 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Sun, 22 Nov 2026 09:57:00 +0000 Subject: [PATCH 4/7] fix(mcp): an unreadable run refuses instead of granting the rest `_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. --- agentdescent/mcp.py | 32 +++++++++++---- changelog.d/1082-ticket-call-cap.md | 6 +++ tests/test_mcp_ticket_cap.py | 62 +++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 7 deletions(-) diff --git a/agentdescent/mcp.py b/agentdescent/mcp.py index f0f989d0..3830a46d 100644 --- a/agentdescent/mcp.py +++ b/agentdescent/mcp.py @@ -566,16 +566,22 @@ def _ticket_spent(self) -> int: the cap it was started with, so two overlapping starts cannot both take the same remainder. A finished run is charged what it used, so an under-spending run gives the rest of the Ticket back. A run whose - status cannot be read counts as 0, so a store that lost one run does - not make the Ticket unstartable forever. + status cannot be read is not free: this raises instead of counting it + as 0, because a remainder computed over a run nobody can read may + already be spent, and granting it would start the run that breaks the + ceiling (#1082). """ spent = 0 for run_id in self._ticket_runs: reserved = max(0, int(self._ticket_reserved.get(run_id, 0))) try: st = runstore.get(run_id, store=self.store).status() - except (runstore.RunStoreError, ValueError, OSError): - continue + except (runstore.RunStoreError, ValueError, OSError) as e: + raise runstore.RunStoreError( + f"run {run_id} cannot be accounted: its status cannot be " + f"read ({e}), so what this Ticket has spent is unknown; " + "no run may start until the run store is readable again. " + "Fix or remove that run directory, then retry.") from e charged = int(st.calls) + int(st.pending_calls) if st.state in ("done", "failed", "cancelled"): spent += charged @@ -619,10 +625,22 @@ def _ticket_open(self, max_calls: Optional[int], max_usd: Optional[float], cap counts that ledger (``execute`` seeds ``Usage`` from it), so the number it is relaunched with is ``prior + remaining``: passing the remainder alone would stop it at once having "reached" a cap it already - went past. The reply says the same number it gave the child. + went past. The reply says the same number it gave the child. A run whose + status cannot be read refuses here too, with its own sentence: that is + an unreadable ledger, not a spent one. """ - limit = _call_limit_payload(max_calls, max_usd, usd_per_call, - spent=self._ticket_spent()) + # Both of these raise reasons a host must hear as a refusal, not as a + # traceback: `start` reaches this under the lock, outside the try that + # wraps its argument parsing, so an escaping SpecError would bypass the + # `ok: false` answer the CLI and `plan` already give (#1082, #1196). + try: + spent = self._ticket_spent() + except runstore.RunStoreError as e: + return None, None, {"ok": False, "error": str(e)} + try: + limit = _call_limit_payload(max_calls, max_usd, usd_per_call, spent=spent) + except SpecError as e: + return None, None, {"ok": False, "error": str(e)} ticket = (limit or {}).get("ticket") or {} if ticket.get("remaining") == 0: return limit, None, self._ticket_refusal(ticket, limit) diff --git a/changelog.d/1082-ticket-call-cap.md b/changelog.d/1082-ticket-call-cap.md index fa58ef1b..b74953c1 100644 --- a/changelog.d/1082-ticket-call-cap.md +++ b/changelog.d/1082-ticket-call-cap.md @@ -6,3 +6,9 @@ remaining, and refuses outright once the ceiling is spent (#1082). The clamp is what the run is actually started with, not just what the reply says, and a started run holds its cap until it reports, so two overlapping starts cannot both take the remainder (#1082). + +A run whose status cannot be read is no longer counted as free: the Ticket +refuses to start or resume anything until the run store is readable again, +instead of granting a remainder that may already be spent. A `max_usd` without +`usd_per_call` is still refused with the argument named in the message, now +from inside the same gate (#1196). diff --git a/tests/test_mcp_ticket_cap.py b/tests/test_mcp_ticket_cap.py index 7dcc387d..32bc828c 100644 --- a/tests/test_mcp_ticket_cap.py +++ b/tests/test_mcp_ticket_cap.py @@ -12,6 +12,8 @@ from __future__ import annotations +import os +import re import threading import time @@ -51,6 +53,19 @@ def _wait_more(rd, before_calls, timeout=120): return rd.status() +def _cap_in_detail(st): + """The `cap N` a capped run actually stopped at, read from its own status. + + The reply is not the enforcement: a run whose ``stop_detail`` names a + different number than the reply handed out is the grant mismatch this file + exists to pin (#1082). Only a run that stopped on the call budget has one. + """ + assert st.stop_reason == "budget", st + m = re.search(r"cap (\d+)\s*$", st.stop_detail or "") + assert m, st.stop_detail + return int(m.group(1)) + + def _start_in(tmp_path, tools, name, **kwargs): sub = tmp_path / name sub.mkdir() @@ -81,6 +96,10 @@ def test_second_run_is_clamped_to_what_the_ticket_has_left(store, tmp_path, monk assert st2.state == "done", st2 assert st2.calls <= 1, st2 assert st.calls + st2.calls <= 2, (st.calls, st2.calls) + # The child stopped where the reply said it would: `stop_detail` names the + # same cap the host was told, so the number a host shows is the number that + # was enforced. + assert _cap_in_detail(st2) == second["call_limit"]["max_calls"], st2.stop_detail def test_a_spent_ticket_refuses_another_start(store, tmp_path, monkeypatch): @@ -256,3 +275,46 @@ def test_a_resumed_run_is_charged_to_the_ticket(store, tmp_path, monkeypatch): # Ticket bills 4 of 3. assert st_a2.calls - st_a.calls == 1, (st_a.calls, st_a2.calls) assert st_a2.calls + st_b.calls == 3, (st_a2.calls, st_b.calls) + +def test_a_ceiling_bound_run_is_stopped_at_the_cap_the_reply_quotes(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + # The caller asks for nine, the ceiling grants three. The reply says 3, so + # the child has to stop at 3: a reply that says 3 over a child stopped + # anywhere else is the grant mismatch this file pins, not a display bug. + first = _start_in(tmp_path, tools, "t0", max_calls=9) + assert first["call_limit"]["max_calls"] == 3, first["call_limit"] + assert first["call_limit"]["source"] == runstore.OPERATOR_MAX_CALLS_ENV + st = _wait(runstore.get(first["run_id"], store=store)) + assert st.calls == 3, st + assert _cap_in_detail(st) == first["call_limit"]["max_calls"], st.stop_detail + + +def test_an_unreadable_run_refuses_instead_of_granting_the_rest(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=1) + st = _wait(runstore.get(first["run_id"], store=store)) + assert st.calls == 1, st + + # A store that lost one run's status cannot say what this Ticket spent. + # Reading it as 0 hands the next run the rest of a budget that may already + # be gone, so the Ticket refuses until the store is readable again. + os.remove(runstore.get(first["run_id"], store=store).status_path) + sub = tmp_path / "t1" + sub.mkdir() + refused = tools.start(_dir_spec(str(sub)).to_dict()) + assert refused["ok"] is False, refused + assert first["run_id"] in refused["error"], refused["error"] + assert "cannot be accounted" in refused["error"], refused["error"] + # Refused before the run existed: one run directory, not two. + assert len(os.listdir(store)) == 1, os.listdir(store) + + # `plan` says the same thing, so a host that plans before starting is not + # told a remainder the Ticket is not willing to grant. + plan_sub = tmp_path / "t2" + plan_sub.mkdir() + plan = tools.plan(_dir_spec(str(plan_sub)).to_dict()) + assert plan["ok"] is False, plan + assert first["run_id"] in plan["error"], plan["error"] + assert "cannot be accounted" in plan["error"], plan["error"] From bb08b16e4125228400dbf4e377c6e3e71ed99c22 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Mon, 23 Nov 2026 01:13:05 +0000 Subject: [PATCH 5/7] fix(mcp): a resumed external run is granted the remainder, not the ceiling `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. --- agentdescent/mcp.py | 53 +++++++++++++------- changelog.d/1082-ticket-call-cap.md | 5 ++ docs/dsh-super-agent.md | 13 +++-- tests/test_mcp_ticket_cap.py | 78 +++++++++++++++++++++++++++++ 4 files changed, 129 insertions(+), 20 deletions(-) diff --git a/agentdescent/mcp.py b/agentdescent/mcp.py index 3830a46d..e1f9c681 100644 --- a/agentdescent/mcp.py +++ b/agentdescent/mcp.py @@ -610,7 +610,8 @@ def _ticket_refusal(self, ticket: Dict[str, Any], def _ticket_open(self, max_calls: Optional[int], max_usd: Optional[float], usd_per_call: Optional[float], *, - prior_calls: int = 0) -> Tuple[ + prior_calls: int = 0, registered: bool = True, + run_id: Optional[str] = None) -> Tuple[ Optional[Dict[str, Any]], Optional[int], Optional[Dict[str, Any]]]: """``(limit, applied, refusal)`` for one ``start`` / ``resume`` (#1082). @@ -621,13 +622,20 @@ def _ticket_open(self, max_calls: Optional[int], max_usd: Optional[float], named none, the caller's own number with no ceiling, ``None`` when neither -- and the refusal is the spent-Ticket reply. - ``prior_calls`` is the ledger a resumed run already carries. The child's - cap counts that ledger (``execute`` seeds ``Usage`` from it), so the - number it is relaunched with is ``prior + remaining``: passing the - remainder alone would stop it at once having "reached" a cap it already - went past. The reply says the same number it gave the child. A run whose - status cannot be read refuses here too, with its own sentence: that is - an unreadable ledger, not a spent one. + ``prior_calls`` is the ledger a resumed run already carries, and + ``registered`` says whether that ledger is already inside ``spent``. + + A run this server started (``registered``) is relaunched with + ``prior + remaining``: the child counts the ledger it resumes, and the + ledger is already charged to the Ticket, so this number stays inside the + ceiling and the reply says exactly what the child was given. A run it + did not start is not in ``spent``, so adding its ledger would grant the + ceiling twice over: its grant is the remainder itself, its earlier calls + counted inside that number, and a ledger that already fills the + remainder is refused by name instead of relaunched (#1082). + + A run whose status cannot be read refuses here too, with its own + sentence: that is an unreadable ledger, not a spent one. """ # Both of these raise reasons a host must hear as a refusal, not as a # traceback: `start` reaches this under the lock, outside the try that @@ -646,18 +654,29 @@ def _ticket_open(self, max_calls: Optional[int], max_usd: Optional[float], return limit, None, self._ticket_refusal(ticket, limit) applied = None if limit is None else limit.get("max_calls") if applied is not None and prior_calls > 0: - applied += max(0, int(prior_calls)) - limit = {**(limit or {}), "max_calls": applied} + if registered: + applied += max(0, int(prior_calls)) + limit = {**(limit or {}), "max_calls": applied} + elif int(prior_calls) >= int(applied): + # Its ledger is not in `spent` and already fills what is left: + # there is nothing to grant, and relaunching would bill the + # ceiling a second time (#1082). + return limit, None, {"ok": False, "error": ( + f"run {run_id or 'this run'} already carries " + f"{int(prior_calls)} call(s); this Ticket has " + f"{int(applied)} left. Retry in a new server session, or " + "raise the ceiling."), "call_limit": limit} return limit, applied, None def _ticket_reserve(self, run_id: str, applied: Optional[int], prior_calls: int = 0) -> None: """Register a run and the calls it holds until it reports (#1082). - ``prior_calls`` is what the ledger already holds: a resumed run is - charged for the calls it spent before this relaunch plus the cap it is - relaunched with. Registering a run this server already knows must not - list it twice, or the Ticket would charge it twice. + ``held`` is the grant itself: a registered run was given its ledger + plus the remainder, an external one only the remainder (its earlier + calls are counted inside that number). Registering a run this server + already knows must not list it twice, or the Ticket would charge it + twice. """ held = max(0, int(applied or 0)) + max(0, int(prior_calls)) if run_id not in self._ticket_runs: @@ -1064,9 +1083,9 @@ def resume(self, run_id: str, budget_usd: Optional[float] = None, with self._ticket_lock: before = runstore.get(run_id, store=self.store).status() prior = int(before.calls) + int(before.pending_calls) - limit, applied, refused = self._ticket_open(None, None, - usd_per_call, - prior_calls=prior) + limit, applied, refused = self._ticket_open( + None, None, usd_per_call, prior_calls=prior, + registered=run_id in self._ticket_runs, run_id=run_id) if refused is not None: return refused st = runstore.resume( diff --git a/changelog.d/1082-ticket-call-cap.md b/changelog.d/1082-ticket-call-cap.md index b74953c1..abeccbc8 100644 --- a/changelog.d/1082-ticket-call-cap.md +++ b/changelog.d/1082-ticket-call-cap.md @@ -12,3 +12,8 @@ refuses to start or resume anything until the run store is readable again, instead of granting a remainder that may already be spent. A `max_usd` without `usd_per_call` is still refused with the argument named in the message, now from inside the same gate (#1196). + +`resume` shares the same Ticket remainder as `start`: a run this server started +is relaunched with its ledger plus what is left, and a run it did not start is +registered and charged on its first resume here, its whole earlier ledger +counted, with no grant once that ledger fills the remainder. diff --git a/docs/dsh-super-agent.md b/docs/dsh-super-agent.md index fdac4841..e0041727 100644 --- a/docs/dsh-super-agent.md +++ b/docs/dsh-super-agent.md @@ -112,12 +112,19 @@ your tree, under the operator's write allowlist). `AGENTDESCENT_MAX_CALLS` set, the server spends it across the runs it starts: a second `start` is clamped to the remainder, its reply says `ticket: {ceiling, spent, remaining}`, and once the ceiling is spent `start` - refuses, and `resume` is held to the same remainder. Start the next Ticket in - a new server session (or raise the ceiling) rather than reusing the spent one - (#1082). + refuses. `resume` is held to the same remainder: a run this server started is + relaunched with its own ledger plus what is left, while a run it did not start + is relaunched with the remainder itself, its earlier calls counted inside that + number, and a run whose ledger already fills the remainder is refused instead + of relaunched. Start the next Ticket in a new server session (or raise the + ceiling) rather than reusing the spent one (#1082). Only the runs this server started are charged: a run it did not start (a CLI `evolve`, a run from another process) is outside the accounting unless it is resumed here, so mixing CLI and MCP runs inside one session is not covered. + Once an external run is resumed here its whole ledger is charged -- 2 calls + before plus 1 after counts as 3 spent, and the next `start` is refused -- and + its child is still clamped by the absolute ceiling, never by the remainder + alone. `AGENTDESCENT_MAX_CALLS` is the only operator ceiling and it is per-Ticket; a caller's `max_calls` and `max_usd` stay per-run flags, and only `max_calls` is clamped by what the Ticket has left (#1082). diff --git a/tests/test_mcp_ticket_cap.py b/tests/test_mcp_ticket_cap.py index 32bc828c..087dd345 100644 --- a/tests/test_mcp_ticket_cap.py +++ b/tests/test_mcp_ticket_cap.py @@ -318,3 +318,81 @@ def test_an_unreadable_run_refuses_instead_of_granting_the_rest(store, tmp_path, assert plan["ok"] is False, plan assert first["run_id"] in plan["error"], plan["error"] assert "cannot be accounted" in plan["error"], plan["error"] + + +def _external_run(tmp_path, store, name, max_calls): + """A run in the store that this server did not start: another process did. + + Its calls are real -- it is in a run directory -- but it is not in any + ``Tools._ticket_runs``, which is what makes it "external" to the Ticket the + resuming server holds (#1082). + """ + other = Tools(store) + started = _start_in(tmp_path, other, name, max_calls=max_calls) + st = _wait(runstore.get(started["run_id"], store=store)) + return started["run_id"], st + + +def test_a_resumed_external_run_cannot_exceed_the_ceiling(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + run_id, before = _external_run(tmp_path, store, "ext", max_calls=1) + assert before.calls == 1, before + + tools = Tools(store) + assert tools._ticket_spent() == 0, tools._ticket_spent() + resumed = tools.resume(run_id) + assert resumed.get("ok") is not False, resumed + # The remainder is the grant. The child counts the ledger it resumes (one + # call), so a cap of 3 lets it spend 2 more and stop the Ticket at 3. Today + # the reply says 4 -- the remainder plus a ledger that is not in `spent` -- + # while `launch` clamps the child back to the ceiling: the same grant + # mismatch this PR removes for `start`, re-entered through `resume`. + assert resumed["call_limit"]["max_calls"] == 3, resumed["call_limit"] + after = _wait_more(runstore.get(run_id, store=store), before.calls) + assert after.state == "done", after + assert _cap_in_detail(after) == resumed["call_limit"]["max_calls"], after.stop_detail + assert after.calls - before.calls <= 2, (before.calls, after.calls) + assert tools._ticket_spent() <= 3, tools._ticket_spent() + + +def test_a_resumed_external_run_is_charged_inside_the_ceiling(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + run_id, before = _external_run(tmp_path, store, "ext", max_calls=1) + assert before.calls == 1, before + + tools = Tools(store) + own = _start_in(tmp_path, tools, "own", max_calls=1) + own_st = _wait(runstore.get(own["run_id"], store=store)) + assert own_st.calls == 1, own_st + assert tools._ticket_spent() == 1, tools._ticket_spent() + + resumed = tools.resume(run_id) + # One call of the ceiling is this server's own, so two are left. The + # external ledger is not in `spent`: its grant is the 2 that remain, inside + # which its earlier call is counted, so the child spends 1 more and the + # Ticket totals 3. Today the ledger is added to the remainder the reply + # shows (3) and the child spends 2 more: the Ticket bills 4 of 3. + assert resumed["call_limit"]["max_calls"] == 2, resumed["call_limit"] + after = _wait_more(runstore.get(run_id, store=store), before.calls) + assert after.state == "done", after + assert _cap_in_detail(after) == resumed["call_limit"]["max_calls"], after.stop_detail + assert after.calls - before.calls == 1, (before.calls, after.calls) + assert tools._ticket_spent() <= 3, tools._ticket_spent() + + +def test_a_resumed_external_run_with_no_room_is_refused(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + run_id, before = _external_run(tmp_path, store, "ext", max_calls=3) + assert before.calls == 3, before + + tools = Tools(store) + # Its ledger already fills the ceiling the Ticket has left, and it is not + # charged to the Ticket, so there is no remainder to grant: relaunching it + # would hand out the ceiling a second time. Refuse, naming the run. + refused = tools.resume(run_id) + assert refused.get("ok") is False, refused + assert run_id in refused["error"], refused["error"] + assert "already carries 3 call(s)" in refused["error"], refused["error"] + assert "pid" not in refused, refused + after = runstore.get(run_id, store=store).status() + assert (after.state, after.calls) == ("done", 3), after From 27de7b67124cdc6ad7764e81e7ffbeac3eaae333 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Mon, 23 Nov 2026 01:27:58 +0000 Subject: [PATCH 6/7] fix(mcp): resume refuses a run whose status cannot be read `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`. --- agentdescent/mcp.py | 38 +++++++++++++++++++++++-------- docs/dsh-super-agent.md | 5 +++++ tests/test_mcp_ticket_cap.py | 43 ++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 9 deletions(-) diff --git a/agentdescent/mcp.py b/agentdescent/mcp.py index e1f9c681..6d031791 100644 --- a/agentdescent/mcp.py +++ b/agentdescent/mcp.py @@ -485,6 +485,19 @@ def _call_limit_payload(max_calls: Optional[int], max_usd: Optional[float], return payload +def _unreadable_run_error(run_id: str, e: BaseException) -> str: + """The sentence for a run whose status cannot be read (#1082). + + Fail-closed: a remainder computed over a run nobody can read may already be + spent. Restoring the status is the way back -- deleting the directory is + not, because the budget it freed cannot be verified. + """ + return (f"run {run_id} cannot be accounted: its status cannot be read " + f"({e}), so this Ticket's spend is unknown; no run may start or " + "resume until the run store is readable again. Restore a valid " + "status.json, or start a new server session.") + + class Tools: """The tool bodies, SDK-free. One instance per server, bound to a run store.""" @@ -578,10 +591,7 @@ def _ticket_spent(self) -> int: st = runstore.get(run_id, store=self.store).status() except (runstore.RunStoreError, ValueError, OSError) as e: raise runstore.RunStoreError( - f"run {run_id} cannot be accounted: its status cannot be " - f"read ({e}), so what this Ticket has spent is unknown; " - "no run may start until the run store is readable again. " - "Fix or remove that run directory, then retry.") from e + _unreadable_run_error(run_id, e)) from e charged = int(st.calls) + int(st.pending_calls) if st.state in ("done", "failed", "cancelled"): spent += charged @@ -1070,10 +1080,16 @@ def resume(self, run_id: str, budget_usd: Optional[float] = None, # a run that died on a spent quota is not relaunched into the same # 429 (#926, `force` opts out), and an absent plugin host must not # relaunch and report running (#370). - require_resume_not_solved(run_id, store=self.store) - if not force: - require_resume_not_quota_exhausted(run_id, store=self.store) - require_resume_host_on_path(run_id, store=self.store) + try: + require_resume_not_solved(run_id, store=self.store) + if not force: + require_resume_not_quota_exhausted(run_id, store=self.store) + require_resume_host_on_path(run_id, store=self.store) + except (ValueError, OSError) as e: + # These gates read the run's status too. A corrupt one is a + # refusal with a reason, not a traceback out of `resume` + # (#1082); a missing run stays a RunStoreError as before. + return {"ok": False, "error": _unreadable_run_error(run_id, e)} # One gate for both entry points (#1082): a resumed run belongs to # this Ticket too, so it is clamped to what is left and charged for # what it spends. It already carries a ledger, so the reservation is @@ -1081,7 +1097,11 @@ def resume(self, run_id: str, budget_usd: Optional[float] = None, # number the child gets, for the same reason `start` hands over the # enforced one: `launch` clamps only against the full ceiling. with self._ticket_lock: - before = runstore.get(run_id, store=self.store).status() + try: + before = runstore.get(run_id, store=self.store).status() + except (ValueError, OSError) as e: + return {"ok": False, + "error": _unreadable_run_error(run_id, e)} prior = int(before.calls) + int(before.pending_calls) limit, applied, refused = self._ticket_open( None, None, usd_per_call, prior_calls=prior, diff --git a/docs/dsh-super-agent.md b/docs/dsh-super-agent.md index e0041727..db5004de 100644 --- a/docs/dsh-super-agent.md +++ b/docs/dsh-super-agent.md @@ -125,6 +125,11 @@ your tree, under the operator's write allowlist). before plus 1 after counts as 3 spent, and the next `start` is refused -- and its child is still clamped by the absolute ceiling, never by the remainder alone. + A run whose status cannot be read is fail-closed: while its `status.json` is + missing or corrupt, `start`, `plan` and `resume` refuse rather than guess what + the Ticket spent, and the way back is to restore that file or start a new + session -- deleting the run directory does not help, because the budget it + freed cannot be verified. `AGENTDESCENT_MAX_CALLS` is the only operator ceiling and it is per-Ticket; a caller's `max_calls` and `max_usd` stay per-run flags, and only `max_calls` is clamped by what the Ticket has left (#1082). diff --git a/tests/test_mcp_ticket_cap.py b/tests/test_mcp_ticket_cap.py index 087dd345..06d7bed0 100644 --- a/tests/test_mcp_ticket_cap.py +++ b/tests/test_mcp_ticket_cap.py @@ -14,6 +14,7 @@ import os import re +import shutil import threading import time @@ -319,6 +320,17 @@ def test_an_unreadable_run_refuses_instead_of_granting_the_rest(store, tmp_path, assert first["run_id"] in plan["error"], plan["error"] assert "cannot be accounted" in plan["error"], plan["error"] + # Deleting the run does not free the budget: the Ticket still cannot prove + # what was spent, and the refusal has to say so instead of suggesting it. + shutil.rmtree(runstore.get(first["run_id"], store=store).path) + gone_sub = tmp_path / "t3" + gone_sub.mkdir() + gone = tools.start(_dir_spec(str(gone_sub)).to_dict()) + assert gone["ok"] is False, gone + assert "Restore a valid status.json" in gone["error"], gone["error"] + assert "start a new server session" in gone["error"], gone["error"] + assert "remove that run directory" not in gone["error"], gone["error"] + def _external_run(tmp_path, store, name, max_calls): """A run in the store that this server did not start: another process did. @@ -396,3 +408,34 @@ def test_a_resumed_external_run_with_no_room_is_refused(store, tmp_path, monkeyp assert "pid" not in refused, refused after = runstore.get(run_id, store=store).status() assert (after.state, after.calls) == ("done", 3), after + + +def test_resume_refuses_when_the_run_status_cannot_be_read(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=1) + st = _wait(runstore.get(first["run_id"], store=store)) + assert st.calls == 1, st + + rd = runstore.get(first["run_id"], store=store) + good = open(rd.status_path, encoding="utf-8").read() + with open(rd.status_path, "w", encoding="utf-8") as fh: + fh.write("{not json") + # `resume`'s pre-gates read the run's status before the Ticket gate does: a + # corrupt file must come back as a refusal naming the run, not as the + # `JSONDecodeError` the file itself raises. + refused = tools.resume(first["run_id"]) + assert refused.get("ok") is False, refused + assert first["run_id"] in refused["error"], refused["error"] + assert "cannot be accounted" in refused["error"], refused["error"] + # Not relaunched: the corrupt status was not rewritten into a `running` one. + assert open(rd.status_path, encoding="utf-8").read() == "{not json" + + # Restoring the file is the way back, and `resume` works again. + with open(rd.status_path, "w", encoding="utf-8") as fh: + fh.write(good) + resumed = tools.resume(first["run_id"]) + assert resumed.get("ok") is not False, resumed + after = _wait(runstore.get(first["run_id"], store=store)) + assert after.state == "done", after + assert after.calls == 3, after From 18c333d935e0aed1cde07fb6e89ab267ed62156c Mon Sep 17 00:00:00 2001 From: HugoXK Date: Mon, 23 Nov 2026 01:41:48 +0000 Subject: [PATCH 7/7] fix(mcp): a decided resume refusal is not an unreadable store 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. --- agentdescent/mcp.py | 10 +++++++++ tests/test_mcp_ticket_cap.py | 39 ++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/agentdescent/mcp.py b/agentdescent/mcp.py index 6d031791..fbe2a597 100644 --- a/agentdescent/mcp.py +++ b/agentdescent/mcp.py @@ -1085,6 +1085,12 @@ def resume(self, run_id: str, budget_usd: Optional[float] = None, if not force: require_resume_not_quota_exhausted(run_id, store=self.store) require_resume_host_on_path(run_id, store=self.store) + except SpecError: + # The gates refuse with `SpecError`, a `ValueError`: the status + # is readable and the refusal is decided (solved, quota, host), + # so it keeps its own sentence instead of becoming "cannot be + # accounted" (#1082). + raise except (ValueError, OSError) as e: # These gates read the run's status too. A corrupt one is a # refusal with a reason, not a traceback out of `resume` @@ -1099,6 +1105,10 @@ def resume(self, run_id: str, budget_usd: Optional[float] = None, with self._ticket_lock: try: before = runstore.get(run_id, store=self.store).status() + except SpecError: + # Same reason as the gates above: a decided `SpecError` + # out of the store is not an unreadable status (#1082). + raise except (ValueError, OSError) as e: return {"ok": False, "error": _unreadable_run_error(run_id, e)} diff --git a/tests/test_mcp_ticket_cap.py b/tests/test_mcp_ticket_cap.py index 06d7bed0..283cd0d1 100644 --- a/tests/test_mcp_ticket_cap.py +++ b/tests/test_mcp_ticket_cap.py @@ -439,3 +439,42 @@ def test_resume_refuses_when_the_run_status_cannot_be_read(store, tmp_path, monk after = _wait(runstore.get(first["run_id"], store=store)) assert after.state == "done", after assert after.calls == 3, after + + +def test_a_solved_run_still_refuses_as_solved_not_unreadable(store, tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=1) + rd = runstore.get(first["run_id"], store=store) + st = _wait(rd) + assert st.calls == 1, st + rd.update_status(state="done", stop_reason="target_reward") + + # The status file is readable, so the refusal has to stay the #900 one: + # `SpecError` is a `ValueError`, and the wrap that turns an unreadable + # status into a refusal must not swallow it and send the operator to + # restore a file that is fine (#1082). + refused = tools.resume(first["run_id"]) + err = refused.get("error") or "" + assert "already reached its target" in err, refused + assert "cannot be accounted" not in err, refused + after = rd.status() + assert (after.state, after.stop_reason) == ("done", "target_reward"), after + + +def test_a_quota_spent_run_still_refuses_as_quota_not_unreadable(store, tmp_path, + monkeypatch): + monkeypatch.setenv("AGENTDESCENT_MAX_CALLS", "3") + tools = Tools(store) + first = _start_in(tmp_path, tools, "t0", max_calls=1) + rd = runstore.get(first["run_id"], store=store) + assert _wait(rd).calls == 1 + rd.update_status(state="failed", stop_reason="error", + error="QuotaExhausted: the quota resets at 2026-11-24 " + "00:00:00 +0800 CST") + + refused = tools.resume(first["run_id"]) + err = refused.get("error") or "" + assert "failed on QuotaExhausted" in err, refused + assert "cannot be accounted" not in err, refused + assert rd.status().state == "failed", rd.status()