Skip to content

Finish the pre-charge cleanup: faults that pull request 279 leaves held #283

Open

Description

@PetrefiedThunder

Summary

Pull request #279 (for #278) releases the consumed quote, the owned idempotency record and the enterprise (IGA) use for ledger contention and for faults before the permit reserve. An independent review of #279 at b852652 (10 agents; probes run on the PR head and on main) found no blocker, no double release and no regression, and no money-safety invariant broken. It also listed the gaps below that #279 deliberately or incidentally leaves. Apart from the one inaccurate comment in item 2, each is identical on main, so none is a regression. This issue tracks them together so the pieces are scoped once.

Verification column: "verified" means a second agent reproduced it with a probe and tried to refute it; "reported" means a reviewer claimed it and no verifier ran (the review ran out of verifier slots), so treat it as a lead.

Items

  1. A generic fault at the quote consume strands the key, the reservation and the call slot (verified, minor, same on main). Local tool, permit max_calls=1, signed quote. The reserve succeeds (spent credits and tool call count move), then QuoteService.consume raises once. The wrapper re-raises past the marker without abandoning. Observed on the PR head and on main: the first call answers internal_error, the record stays in progress, the retry answers idempotency_in_progress, a fresh key on the same permit answers permit_max_calls_exceeded, and reconcile_stuck_records does nothing. A capped permit becomes unusable. Fix direction: nothing has been released between the reserve and the consume, so a try/except around the consume can use the primitives the lost-quote branch already uses (_release_local_permit_reservation locally; abandon_effect_free_prepared_attempt for a remote prepared attempt). Leave the quote alone there: the fault is commit-uncertain and QuoteService.release is not keyed to the consumer. The test test_a_fault_after_the_reserve_does_not_free_the_key_over_a_held_reservation pins the stranded state as intended, so the fix has to invert it. This is the part of Release the quote, the permit reservation and the idempotency record on every pre-charge fault #278 ("any exception that escapes before the charge checkpoint") that Release the quote and the idempotency record on pre-charge faults #279 does not cover.
  2. Audit or receipt contention in a post-reserve denial branch frees the key but not the IGA use (verified, minor). The comment and PR text say inner branches release their own use; at the post-reserve permit-denied branch with audit contention none does, so the advised retry is refused iga_max_uses_exceeded when max_uses is set. The comment in gateway/app/routers/mcp.py near the wrapper's IGA release is inaccurate for this case.
  3. Builtin exception types are exempt from the pre-reserve sweep (verified, nit; reviewers rated up to major). _RECORD_KEEPING_ERRORS includes ValueError, PermissionError and HTTPException by type, because the code raises them deliberately after recording a denial. A library-raised instance of the same types in the pre-reserve span still strands the key and the IGA use. Fix direction: mark the deliberate ones (a dedicated exception type or an attribute) instead of exempting by builtin type.
  4. human_approval_pending / unavailable abandons the record but never returns the IGA use (verified, minor, same on main). The documented retry with the same key then hits iga_max_uses_exceeded when max_uses is set (the IGA gate runs before the approval gate).
  5. Remote tool with a quote: a generic pre-charge fault leaves the quote consumed (verified, nit, same on main). After _repair_pre_dispatch reconciles and the record completes as failed_refunded, a new key with the same quote is refused quote_already_consumed.
  6. Abandon-then-release race (reported by CodeRabbit after READY FOR QA and by a reviewer; traced safe by the author, not probed by a verifier). The wrapper abandons the idempotency record and then returns the IGA use. A duplicate concurrent request with the same key landing between the two is refused iga_max_uses_exceeded and that denial is stored for the key, so that key is poisoned. No money moves and a new key works. Closing it needs the IGA counters and the database abandon to commit together; there is no primitive for that today. The action path uses the same order.
  7. Test gaps (reported, not verified): mutants of the _RECORD_KEEPING_ERRORS constant, the redundant generic_precharge disjunct and the reason strings survive the PR's test files; two narrower variants of an unconditional IGA release survive both PR test files (killed only by other files); no PR test touches a prepared remote dispatch attempt; the post-charge negative test does not discriminate the wrapper guard because abandon() refuses a record with a ledger entry on its own. One reviewer claim was refuted: single-shot cleanups (one lost write in a cleanup) are the existing pattern on main and not a defect.

Acceptance

For each item fixed: a test that fails without the fix and asserts side effects (record, reservation counters, IGA use counters, quote state), not only the status; the pinned test in item 1 inverted deliberately; no double release of the permit reservation, the quote or the IGA use; a post-charge fault still keeps the record and the quote.

Out of scope here: reservation release made keyed per invocation (the permit-wide counters are clamped decrements, which is why a blind second release over-refunds); that would be its own change.

Activity

  1. added
    bug
    on Nov 1, 2026
  2. PetrefiedThunder commented on Nov 4, 2026

    @PetrefiedThunder
    CollaboratorAuthor

    Item 6 (abandon-then-release race): accepted by the maintainer on 2026-11-04 (recorded by the coordinating session on their instruction; see #279). It stays a documented known limit: the failure is bounded (no money moves, a new key works), the action path uses the same order, and closing it needs a primitive that commits the IGA counters and the database abandon together. Revisit only if such a primitive appears.

    The other items (1 to 5 and 7) are unchanged and start after #279 merges.


    Generated by Claude Code

  3. PetrefiedThunder commented on Nov 5, 2026

    @PetrefiedThunder
    CollaboratorAuthor

    Item 3 is partly closed by #279 (recorded by the coordinating session, 2026-11-05).

    QA agent codex failed #279 at ab5283a on exactly this item: a bare ValueError in _RECORD_KEEPING_ERRORS kept the idempotency record for unexpected ValueErrors (a json.JSONDecodeError, a driver error) raised after the record is granted and before the reserve, so every retry met idempotency_in_progress. The PR now fixes the ValueError part: a ValueError is kept only when _value_error_jsonrpc_code recognises its text (the set the pipeline raises on purpose); any other takes the generic pre-charge release. Tests: an unexpected ValueError and a JSONDecodeError, each injected at two points before the reserve; the same two kinds on the IGA max_uses=1 retry; a guard that a classified ValueError ("Tool not found" on a permitted call) keeps its own cleanup. A mutation back to the old behaviour fails exactly the six new cases. One intended side effect: tool_price_invalid, which is raised after the record is granted on a permitted invoke, now frees the key too (its comment is corrected in the PR).

    What stays open under item 3:

    • PermissionError is still exempt by builtin type. It subclasses OSError, so an unexpected filesystem PermissionError in the pre-reserve span has the same shape. All six places in mcp.py that raise it on purpose do so as PermissionError(reason) (lines 1822, 1997, 2012, 2373, 2465, 2805), which carries no errno; an OS-raised one always does. Fix direction: keep a PermissionError only when exc.errno is None, or mark the deliberate ones with a dedicated type as the item already suggests.
    • HTTPException is still exempt by type. Not traced for a library-raised instance.

    Item 7 (test gaps): the surviving mutants of _RECORD_KEEPING_ERRORS are now killed for ValueError. They still survive for PermissionError and HTTPException.

    Item 6 stays accepted as recorded above. The other items are unchanged and start after #279 merges.


    Generated by Claude Code

  4. PetrefiedThunder commented on Nov 5, 2026

    @PetrefiedThunder
    CollaboratorAuthor

    Test-hygiene note from #279 (recorded by the coordinating session, 2026-11-05), relevant to item 7 and to every test that stubs a service.

    CI force-installs pytest 9.1.1 (PYTEST_VERSION in .github/workflows/ci.yml) over gateway/requirements.txt, which says pytest>=9.2.0. Under 9.1.1, monkeypatch.undo() of an INSTANCE attribute on a singleton service restores it by assigning the saved bound method instead of deleting the attribute. The singleton then keeps a stray copy of the method for the rest of the worker's life. Under 9.2.0 the attribute is deleted and nothing is left behind.

    That broke #279's CI on Python 3.11, 3.13 and 3.14 (while it passed locally, on 3.12 and with 9.2.0): a new test patched complete on get_idempotency_service(), and three older tests (test_mcp_trust.py around lines 1210 and 1400, test_x402.py around 1344, test_acp_bridge.py around 1124) patch IdempotencyService.complete on the CLASS, which the stray instance copy bypasses. Whether a given run failed depended on how pytest-xdist scheduled the tests onto workers.

    Rule for tests added under this issue and elsewhere: patch service methods on the CLASS (monkeypatch.setattr(IdempotencyService, "complete", ...), restored exactly), never on a singleton instance. #279 now does this through a _fail_once_on(monkeypatch, cls, name, error) helper.

    Separate from this issue: the pytest pin in CI does not match the version the requirements declare, so Dependabot's pytest bumps do nothing in CI. That is raised with the maintainer.


    Generated by Claude Code

  5. PetrefiedThunder commented on Nov 5, 2026

    @PetrefiedThunder
    CollaboratorAuthor

    Update to the test-hygiene note above (2026-11-05): the CI pytest pin mismatch it mentions is fixed. #313 (closes #312) merged at 10:33 UTC as 1ab98dc: CI now installs pytest 9.2.0, every pytest install in ci.yml uses PYTEST_VERSION, and gateway/tests/test_dev_tool_pins.py fails if the pin stops satisfying the floor in gateway/requirements.txt. The grok QA pass on #313 also noted that the stray-method behaviour of monkeypatch.undo() on an inherited instance attribute is fixed upstream in pytest 9.2.0 (pytest issue 10644).

    The rule for tests stays as good hygiene: patch service methods on the class, not on a singleton instance, so the tests do not depend on the installed pytest version. #279 does this through its _fail_once_on helper.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions