AP2 icon indicating copy to clipboard operation
AP2 copied to clipboard

[Bug]: x402 sample persists payment token as used before settlement is confirmed

Open giorgioroth opened this issue 4 months ago • 6 comments

What happened?

In the x402 human-not-present sample at commit e1ea56d, merchant_agent_mcp.complete_checkout records the payment token as consumed and allocates an order before it calls the PSP, and does not restore that state when the call fails.

Observed ordering in code/samples/python/src/roles/merchant_agent_mcp/server.py:

Line Action
923 token_data['used'] = True
924–930 order_id allocated; amount_charged and currency recorded
946 _save_token_store(token_store) — persisted
984 POST to the x402 PSP at /settle-payment
1000 return {'error': 'PSP_call_failed', …} on exception

Between line 946 and line 1000 there is no reassignment of used, no deletion from the store, and no compensating write. The card flow beginning at line 1013 has the same ordering and raises ValueError on processor error, also without restoration.

Steps to reproduce:

  1. Run the x402 human-not-present scenario with BROADCAST_ON_CHAIN unset (default FALSE). Export a shared TEMP_DB_DIR so the roles share one state directory.
  2. Complete one purchase with all services reachable, to confirm the baseline. This succeeded, producing a receipt and an order id.
  3. Delete .temp-db/ap2_token_store.json.
  4. Stop the x402 PSP process listening on localhost:8084. Leave the other roles running.
  5. Repeat the flow: product query, $200 budget authorization, mandate approval, then the price-drop trigger setting the item to $199 with stock 10.

What I expected: either the token remains available for a further attempt, or the failure path records that settlement was not confirmed.

What happened: complete_checkout returned PSP_call_failed. No receipt and no transaction hash were produced. The token store nevertheless contained "used": true with an allocated order_id. Since complete_checkout begins by refusing a token already marked used, a further attempt presenting the same token would be refused as token_already_used.

Scope of the report. This concerns the sample implementation at one commit, in one configuration, with the settlement endpoint deliberately unavailable. It does not establish loss of funds: no transfer was attempted. It does not establish on-chain consumption of the EIP-3009 authorization: broadcast was disabled and no transaction was submitted. I did not test whether a retry in practice would present the same token or obtain a new payment credential.

Question: is this ordering intentional for the samples? If token consumption and order allocation are meant to precede settlement confirmation, is reconciliation expected to be the integrator's responsibility, or would a restoration step on the failure branch be in scope for the sample?

Related existing issues. I looked for prior coverage before filing. #44 requests that examples and guidance for handling failure states and enforcing mandate constraints be added; this report is about what the current sample does rather than what should be documented, so I filed it separately, but the two may belong together. #224 concerns proof-of-delivery before payment release, which is the same ordering question from the settlement side. If either already covers this, closing in favour of them is fine by me.

Full conditions, the baseline run and the limits of the observation: https://github.com/giorgioroth/AP2/blob/main/REPRO_X402_SETTLEMENT_FAILURE.md

Relevant log output

Merchant MCP · complete_checkout — Calling complete checkout via Merchant MCP

Error
PSP_call_failed
All connection attempts failed

--- token store after the failed run, truncated ---

{
  "x402_tok_4703483ae1954bb5a4e97a4fa62deed7": {
    "used": true,
    "order_id": "cf8e19d1-1631-4abd-9035-eee632f2a3f3",
    "expires_at": 1785351577,
    "currency": "USD",
    "checkout_jwt_hash": "14UvHy8FJkNG98TQ…",
    "open_checkout_hash": "QjZheS5cty8Q8mfz…"
  }
}

Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

giorgioroth avatar Jul 30 '26 03:07 giorgioroth

This is the right failure boundary to make explicit in the sample.

For human-not-present checkout, I would treat used=true as a post-settlement or post-terminal-reservation state, not something persisted before the PSP call unless the store also records a separate settlement_pending / settlement_failed state with an idempotency key. Otherwise an infrastructure failure becomes indistinguishable from successful token consumption, and retry/reconciliation code has to infer intent from a partially-written order.

The useful contract for integrators is probably:

  • mandate/payment credential accepted
  • settlement attempt started with an idempotency key
  • settlement confirmed, then token marked consumed
  • settlement failed, then retryable state or explicit reconciliation record

That keeps agent authorization, order allocation, and payment finality separate. It also gives MCP/AP2 clients a cleaner receipt surface: the agent can say “authorized but not settled” instead of only surfacing token_already_used on the next attempt.

I would support documenting this in the sample even if the production answer is “integrators own reconciliation,” because this is exactly where agent commerce systems need crisp state semantics.

0xbrainkid avatar Jul 30 '26 06:07 0xbrainkid

Thanks! I think we're describing the same boundary from two directions, and I want to be careful about which parts of your description my report actually supports.

What the report establishes, at commit e1ea56d, in the one configuration I ran:

  • used=true and the order allocation are written and persisted before the PSP call (923–946 precede 984), and there is no reassignment, deletion or compensating write on the exception path;
  • after the failed run the store contained "used": true with an allocated order_id, and no receipt or transaction hash was produced.

One further point is read from the code rather than observed: since complete_checkout refuses a token already marked used, a second presentation of that same token would be refused as token_already_used. I did not run that second attempt, and I did not test whether a retry would in practice present the same token or obtain a new credential.

Your proposal goes further than the observation. Separating settlement attempt, settlement outcome and token consumption, keyed by an idempotency key, would remove the specific ambiguity I saw — one boolean carrying two meanings. I can't claim it is the required contract, or that equivalent mechanisms don't already exist elsewhere in the sample or aren't deliberately delegated to integrators. I haven't checked that.

I'd also state the ambiguity more narrowly than "infrastructure failure becomes indistinguishable from successful token consumption". What I can support is that used=true alone does not distinguish settlement completed, settlement pending reconciliation, and a failure path that left partially committed local state. Whether some other record distinguishes them is something I did not establish.

The part that needs no further verification is your last paragraph: if the intended contract is that integrators own reconciliation, saying so explicitly in the sample would already make the failure boundary clear. That, plus the maintainers' answer on whether the ordering is intentional, seem the useful next steps.

giorgioroth avatar Jul 30 '26 17:07 giorgioroth

Following up, since this is a design question rather than a defect I can patch on my own judgment.

I'm willing to prepare an implementation and regression tests, but I don't want to encode a settlement contract before the intended ownership is clear. Three directions look materially different:

  1. The sample owns the intermediate state: it records a settlement-pending or settlement-failed state with an idempotency key, and marks the token consumed only after settlement is confirmed.
  2. Reconciliation is deliberately delegated to integrators, in which case the sample would state that contract explicitly rather than leaving used=true to stand alone as a settlement outcome.
  3. The current ordering is intended as-is for the samples, and nothing changes.

Any of the three is a reasonable answer, and the third would close this issue as working as intended, which is a fine outcome. What the report established is narrower than any of them: after a settlement call that failed at connection time, used=true and an allocated order_id remained persisted, with no receipt and no transaction hash. Which contract that state belongs to is not something I can read off the sample.

If maintainers confirm a direction, I can prepare the corresponding change. I'd rather not guess: a test written now would either freeze the current behaviour as correct or fail against it, and which of those is right depends on the answer.

giorgioroth avatar Aug 02 '26 07:08 giorgioroth

One piece of field evidence for the "does this matter for a sample" question, offered as data rather than as a position on which of the three directions is right — that's maintainers' to answer, and @giorgioroth has already offered the implementation.

We ran a first-party paid audit of x402 sellers: one real settled USDC payment to each of 502 distinct Base payout addresses, 2026-08-07. Twelve of them settled the payment on-chain and then refused the request — HTTP 400×5, 405×5, 500×2. In each of those twelve, settlement completed before the request was validated.

Being precise about what that does and does not support, because it is adjacent to #308 rather than the same defect:

  • It is not the same ordering. #308 is local state (token consumed, order allocated) committed before the settlement call is confirmed. What we observed is the money moving before the request is validated. They are mirror images of the same missing property — no atomic coupling between "payment finalised" and "obligation established" — but they are not the same bug, and our data says nothing directly about token-store handling.
  • It does not establish intent. A correctly-parameterised request to most of those twelve would likely have been served; we did not retry to find out.
  • It does not establish that any of those services derive from AP2 samples. We did not attempt to attribute implementations, and we have no basis to.

What it does support is narrower: charge-before-confirm ordering is already present in deployed x402 services at a measurable rate, and it is silent from the buyer side — the failure surfaces as a normal HTTP error while the payment has settled, so an agent gets no signal distinguishing "wrong parameter" from "paid and refused."

That is the reason I would argue for at least direction 2 (state the contract explicitly) rather than direction 3. Integrators copy reference implementations structurally. Where the ambient production pattern already commits before confirming, a sample that does the same reads as endorsement, and the cost of saying "integrators own reconciliation" in one sentence is close to zero.

Method and receipts for the audit are public (each of the twelve has a settlement transaction): https://merona.io/real-seller-index has the index methodology; happy to share the per-seller delivery breakdown if it is useful to anyone here.

jywy78kgrf-create avatar Aug 11 '26 19:08 jywy78kgrf-create

Thanks for the detailed reproduction. The failure mode you describe is exactly the kind of pre-settlement state transition Varyntiq is designed to make explicit: a decision is issued before signing, and a failed settlement must not be treated as a successful spend.

We have an independent adapter that can evaluate an operation before signing, return ALLOW, BLOCK, or REQUIRE_APPROVAL, bind the decision to an idempotency key and request fingerprint, and emit an auditable receipt. It never receives private keys, signs, settles, or claims that a payment succeeded.

A minimal non-production test could cover settlement failure, safe retry, and rejection of a replayed decision. Would reviewing this adapter against the sample's token-store and reconciliation path be useful?

Demo: https://github.com/mercadosclaro-eng/ai-payment-control-plane/tree/main/integrations/inflow-x402

mercadosclaro-eng avatar Sep 27 '26 00:09 mercadosclaro-eng

Thanks for the reference. The AP2 demo at 7177041 illustrates the delayed-consumption part of direction 1 in my August 2 comment. That option also included an explicit intermediate state and an idempotency key. I left the intended AP2 contract open.

The main gap I see is concurrency. The guard checks used and then awaits settlement before updating it. It does not record a pending attempt that prevents overlapping calls from reaching settle(). An unconfirmed outcome also leaves the token available, without distinguishing definite non-execution from an outcome that still needs reconciliation. If safety depends on idempotency inside settle(), that should be part of the documented contract.

An AI assistant reported two simulated provider effects in each of its concurrent-call and lost-acknowledgment checks. I did not run those checks myself. They concern the no-funds demo, not a deployed payment path.

There is a separate decision-binding point: the guard puts the operation fingerprint in the receipt but does not compare it with the incoming ALLOW. The replay test starts with an already-used token, so it does not test that binding.

Could you clarify which layer owns the pending state and the idempotency guarantee? A useful regression would count provider calls and committed mock effects separately, and check that a decision issued for a different operation is refused.

giorgioroth avatar Nov 11 '26 02:11 giorgioroth