Repository navigation
Backlog
Labels
bugSomething isn't working
Description
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).
- 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.
- A product question: while the key that signed a permit is
disabled, the operator retry of that call's pending refund refuses. - 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_pendingstores 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.py368 to 419), or through the sweep, which runs every 300 s and takes terminal attempts idle for 300 s (main.py252 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
activeagain, the signer refuses the item on each pass and logsrefund_reconciliation_unsigned_already_refundedat error level (663 to 679); - the dispatch reconciler skips it (
mcp_dispatch_attempts.py2158 to 2169); - the operator refund list does not show it (808 to 868);
- a replay returns
refund_reconciliation.statuspendingwithreceipt_idnull.
- Expected: the record matches the ledger. On main the attempt gets a
failed_refundedreceipt once the key row isactiveagain. - Preconditions, all needed:
- the live refund or its checkpoint write fails;
- the key row becomes
disabledafter the audit write and beforecreate_pendingsigns. No product code writesdisabled, 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_refundedreceipt (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. Commit0c3790ae8fd1c7724d983e31d4bc634e86dc4a32does 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
disabledduring a call, and a second key signs the unsigned item. The operator retry answers 409refund_reconciliation_permit_invalid. The same-key replay answerspermit_signature_invalid. In the local-tool test, after the old key row is set back toactive, 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_disabledguards the status writes (signing_keys.py:271 to 275). Exceptions, tested on 2026-12-01 at707ba29and at main37618e0, 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 writesactivewhen it readretired, so adisabledcommitted 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_metadataandrotate_active_key_metadatahave 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 todisabledinside the window of one call. Theensure_active_keycase also needs the row to beretiredfirst, 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.pyon PostgreSQL. Thepythonjob 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
0c3790ae8fd1c7724d983e31d4bc634e86dc4a32has no behavior test.test_a_denial_that_repeats_the_marker_name_is_not_an_unsigned_itemchecks statement text (699 to 717), and each checked substring ends in" OR ". A scratch run that moved theresponse_json IS NULLcondition 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 whendebit_refunded_atandbudget_released_atare 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
Metadata
Metadata
Assignees
Labels
bugSomething isn't working
Activity
PetrefiedThunder commentedon Nov 30, 2026
Additions at the maintainer's request on 2026-11-30. CodeRabbit re-reviewed #330 at head
707ba293ade3b2de06ff1ac7e5646a4d0411b25cand 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 at707ba29. Tests ran on SQLite.4. Doc sentences that the unsigned path makes inexact (docs only)
gateway/docs/failure-semantics.mdline 55 says forfailed_unrefunded: "a durable operator work item is created atomically with the receipt". Lines 361 to 362 say the system "signsfailed_unrefundedatomically 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.failed_unrefundedatomically 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.disabledrefuses, "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 isdisabled."5. A docstring and a comment that overstate what the sweep leaves alone (text only)
gateway/app/services/refund_reconciliation.py, docstring of_refund_landed_and_budget_released(lines 460 to 475): "Nothing else releases that reservation (the dispatch sweep skips an attempt whose refund was never checkpointed while its debit stands)". That holds whenmark_debit_refundedrolled back. When it committed and the request then saw an exception, the sweep does release the reservation once the attempt has been idle for 300 seconds (tested, with the attempt backdated). The comment at lines 664 to 670 has the same gap: it says the dispatch reconciler leaves these items alone, and the sweep's budget release does not.test_unsigned_item_whose_refund_landed_unacknowledged_is_signed_and_released_once(gateway/tests/test_mcp_upstream_governed.pyline 3587) covers the lost acknowledgement only in the form where the checkpoint does not commit. Its helper replacesmark_debit_refundedwith a function that only raises (lines 3429 to 3438). By a name search, no test at this head makesmark_debit_refundedcommit and then lets the request see an exception.6. The signer does not compare the stored request hash with the record (minor)
sign_unsigned_pendingpassesinputs.request_hashfrom the stored marker tocreate_pending(line 700) and on tocreate_receipt, which only checks that it is 64 hex characters (gateway/app/services/receipts.pylines 557 to 564). With only that field changed by a direct database write, the signer signed a receipt that carries the changed hash, andverify_modelreturned True for it.idempotency_records, or data corruption. No product route undergateway/appwas found that writes inside a stored marker. The same actor can also change the record's ownrequest_hashcolumn, which defeats a comparison, and every other marker field that the signer signs.ledger_entry_id, and the operator retry compares the charge amount with the item's credits.inputs.request_hashwith the record'srequest_hashand 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.action_identitypath (gateway/app/routers/mcp.pylines 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
PetrefiedThunder commentedon Dec 1, 2026
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
707ba293ade3b2de06ff1ac7e5646a4d0411b25cunless stated.7. A committed
disabledcan be overwritten in a narrow race (low, tested)This replaces "by code reading, not run" in part 2 of the issue body.
gateway/app/services/signing_keys.py, the same file on main37618e0and at707ba29.ensure_active_key(line 277) reads the key row without a lock (lines 281 to 286), checks fordisabledon that read (line 292), and writesactivewhen the row it read wasretired(lines 295 to 297). The UPDATE selects by key id only.707ba29: with the rowretired, adisabledthat another session commits after the read is overwritten withactive. The key is then published again and signs again, and a signature made before the disable verifies again. The compromise steps ingateway/docs/key-management.md(lines 158 to 163) say that must not happen.activewithretired_atset, the write does not touchstatus, and the next signature is refused. Whendisabledis committed before the read, the call refuses withsigning_key_disabled.6af04421c0900c7808b3d84328ae8f12dfc6b7cd:ensure_active_keynever rewrites an existing row (lines 340 to 343 there). Tested: the call refuses withsigning_key_retiredand the row staysdisabled. 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.retire_key_metadata(lines 376 to 390): a concurrentdisabledbecomesretired, so the key is published again and its old signatures verify again. Tested.rotate_active_key_metadata(lines 392 to 439): a concurrentdisabledon the target row becomesactive. Tested. By reading, a concurrentdisabledon the old row would becomeretired(lines 417 to 420).ensure_active_key, the row must already beretired. In product code only the two methods above writeretired, so that takes a manual call to one of them or a direct database edit. An operator must then setdisabledby 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.disabledin a transaction that is still open when the write runs. Only adisabledthat was already committed was run.with_for_update=Trueandpopulate_existing=Truebefore the check, asvalidate_prepared_signing_keyalready does (lines 445 to 464). Or make the UPDATE conditional onstatus != '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)
gateway/app/services/permits.py.reconcile_budgets(line 2029) takes permits that are not active or are pastexpires_atand have been idle for 900 seconds, and sets theirspent_creditsto what_consumed_credits(lines 1834 to 2002) counts. That function counts receipts. A pending item with afailed_unrefundedreceipt is counted. An unsigned item has no receipt and is not counted.707ba29for a revoked permit and for an expired permit, each with no other spend: the pass setspent_creditsfrom 2 to 0 while the charge was still unrefunded. After the signer signed the item, the operator retry answered 409refund_reconciliation_budget_conflict. A later pass counted the new receipt and setspent_creditsback to 2. A second operator retry then refunded once (balance back to 1000, one refund row).spent_creditsfrom 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.reconcile_budgets(gateway/app/main.pyline 377) runs beforesign_unsigned_pending(line 402). So a key that is usable again before the pass does not prevent the reset (tested).reconcile_budgetspass and another operator retry. The reset writesupdated_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_revokedorpermit_expired).reconcile_budgetshad nothing to correct (tested for a revoked permit only)._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.gateway/app/services/permits.pyis the same file on main, at707ba29and 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.pyis the same file at707ba29and 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
PetrefiedThunder commentedon Dec 5, 2026
One more verified item, added on 2026-12-05 at the maintainer's request. CodeRabbit reviewed #331 at head
3ccfb093337b54dee76e17988d3dbbded00782edand 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 at3ccfb09. 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.
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_failureruns 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).retiredafter the pre-charge check and before that audit write. The audit write raisessigning_key_retired(gateway/app/services/audit_chain.pyline 281,gateway/app/services/signing_keys.pyline 319)._audit_mcp_invocationcatches onlyAuditChainContendedError, so the finalizer never runs. Right after the call:-32603 internal_error, with no receipt and norefund_reconciliationdata;spent_credits2;returned_errorwithdebit_refunded_atandbudget_released_atunset, and the idempotency record is still in progress.retired: it refunds the charge once and releases the reservation once (balance 1000, one refund row,spent_credits0). It cannot write the audit event or a receipt, and it reports the attempt as failed;failed_refundedreceipt 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;-32005 signing_key_unavailablewhile the key is retired. With a usable key it answers-32006 upstream_returned_errorwith thefailed_refundedreceipt and does not dispatch again. In a second test, such a replay made before any pass also refunded the charge and released the reservation;38da347and the fix(refunds): record a pending refund even when its receipt cannot be signed #330 heade0f675c, tested with the same test body:disabledat the same moment gives the same call result and the same recovery on both commits. One difference: a replay while the key is unusable answers-32603 internal_errorthere, not-32005. So the code order and its effect are not new with fix(trust): a retired signing key refuses to sign instead of reactivating #331;retiredkey row is set back toactiveby the signer on both commits. The audit event is signed, the caller gets afailed_unrefundedreceipt with a pending refund, and the charge waits for an operator retry. With fix(trust): a retired signing key refuses to sign instead of reactivating #331 a retired key refuses, so fix(trust): a retired signing key refuses to sign instead of reactivating #331 addsretiredas one more key state that reaches this case.retiredordisabledbefore the audit write. By reading, no HTTP route retires a key:retire_key_metadataandrotate_active_key_metadataare service calls. The rollout order ingateway/docs/key-management.md(retire the old row only after no replica runs the old id) is meant to prevent this.gateway/docs/key-management.mdlines 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.gateway/docs/failure-semantics.mdlines 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.").mark_debit_refundedfails, with the key retired before the audit write. At this head onlyretiredwas run;disabledwas 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 toactive; 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.-32603 internal_error, not the signing error text. The charge does not stay charged, because the first dispatch reconcile pass refunds it. Andkey-management.mddescribes the case, so it is not a departure from the documented behavior.If it is revisited:
failure-semantics.mdlines 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."retiredand fordisabled. The existing helper_upstream_refund_failure_with_key_lostdisables the key right after the audit.disabled, and item 8 can delay the refund.-32603 internal_error. Whether it should get a typed answer is not tracked elsewhere.Refs #331, #330.
Generated by Claude Code