Repository navigation
feat(gateway): operator resolution path for delivery_uncertain receipts (SEL-351 follow-up) - #393
PetrefiedThunder wants to merge 2 commits into
Conversation
Signed-off-by: CS <cs@CSs-MacBook-Pro.local>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 51 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b7af94fa2a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if attempt: | ||
|
|
||
| async def finish_compensation() -> None: |
There was a problem hiding this comment.
Release refunded reservations for receipts without dispatch attempts
For an AWI HTTP delivery_uncertain receipt, a manual confirmed_not_delivered resolution with refund_credits=true refunds the wallet and returns success, but this guard skips permit compensation entirely. awi_http_governance.py reserves permit budget before charging and creates receipts without an MCP dispatch attempt, so these receipts legitimately reach this branch with attempt=None. The reservation therefore remains in spent_credits, potentially continuing to deny calls with permit_budget_exceeded after the refund; replaying the resolution cannot repair it. Add a durable, once-only reservation release for this receipt path, or reject unsupported refunds before appending their signed intent.
AGENTS.md reference: gateway/app/services/AGENTS.md:L7-L16
Useful? React with 👍 / 👎.
| await get_permit_service().release_dispatch_budget_once( | ||
| attempt.attempt_id, | ||
| caller=CallerIdentity.for_wallet(receipt.wallet_id), | ||
| ) |
There was a problem hiding this comment.
Account for operator refunds in budget reconciliation
After this release successfully compensates an uncertain dispatch, PermitService._consumed_credits() still unconditionally counts the original delivery_uncertain receipt as consumed and never checks its resolution or refund. Once the permit expires or is revoked and becomes idle, the existing reconcile_budgets() background task writes that inflated receipt total back into spent_credits, undoing the completed budget release while budget_released_at prevents another release. Update the reconciliation source of truth to exclude operator-resolved non-deliveries whose refund is durably complete, without excluding records that only contain signed refund intent.
AGENTS.md reference: gateway/app/services/AGENTS.md:L7-L16
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit b7af94f. Configure here.
Written by the Codex CLI engine. Reject refunds for receipts without a dispatch attempt before signing intent; exclude durably refunded operator non-deliveries from budget reconciliation; normalize lookup origins at register and lookup; return audited 409 resolution_inconclusive for dispatch-context conflicts. Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com>

Summary
A signed
delivery_uncertainreceipt previously had no operator resolution caller. Add a bootstrap-admin-onlyPOST /v1/admin/receipts/{receipt_id}/resolutionand a thingateway/scripts/amw_resolutions.pyclient. The original receipt, signature, debit and agent replay remain unchanged; readers discover the separate resolution through the existing receipt endpoint and wallet chain.Resolution v0.2 signs the SHA-256 digest of canonical evidence capped at 16 KiB. Exact outcome/evidence replays return the same row; conflicting evidence or outcomes return 409. Refund intent is part of the signed evidence. Explicit confirmed non-delivery refunds use the existing money service's separate
refund-{ledger_entry_id}entry, then its durable dispatch compensation checkpoints and once-only permit budget release. Retries converge after interruption before the refund or before budget release.An explicitly registered
RefundFixtureStatusLookupreads only the fixture/statuscontract with bearer authentication, a five-second timeout, bounded response bytes, disabled redirects, and no retained raw response. Nothing is registered by default. Executed answers support success; unfenced negative answers, pending/unknown answers, errors and malformed responses remain inconclusive and write no resolution or refund.Related issues
SEL-351 follow-up, replacing the unused append_resolution TODO with an operator-only path.
Area and license
Spec changes
spec/or normative protocol material are changed.Migration and compatibility
058_resolution_evidencefollows057_receipt_permit_seq_unique, adding nullable canonical evidence and evidence_hash columns. Existing v0.1 rows retain their original bytes and remain verifiable offline. New operator records use v0.2; the SDK verifies its evidence digest as well as the signature and original-receipt link. The existing v0.1 golden signing snapshot stays unchanged, and CHANGELOG records the v0.2 version bump.The rollout document covers image/head compatibility and rollback. Downgrade refuses while signed evidence exists, rather than discarding it. No staging/production migration or deployment was performed.
Security
Reuse
AuthContext.require_bootstrap_admin()without adding an authentication scheme. Agent/wallet credentials, demo credentials and permits cannot authorize the route. The operator route is absent from MCP tools and agent discovery. Every handled resolution attempt records a control-plane audit event with an operator credential fingerprint or key id, including conflicts and inconclusive lookups. The adapter never logs its token or persists provider response bodies. Operator evidence is visible to authorized receipt readers, so the runbook requires review/redaction of free text and provider-specific fields in addition to automatic credential-field redaction.A terminal dispatch row does not fence a paused sender. Negative lookup answers for a historical dispatch claim therefore remain inconclusive. Manual non-delivery evidence requires the operator to establish that senders have stopped. Successful resolutions never refund, and refund intent cannot be changed after append.
Validation
Local tests used fakes/MockTransport and disposable PostgreSQL 16 at 127.0.0.1:55439. All databases created for this change were dropped afterward. Cached Python 3.14.9, pytest 9.2.0, Ruff 0.17.3 and mypy 2.4.1 were used without package-network access.
uv run --no-project --active python -m pytest -n 6 --timeout 300 -qtests/test_mcp_postgres_multiprocess.pyThe plain gateway run skips opt-in tests; the requested PostgreSQL proofs above were run separately with the CI opt-in flags,
ENVIRONMENT=test, and disposable database acknowledgement. Multiprocess tests additionally usedSTATE_BACKEND=postgresandMCP_STRESS_DB_ISOLATED=1.Ruff check/format passed for every Python project returned by CI project discovery. Pinned mypy passed for all 215 application source files. OpenAPI export matches the app. SDK wheel and source distribution built successfully. Staged secret scans, private-key detection, whitespace, merge-conflict, Ruff and formatting hooks passed. The isolated mypy pre-commit hook was skipped because its resolver could not obtain mypy from the offline package cache; the direct pinned application check passed. An all-files pre-commit run also reported existing issues in untouched files; those were left outside this PR.
New coverage includes actual agent-key refusal, evidence size bounds and tampering, stable v0.1 verification, conflicting re-resolution, fixture lookup failures/timeouts, separate exactly-once refunds, interruption before refund and after refund/before budget release, unchanged original receipt bytes, a fresh-app/fresh-singleton lost-response replay with one dispatch and one debit, offline resolution verification, and concurrent PostgreSQL operator requests.
Open questions
not_executedfor a previously claimed send requires a genuine upstream fencing contract. Until one exists, that answer remains inconclusive and the operator must obtain authoritative evidence and stop potential senders before making a manual assertion.Contributor checklist
Note
High Risk
Touches operator auth, signed ledger refunds, and permit budget reconciliation for ambiguous delivery receipts; mistakes could incorrectly release charges or double-refund without careful idempotency.
Overview
Adds a bootstrap-admin-only path to adjudicate signed
delivery_uncertainreceipts without mutating the original receipt, replay, or redispatching tools.POST /v1/admin/receipts/{receipt_id}/resolutionaccepts bounded operator evidence and appends a signed resolution-v0.2 record (migration 058 addsevidence/evidence_hash; v0.1 remains verifiable). Conflicting outcome or evidence returns 409; identical requests replay the same row.refund_creditsonconfirmed_not_deliveredcreates a separate ledger refund, with retries finishing interrupted compensation and permit budget release only after a matching refund entry exists.An optional startup-registered fixture status lookup can corroborate outcomes under strict timeouts and refuses unfenced negative answers when a dispatch claim may still send. Documentation, OpenAPI, CLI
amw_resolutions.py, and the Python SDK verifier are updated for v0.2 evidence-hash checks.Reviewed by Cursor Bugbot for commit 2cfb9ea. Bugbot is set up for automated code reviews on this repo. Configure here.
Follow-up review fixes
refund_creditswith409 resolution_refund_unsupportedbefore signed refund intent is appended. This chooses the supported-kind rejection option rather than adding a new reservation release marker.409 resolution_inconclusivewithout appending a resolution or refunding.Regression tests cover all four findings, including expired permit reconciliation after completed and interrupted refunds.
Validation of the follow-up worktree changes: focused suites 360 passed, 23 skipped; full gateway suite with
-n 6 --timeout 3006631 passed, 107 skipped; disposable PostgreSQL operator race 1 passed. Ruff check and format pass across all discovered Python projects; pinned mypy 2.4.1 passes all 215 gateway source files.These follow-up changes are commit
2cfb9ea0on this branch (review findings: no-attempt refund rejected before signed intent; budget reconciliation excludes durably refunded operator non-deliveries; lookup origin normalization; audited 409 for dispatch-context conflicts).