Skip to content

Follow-up to #330: an unsigned pending refund can be stored for a charge already refunded, the disabled-key operator retry question, and test gaps #435

Backlog

Description

@PetrefiedThunder

Summary

A review of #330 on 2026-11-27 found three things. They were rechecked at the #330 head on 2026-11-29 and 2026-11-30 (UTC).

  1. A race can store "refund pending, receipt unsigned" for a charge that is already refunded. No wallet money moves wrongly: the charge is refunded once and the permit reservation is released. The record and the caller's answer are wrong, and the call gets no receipt. It is hard to reach: it needs a failed refund, a direct database edit of the key row between two steps of one request, and a competing retry or a stalled request. It is new with fix(refunds): record a pending refund even when its receipt cannot be signed #330.
  2. A product question: while the key that signed a permit is disabled, the operator retry of that call's pending refund refuses.
  3. Test gaps in fix(refunds): record a pending refund even when its receipt cannot be signed #330.

Affected area

  • spec
  • verifier
  • Python SDK
  • TypeScript SDK
  • integration
  • example
  • gateway
  • build or tooling
  • Other:

Version or commit

#330 at 893ac66b0a4bb7eade65f643c16bb4cb0f87ac02, compared with main at 57ac9a919766a8d8db324666ddb16226cf2940fb. #331 at c82007485a606e210205dce9d4bb28b8c33fa49a was read, not run. Line numbers are at the #330 head. Tests ran on SQLite unless stated.

1. Unsigned pending record for a refunded charge (low)

  • Where: gateway/app/routers/mcp.py, _raise_refunded_upstream_failure (refund 3856 to 3866, audit write 3869); gateway/app/services/refund_reconciliation.py, _record_unsigned_pending (516 to 573).
  • Actual: an upstream call returns an error and its live refund fails. The audit write succeeds, then the key cannot sign, so create_pending stores an unsigned item. If the dispatch reconciler handles the attempt before that write, it refunds and releases the reservation but writes no receipt. It gets there through a same-key retry (idempotency.py 368 to 419), or through the sweep, which runs every 300 s and takes terminal attempts idle for 300 s (main.py 252 and 326). Then the live path stores the unsigned item. End state:
    • one refund row, wallet balance and permit spend as before the call, no receipt;
    • after the key row is active again, the signer refuses the item on each pass and logs refund_reconciliation_unsigned_already_refunded at error level (663 to 679);
    • the dispatch reconciler skips it (mcp_dispatch_attempts.py 2158 to 2169);
    • the operator refund list does not show it (808 to 868);
    • a replay returns refund_reconciliation.status pending with receipt_id null.
  • Expected: the record matches the ledger. On main the attempt gets a failed_refunded receipt once the key row is active again.
  • Preconditions, all needed:
    • the live refund or its checkpoint write fails;
    • the key row becomes disabled after the audit write and before create_pending signs. No product code writes disabled, so this takes a direct database edit, as in the compromise steps (gateway/docs/key-management.md, line 158);
    • in that window, on a replica whose key cannot sign, a same-key retry, or a stall of more than 300 s that lets the sweep run. A retry on a replica that can sign ends with a failed_refunded receipt (tested at fix(refunds): record a pending refund even when its receipt cannot be signed #330).
  • fix(trust): a retired signing key refuses to sign instead of reactivating #331, by code reading: its check at mcp.py line 1220 (at fix(trust): a retired signing key refuses to sign instead of reactivating #331) refuses a request on a replica whose key cannot sign, before the idempotency record is read. That closes the retry path, not the sweep.
  • Evidence: a scratch test, available on request, forces this order: refund (or checkpoint) failure, key row disabled right after the audit write, competitor right before create_pending. All four variants give the end state above at fix(refunds): record a pending refund even when its receipt cannot be signed #330, and the receipt above on main. Commit 0c3790ae8fd1c7724d983e31d4bc634e86dc4a32 does not change this path.

2. Question: should the operator retry depend on the permit key's status?

  • Where: _retry_locked, refund_reconciliation.py:1039 to 1045 (receipt check) and 1073 to 1079 (permit check).
  • Actual, tested at fix(refunds): record a pending refund even when its receipt cannot be signed #330 (local and upstream tools): the key row is set to disabled during a call, and a second key signs the unsigned item. The operator retry answers 409 refund_reconciliation_permit_invalid. The same-key replay answers permit_signature_invalid. In the local-tool test, after the old key row is set back to active, one retry refunds the charge once, and a second retry refunds nothing more.
  • Tested on both commits: a pending refund whose receipt was signed by the key that is later disabled is refused with 409 refund_reconciliation_receipt_invalid. The receipt check runs first.
  • Compared with main, tested: for an upstream call whose key is disabled after the audit write and stays disabled, main's sweep refunds the charge. At fix(refunds): record a pending refund even when its receipt cannot be signed #330 it stays charged: the item stays unsigned while no key can sign, and once a second key signs it, the operator retry refuses as above.
  • No product code is written to move a key out of disabled: _assert_key_not_disabled guards the status writes (signing_keys.py:271 to 275). Exceptions, tested on 2026-12-01 at 707ba29 and at main 37618e0, where this file is the same as at this head (item 7 in the comments below): ensure_active_key (277 to 298) reads the key row without a lock and writes active when it read retired, so a disabled committed between that read and that write is overwritten. fix(trust): a retired signing key refuses to sign instead of reactivating #331 removes that write. retire_key_metadata and rotate_active_key_metadata have the same gap, and fix(trust): a retired signing key refuses to sign instead of reactivating #331 does not change them. Each case needs a direct database edit to disabled inside the window of one call. The ensure_active_key case also needs the row to be retired first, and the other two need a manual call to the method. No other refund route for this charge was found. failure-semantics.md (371 to 392) documents the refusals.
  • Question: should an operator's retry of a refund to the charged wallet depend on the status of the key that signed the permit? In the tests above the charge stayed unrefunded for as long as the key row stayed disabled.

3. Test gaps

  • No CI job runs tests/test_refund_reconciliation_unsigned.py on PostgreSQL. The python job uses SQLite (tests/conftest.py:137 to 140). The PostgreSQL jobs list their files (ci.yml 423 and 529 to 583), and this file is not listed.
  • On PostgreSQL 16 at the head the file gives 8 failed, 1 passed, 9 errors (asyncpg "attached to a different loop"). tests/test_refund_reconciliation.py, older than fix(refunds): record a pending refund even when its receipt cannot be signed #330, fails the same way.
  • The reconciler half of 0c3790ae8fd1c7724d983e31d4bc634e86dc4a32 has no behavior test. test_a_denial_that_repeats_the_marker_name_is_not_an_unsigned_item checks statement text (699 to 717), and each checked substring ends in " OR ". A scratch run that moved the response_json IS NULL condition last, with the same logic, made the test fail.
  • Every test that signs or refunds an unsigned item first sets the key row back to active (test_refund_reconciliation_unsigned.py:204, 242, 328, 400, 526, 532, 682, 750; test_mcp_upstream_governed.py:3510, 3565, 3624). None keeps the first key disabled while a second key signs.
  • On the upstream path, no test makes the key unusable before the audit write. _upstream_refund_failure_with_key_lost (test_mcp_upstream_governed.py:3373) disables it right after.

Suggested next step

  • Part 1, a direction, not tested: in the locked write of _record_unsigned_pending (line 539), read the dispatch attempt and store nothing when debit_refunded_at and budget_released_at are both set. The reconciler does not take that lock before it refunds, so this narrows the window but does not close it.
  • Part 2: a maintainer decision.
  • Part 3: add the two missing tests, and a PostgreSQL run once the harness supports it.

Refs #330, #331, #422. Related: #434, a different defect in the same _retry_locked.

Edited 2026-11-30: one sentence in part 2 was corrected. It said that no product code moves a key out of disabled, without the ensure_active_key exception. Edited 2026-12-01: that passage now says the exception was tested and names two more methods with the same gap.


Generated by Claude Code

Activity

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

    @PetrefiedThunder
    CollaboratorAuthor

    Additions at the maintainer's request on 2026-11-30. CodeRabbit re-reviewed #330 at head 707ba293ade3b2de06ff1ac7e5646a4d0411b25c and opened three threads. Each was checked against the code and by test. None of them is changed in #330. Each thread gets a reply that links to this comment, and is then resolved. Line numbers are at 707ba29. Tests ran on SQLite.

    4. Doc sentences that the unsigned path makes inexact (docs only)

    • Thread: fix(refunds): record a pending refund even when its receipt cannot be signed #330 (comment)
    • Decision: the maintainer chose on 2026-11-30 to defer this to a follow-up. No wording commit goes onto fix(refunds): record a pending refund even when its receipt cannot be signed #330 or fix(trust): a retired signing key refuses to sign instead of reactivating #331 for it now.
    • gateway/docs/failure-semantics.md line 55 says for failed_unrefunded: "a durable operator work item is created atomically with the receipt". Lines 361 to 362 say the system "signs failed_unrefunded atomically with a durable reconciliation work item". Neither has an exception. With fix(refunds): record a pending refund even when its receipt cannot be signed #330 the work item can be stored without a receipt, so line 55 is false for that path and lines 361 to 362 are incomplete. On main the same words are true.
    • Replacement text, checked against the strings that other tests pin:
      • Line 55, Wallet cell: "Charged; a durable operator work item is created atomically with the receipt when the receipt can be signed, and without a receipt when it cannot (see "Refunds are written at most once")"
      • From "pretend:" on line 361 to "later." on line 363: "pretend: when the receipt can be signed, it signs failed_unrefunded atomically with a durable reconciliation work item, and an operator (bootstrap-admin only) retries it later. When it cannot, the work item is still recorded, without a receipt, as described below." The sentence after it stays.
    • Same section, lines 402 to 404: "the operator retry then finds that refund, refunds nothing more, and releases the reservation once". Its own sentence has no condition. The condition is two sentences earlier, at lines 393 to 396: a retry that finds the signing key that signed the call's permit disabled refuses, "also in the case described next". Optional, so that the sentence is true on its own: end it with "and releases the reservation once, unless the signing key that signed the call's permit is disabled."

    5. A docstring and a comment that overstate what the sweep leaves alone (text only)

    6. The signer does not compare the stored request hash with the record (minor)

    • Thread: fix(refunds): record a pending refund even when its receipt cannot be signed #330 (comment)
    • Decision: the maintainer chose on 2026-11-30 to leave this as it is. It is recorded here so the reasoning is not lost.
    • Actual, tested: sign_unsigned_pending passes inputs.request_hash from the stored marker to create_pending (line 700) and on to create_receipt, which only checks that it is 64 hex characters (gateway/app/services/receipts.py lines 557 to 564). With only that field changed by a direct database write, the signer signed a receipt that carries the changed hash, and verify_model returned True for it.
    • Reach: a direct write to idempotency_records, or data corruption. No product route under gateway/app was found that writes inside a stored marker. The same actor can also change the record's own request_hash column, which defeats a comparison, and every other marker field that the signer signs.
    • No money moves because of this. The checkpoint compares ledger_entry_id, and the operator retry compares the charge amount with the item's credits.
    • The live path has no explicit comparison either. There the two hashes are equal because both are computed from the same payload in the same request (tested: equal).
    • If it is revisited: after the response-hash check (lines 680 to 689), the signer could compare inputs.request_hash with the record's request_hash and skip the item on a mismatch, with a test. That would be a consistency check against a one-field edit or corruption. It is not a security boundary.
    • Before such a check is added: it was not tested that the two hashes are equal on the action_identity path (gateway/app/routers/mcp.py lines 1733 to 1736). If they differ there, the check would refuse legitimate items and they would stay unsigned.

    Nothing here was run on PostgreSQL.

    Edited 2026-11-30: added the test gap bullet under item 5.


    Generated by Claude Code

  3. PetrefiedThunder commented on Dec 1, 2026

    @PetrefiedThunder
    CollaboratorAuthor

    Two more verified items, added on 2026-12-01. The maintainer asked for a worker session's follow-up list to be checked. Line numbers are at 707ba293ade3b2de06ff1ac7e5646a4d0411b25c unless stated.

    7. A committed disabled can be overwritten in a narrow race (low, tested)

    This replaces "by code reading, not run" in part 2 of the issue body.

    • Where: gateway/app/services/signing_keys.py, the same file on main 37618e0 and at 707ba29. ensure_active_key (line 277) reads the key row without a lock (lines 281 to 286), checks for disabled on that read (line 292), and writes active when the row it read was retired (lines 295 to 297). The UPDATE selects by key id only.
    • Tested on SQLite and on PostgreSQL 16 at READ COMMITTED, on main and at 707ba29: with the row retired, a disabled that another session commits after the read is overwritten with active. The key is then published again and signs again, and a signature made before the disable verifies again. The compromise steps in gateway/docs/key-management.md (lines 158 to 163) say that must not happen.
    • Not overwritten: when the row read was active with retired_at set, the write does not touch status, and the next signature is refused. When disabled is committed before the read, the call refuses with signing_key_disabled.
    • fix(trust): a retired signing key refuses to sign instead of reactivating #331 at 6af04421c0900c7808b3d84328ae8f12dfc6b7cd: ensure_active_key never rewrites an existing row (lines 340 to 343 there). Tested: the call refuses with signing_key_retired and the row stays disabled. So fix(trust): a retired signing key refuses to sign instead of reactivating #331 removes this case. Do not reactivate a retired signing key on sign #280 tracks its root cause.
    • Two service methods have the same gap. fix(trust): a retired signing key refuses to sign instead of reactivating #331 does not change them, and Do not reactivate a retired signing key on sign #280 does not cover them:
      • retire_key_metadata (lines 376 to 390): a concurrent disabled becomes retired, so the key is published again and its old signatures verify again. Tested.
      • rotate_active_key_metadata (lines 392 to 439): a concurrent disabled on the target row becomes active. Tested. By reading, a concurrent disabled on the old row would become retired (lines 417 to 420).
      • The tests ran on all three commits, on SQLite and PostgreSQL 16. Neither method has a route or script caller today.
    • Reach: for ensure_active_key, the row must already be retired. In product code only the two methods above write retired, so that takes a manual call to one of them or a direct database edit. An operator must then set disabled by a direct database edit inside one call by a process configured with that key. For the two methods, a manual call to the method must run at the same moment as that edit. No money moves and no permit limit changes.
    • Not tested: on PostgreSQL, a disabled in a transaction that is still open when the write runs. Only a disabled that was already committed was run.
    • Suggested fix for the two methods: read the row with with_for_update=True and populate_existing=True before the check, as validate_prepared_signing_key already does (lines 445 to 464). Or make the UPDATE conditional on status != 'disabled' and check the row count.

    8. The stale-budget sweep gives back the reservation of a still-unsigned item on a revoked or expired permit (low, new with #330)

    • Where: gateway/app/services/permits.py. reconcile_budgets (line 2029) takes permits that are not active or are past expires_at and have been idle for 900 seconds, and sets their spent_credits to what _consumed_credits (lines 1834 to 2002) counts. That function counts receipts. A pending item with a failed_unrefunded receipt is counted. An unsigned item has no receipt and is not counted.
    • Actual, tested at 707ba29 for a revoked permit and for an expired permit, each with no other spend: the pass set spent_credits from 2 to 0 while the charge was still unrefunded. After the signer signed the item, the operator retry answered 409 refund_reconciliation_budget_conflict. A later pass counted the new receipt and set spent_credits back to 2. A second operator retry then refunded once (balance back to 1000, one refund row).
    • With one earlier paid call on the permit, tested for both kinds of permit: the pass set spent_credits from 4 to 2. The operator retry then succeeded at once and decremented again on the dead permit (2 to 0). The next pass set it back to 2.
    • Pass order: in one periodic pass reconcile_budgets (gateway/app/main.py line 377) runs before sign_unsigned_pending (line 402). So a key that is usable again before the pass does not prevent the reset (tested).
    • Cost: the refund is delayed until a later reconcile_budgets pass and another operator retry. The reset writes updated_at, so that pass comes at least 900 seconds after the reset. Nothing retries on its own. No run refunded the charge more than once, and each of the four runs above ended with one refund. The revoked or expired permit admitted nothing (permit_revoked or permit_expired).
    • On main there is no unsigned item. With the key unusable, the dispatch sweep refunded and released, and reconcile_budgets had nothing to correct (tested for a revoked permit only).
    • Suggested fix, not tested: in _consumed_credits, also count a charged call on the permit that is still owed back and has no receipt. Or skip the reset for a permit that still has such an item.
    • Where it comes from: gateway/app/services/permits.py is the same file on main, at 707ba29 and at the fix(trust): a retired signing key refuses to sign instead of reactivating #331 head. The behavior is new with fix(refunds): record a pending refund even when its receipt cannot be signed #330 because fix(refunds): record a pending refund even when its receipt cannot be signed #330 adds the unsigned item. gateway/app/services/refund_reconciliation.py is the same file at 707ba29 and at the fix(trust): a retired signing key refuses to sign instead of reactivating #331 head. Item 8 was not run at the fix(trust): a retired signing key refuses to sign instead of reactivating #331 head.

    Limits: item 8 ran on SQLite only, with expiry and idle time simulated.


    Generated by Claude Code

  4. PetrefiedThunder commented on Dec 5, 2026

    @PetrefiedThunder
    CollaboratorAuthor

    One more verified item, added on 2026-12-05 at the maintainer's request. CodeRabbit reviewed #331 at head 3ccfb093337b54dee76e17988d3dbbded00782ed and put one finding in its review body (review 6200537134, no thread). It was checked by reading and with a local test that was not committed or pushed. Line numbers are at 3ccfb09. Tests ran on SQLite. No commit has been added to #331 for it, and no fix has been decided.

    9. Upstream refund-failed path: a key that becomes unusable before the terminal audit write leaves no pending item (low, tested)

    This extends the last bullet of part 3 in the issue body, which lists only the missing test.

    • Where: gateway/app/routers/mcp.py, _raise_refunded_upstream_failure. In the refund-failed branch (line 3882) the terminal audit event is written first (line 3884), and _finalize_unrefunded_failure runs after it (line 3906). The audit call has no error handling around it. The local-tool path has: it catches a failed audit write (lines 3141 to 3169) and still calls the finalizer (line 3171).
    • Actual, tested: an upstream call is charged and returns an error, the live refund fails, and the configured key row is set to retired after the pre-charge check and before that audit write. The audit write raises signing_key_retired (gateway/app/services/audit_chain.py line 281, gateway/app/services/signing_keys.py line 319). _audit_mcp_invocation catches only AuditChainContendedError, so the finalizer never runs. Right after the call:
      • the caller gets -32603 internal_error, with no receipt and no refund_reconciliation data;
      • no unsigned pending item is stored. The operator refund list was still empty after all four passes;
      • with a 1000-credit wallet and a 2-credit call: balance 998, no refund row, permit spent_credits 2;
      • the dispatch attempt is returned_error with debit_refunded_at and budget_released_at unset, and the idempotency record is still in progress.
    • Recovery, tested by calling the cleanup passes in the app's order:
      • first dispatch reconcile pass, key still retired: it refunds the charge once and releases the reservation once (balance 1000, one refund row, spent_credits 0). It cannot write the audit event or a receipt, and it reports the attempt as failed;
      • after the key row is usable again: one terminal audit event and one failed_refunded receipt are written, and the idempotency record is completed. In the logged run a replay with the same idempotency key wrote them before the third pass, and the passes after it changed nothing. By reading, a pass on a replica whose key can sign writes them too;
      • a replay with the same idempotency key answers -32005 signing_key_unavailable while the key is retired. With a usable key it answers -32006 upstream_returned_error with the failed_refunded receipt and does not dispatch again. In a second test, such a replay made before any pass also refunded the charge and released the reservation;
      • four passes and three replays gave one refund row and one upstream dispatch.
    • By the code, the sweep takes a terminal attempt after it has been idle for 300 s, on the 5-minute cleanup cycle. Until then the charge and the reservation stay held, unless the caller replays with the same idempotency key on a replica whose key can sign. No operator route is involved, because no work item exists.
    • Compared with main 38da347 and the fix(refunds): record a pending refund even when its receipt cannot be signed #330 head e0f675c, tested with the same test body:
    • Preconditions, all needed: an upstream (remote MCP) call that passes the pre-charge check and is charged; the upstream returns an error (tested) or, by reading, fails before dispatch; the live refund fails; and within that one request the configured key row becomes retired or disabled before the audit write. By reading, no HTTP route retires a key: retire_key_metadata and rotate_active_key_metadata are service calls. The rollout order in gateway/docs/key-management.md (retire the old row only after no replica runs the old id) is meant to prevent this.
    • Documented at fix(trust): a retired signing key refuses to sign instead of reactivating #331: gateway/docs/key-management.md lines 294 to 298 say "If the key was lost before that audit event, nothing is recorded by the call; the dispatch attempt row remains and the dispatch reconciler rebuilds the evidence from a replica whose key can sign." Those lines are new with fix(trust): a retired signing key refuses to sign instead of reactivating #331, and the fix(trust): a retired signing key refuses to sign instead of reactivating #331 description says the same. The case was noted earlier: two comments on fix(refunds): record a pending refund even when its receipt cannot be signed #330 on 2026-11-19 list it as known and left to the dispatch reconciler, and a review of fix(refunds): record a pending refund even when its receipt cannot be signed #330 on 2026-11-26 (review 6074763673, point 6) describes it for a disabled key.
    • Not exact in the docs: gateway/docs/failure-semantics.md lines 371 to 373 say that when the receipt cannot be signed "the work item is still recorded, without a receipt". That sentence came with fix(refunds): record a pending refund even when its receipt cannot be signed #330. On the upstream path it holds only when the terminal audit event was already written. Both replacement texts in item 4 above have the same gap: the line 55 text ("and without a receipt when it cannot") and the lines 361 to 363 text ("When it cannot, the work item is still recorded, without a receipt, as described below.").
    • Not tested: the variant where the refund lands and only mark_debit_refunded fails, with the key retired before the audit write. At this head only retired was run; disabled was run on main and on the fix(refunds): record a pending refund even when its receipt cannot be signed #330 head. The usable key was made by setting the same row back to active; a redeploy with a new key id was not run. The test called the cleanup passes directly and did not wait for the idle window or the cleanup loop. Nothing here was run on PostgreSQL.
    • Where this differs from the bot's text: the caller gets a generic -32603 internal_error, not the signing error text. The charge does not stay charged, because the first dispatch reconcile pass refunds it. And key-management.md describes the case, so it is not a departure from the documented behavior.

    If it is revisited:

    • Docs: add the condition to failure-semantics.md lines 371 to 373 and to both item 4 replacement texts. For example: "On the upstream path this holds when the terminal audit event was already written. Otherwise nothing is recorded by the call. The dispatch reconciler refunds the charge, and writes the audit event and the receipt once a replica whose key can sign runs it."
    • Test: one upstream test that makes the key unusable before the audit write, for retired and for disabled. The existing helper _upstream_refund_failure_with_key_lost disables the key right after the audit.
    • Code, a direction, not tested: wrap the upstream audit call the way the local-tool path does, so that the finalizer still runs. Compare the two outcomes first. Today the dispatch reconciler refunds on its own. With that change the call would store an unsigned item, which waits for a signer and then for an operator retry. On that route, part 1 of this issue can store a wrong record for a charge already refunded, part 2 can leave the charge unrefunded while the permit's key is disabled, and item 8 can delay the refund.
    • The live call answers a generic -32603 internal_error. Whether it should get a typed answer is not tracked elsewhere.

    Refs #331, #330.


    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