diff --git a/agentdescent/mcp.py b/agentdescent/mcp.py index 6321bb80..fbe2a597 100644 --- a/agentdescent/mcp.py +++ b/agentdescent/mcp.py @@ -33,7 +33,8 @@ import json import os import secrets -from typing import Annotated, Any, Dict, Optional, Sequence, Tuple +import threading +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 +433,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: the reason is the same, while the actionable hint @@ -447,6 +449,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, @@ -457,16 +466,38 @@ 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 +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.""" @@ -504,6 +535,21 @@ 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] = [] + #: 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. @@ -521,6 +567,150 @@ 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. ``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 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) as e: + raise runstore.RunStoreError( + _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 + 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, 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). + + 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, 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 + # 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) + applied = None if limit is None else limit.get("max_calls") + if applied is not None and prior_calls > 0: + 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). + + ``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: + 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, @@ -717,7 +907,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,9 +961,6 @@ 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) except SpecError as e: return {"ok": False, "error": str(e)} except runstore.RunStoreError as e: @@ -799,23 +987,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 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 @@ -877,13 +1080,56 @@ 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) - 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() + 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 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` + # (#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 + # 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: + 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)} + prior = int(before.calls) + int(before.pending_calls) + 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( + 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 new file mode 100644 index 00000000..abeccbc8 --- /dev/null +++ b/changelog.d/1082-ticket-call-cap.md @@ -0,0 +1,19 @@ +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). 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). + +`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 9aa4fdbc..db5004de 100644 --- a/docs/dsh-super-agent.md +++ b/docs/dsh-super-agent.md @@ -108,6 +108,31 @@ 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. `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. + 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). - 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..283cd0d1 --- /dev/null +++ b/tests/test_mcp_ticket_cap.py @@ -0,0 +1,480 @@ +"""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 os +import re +import shutil +import threading +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 _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 _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() + 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} + 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) + # 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): + 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_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) + 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"] + + +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) + +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"] + + # 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. + + 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 + + +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 + + +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() 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)