Skip to content

fix: retry settlement on conflicting_nonce with exponential backoff - #106

Closed
anansutiawan wants to merge 1 commit into
aibtcdev:mainfrom
anansutiawan:fix/retry-conflicting-nonce
Closed

anansutiawan wants to merge 1 commit into
aibtcdev:mainfrom
anansutiawan:fix/retry-conflicting-nonce

Conversation

@anansutiawan

Copy link
Copy Markdown

Summary

Fixes #84 — concurrent x402 payment settlements can hit nonce contention at the relay, causing both to fail with conflicting_nonce. This is a transient relay-side race condition (not a client error), so the middleware should retry transparently before propagating the failure to the caller.

Changes

  • Wrapped verifier.settle() in a while retry loop in src/middleware/x402.ts
  • On conflicting_nonce in settleResult.errorReason, retry up to 3 times with exponential backoff: 5s → 10s → 20s
  • All other errors (non-conflicting_nonce failures, thrown exceptions) fall through immediately — no change to existing behavior
  • Added a log.warn on each retry attempt for observability

Why this approach

The issue logs show the relay itself returns conflicting_nonce when two settlements land within the same second. The relay nonce contention clears quickly, so a short delay (5s first retry) recovers most concurrent cases without the client needing to rebuild the payment.

Testing

No new tests are added (E2E tests require a live relay). The fix is isolated to the retry wrapper around the existing settle() call. All pre-existing TypeScript errors in src/endpoints/hashing/ are unrelated and pre-date this change.

🤖 Generated with Claude Code

…al backoff

When two concurrent x402 payments hit the relay within the same second, the
relay may reject one with conflicting_nonce. This is a transient relay-side
race condition, not a client error. Retry up to 3 times with 5s/10s/20s
backoff before propagating the error to the caller.

Closes aibtcdev#84

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

@arc0btc arc0btc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adds transparent retry logic for conflicting_nonce settlements — good call. We process x402 payments through this middleware and have hit nonce contention when concurrent settlements race at the relay within the same second.

What works well:

  • Retry is scoped only to conflicting_nonce — all other failures (exceptions, non-retryable result codes) fall through immediately with no behavior change
  • The settleAttempt < CONFLICTING_NONCE_MAX_RETRIES guard before incrementing means the array index is always in-bounds (0, 1, 2)
  • log.warn on each retry attempt is the right call — this gives operators visibility into contention frequency without polluting the error log
  • Indentation and nesting of the refactored catch block is clean

[suggestion] Total backoff could exceed client HTTP timeouts (src/middleware/x402.ts)

Worst case: 5s + 10s + 20s = 35s before conflicting_nonce is propagated to the caller. Clients (or upstream proxies) with a 30s timeout will see a gateway timeout before the final retry completes. Consider documenting the maximum latency implication, or surfacing it as a configurable option:

// Total worst-case latency: 35s (5+10+20). Ensure any upstream HTTP timeout
// (proxy, CDN, client) exceeds this value, or reduce CONFLICTING_NONCE_MAX_RETRIES.
const CONFLICTING_NONCE_MAX_RETRIES = 3;
const CONFLICTING_NONCE_BACKOFF_MS = [5_000, 10_000, 20_000];

[nit] Unreachable fallback in backoff lookup (src/middleware/x402.ts)

The ?? 20_000 default is dead code — settleAttempt is always 0, 1, or 2 when this line executes (the condition settleAttempt < 3 guarantees it). No functional problem, just a slightly misleading guard:

          const delayMs = CONFLICTING_NONCE_BACKOFF_MS[settleAttempt];

Code quality notes:

  • The while (true) + break pattern is readable given the existing nesting depth. A helper like settleWithRetry() would clean it up further but isn't necessary here.
  • The // end while (retry loop) comment at the closing brace is mildly redundant — the variable names and structure make the intent clear.

Operational context:
We run a relay that processes concurrent settlements (x402-relay v1.29.0). We added proactive nonce reconciliation on the relay side to prevent the race that causes conflicting_nonce in the first place — this middleware-side retry is a good complementary defense layer for cases that slip through. The 5s first retry matches what we observe: nonce contention at the relay clears within 1–3 seconds, so 5s is a safe floor.

@tfireubs-ui tfireubs-ui left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second APPROVE.

Clean targeted fix for issue #84. The retry loop is correctly scoped:

  • gates on errorReason === 'conflicting_nonce' + settleAttempt < MAX — non-retryable failures still fall through to the existing classification path unchanged
  • backoff array [5_000, 10_000, 20_000] with ?? 20_000 guard against off-by-one — safe
  • log.warn on each attempt gives operators visibility without noisy retries at info
  • exception handler in the catch block is untouched — preserves existing retry-decision logging for non-settle() errors

Worst-case total wait is ~35s which is long for a request lifecycle but acceptable for a transient relay contention window. Since the relay assigns sponsor nonces, a fresh verifier.settle() call on retry should naturally pick up an uncontended slot.

Ready to merge.

@whoabuddy

Copy link
Copy Markdown
Contributor

Hi! Wanted to flag that #107 supersedes the conflicting_nonce retry logic here. The relay now tracks nonce state natively and exposes it via terminalReason in the boring-tx state machine — TERMINAL_REASON_CATEGORY_HANDLING from @aibtc/tx-schemas maps directly to the right client action (rebuild-and-resign vs bounded-retry-same-payment).

Once you've reviewed the new PR and are comfortable, would you mind closing this one? Happy to answer questions about how the new approach works. Thanks for the detailed nonce analysis — it fed directly into the error-hints design.

whoabuddy added a commit that referenced this pull request Apr 23, 2026
Record PR title, body, issue comment text, and all URLs for the
boring-tx state machine PR (#107) and related issue comments on
#94, #106, and #87.

Co-Authored-By: Claude <[email protected]>
whoabuddy added a commit that referenced this pull request Apr 29, 2026
* docs(planning): phase 1 research notes for boring-tx adoption

Map from x402-api compat-shim code paths to the native boring-tx events
emitted by x402-sponsor-relay v1.30.1. Covers shim inventory, behavior
comparison table, tx-schemas entry points, relay RPC response shapes,
PaymentPollingDO public API sketch, and risk list with 8 identified risks.

Co-Authored-By: Claude <[email protected]>

* chore(deps): bump @aibtc/tx-schemas for boring-tx state machine

Bump @aibtc/tx-schemas constraint from ^0.3.0 to ^1.0.0. The 0.x.y semver
locking meant the installed 1.0.0 package was outside the resolvable range;
pinning to ^1.0.0 correctly tracks the native boring-tx state machine exports
needed in Phases 3-5.

Also remove stale patches/x402-stacks+2.0.1.patch — the upstream package
now ships with the desired 120000ms HTTP client timeout natively, making the
patch-package postinstall step error on every npm install.

Baseline: npm run check (tsc --noEmit) exits 0, npm run deploy:dry-run builds
clean at 1027.76 KiB before any logic changes.

Co-Authored-By: Claude <[email protected]>

* refactor(payments): route payment types through @aibtc/tx-schemas

Create src/services/payment-contract.ts as a thin re-export helper over
@aibtc/tx-schemas subpaths, providing a single import point for all
payment-lifecycle types used across middleware, utilities, and Durable
Objects in this service.

Replace SettlementResponseV2 from x402-stacks with SettleResult (aliased
from HttpSettleResponse in tx-schemas) in middleware/x402.ts and types.ts.
The discriminated union type is structurally compatible; a cast is applied
at the verifier.settle() call site — Phase 5 removes the x402-stacks
dependency entirely when the RPC path takes over.

extractCanonicalPaymentDetails is preserved (Phase 5 removes it).

Co-Authored-By: Claude <[email protected]>

* feat(payments): add PaymentPollingDO for checkStatusUrl polling

Adds PaymentPollingDO (SQLite-backed Durable Object) that tracks in-flight
payments by polling checkStatusUrl with exponential backoff until terminal.

Key design decisions:
- _fetchStatus() is the single relay-contact seam: Phase 4 uses HTTP GET,
  issue #87 swaps to env.X402_RELAY.checkPayment(paymentId) — one-line change
- computeDerivedHints() extracted to src/utils/payment-hints.ts so it is
  testable with bun:test without requiring cloudflare:workers runtime
- DO instances are namespaced by paymentId (one per in-flight payment)
- Alarm backoff: 5s (polls 1-3), 15s (4-6), 60s (7+), 10-min timeout

Wiring:
- wrangler.jsonc: PAYMENT_POLLING_DO binding + v3 migration tag in all envs
- src/types.ts: Env interface updated with PAYMENT_POLLING_DO binding
- src/index.ts: exports class; mounts GET /payment-status/:paymentId (free)

Unit tests (36 passing):
- computeDerivedHints covers all terminal reason categories
- Stub-based track → poll → terminal happy-path flow
- derivedHints per category verified

Co-Authored-By: Claude <[email protected]>

* feat(payments): emit native payment.* events, drop compat shim

Middleware now mints a client-side paymentId ("pay_" + crypto.randomUUID())
before submitting to the relay, injects it as the payment-identifier
idempotency input, extracts checkStatusUrl from the relay response extensions
(with a fallback construction), and registers the payment with
PaymentPollingDO.track() as fire-and-forget.

Five native lifecycle events replace all compat-shim-era event names:
  payment.initiated  — paymentId minted, about to submit to relay
  payment.pending    — relay acknowledged but payment is still in-flight
  payment.confirmed  — relay settled successfully
  payment.failed     — relay rejected with a terminal failure reason
  payment.replaced   — payment replaced by another tx (nonce race)

Deleted entirely:
  - extractCanonicalPaymentDetails() and all internal shim helpers
  - inferLegacyStatus() and inferLegacyTerminalReason()
  - getRetryDecisionContext() (tests/_shared_utils.ts update deferred to Phase 7)
  - compat_shim_used log field from buildPaymentLogFields
  - compatShimUsed / source fields from CanonicalPaymentDetails and RetryDecisionContext
  - OpenAPI schema for details.canonical in 402 response body

Unit tests updated to cover the three surviving classifier predicates and
the revised instability derivation signature.

Co-Authored-By: Claude <[email protected]>

* feat(payments): add retryable/retryAfter/nextSteps error hints

All non-200 payment error responses now carry structured retry hints in
both the JSON body and the payment-response header (base64 JSON):

  { retryable, nextSteps, retryAfter? }

nextSteps tokens are stable identifiers tied to tx-schemas terminal
reason categories — not free-form prose — so clients can branch without
string-parsing:
  rebuild_and_resign  — sender nonce issue, build fresh tx
  retry_later         — transient relay/settlement error
  start_new_payment   — identity lost/replaced, restart x402 flow
  fix_and_resend      — invalid payload, fix before retrying
  wait_for_confirmation — confirmed, delivery should proceed

classifyPaymentError() now checks canonical status (failed/replaced/
not_found) from the relay response before falling back to string
heuristics, so boring-tx relay responses are classified accurately.

Settlement failure path: computeDerivedHints() maps canonical status +
terminalReason → hints with no DO round-trip.
Exception path: hintsFromClassifiedCode() derives hints from classified
error code when no canonical status is available.

Updated llms-full.txt error handling section and /topics/payment-flow
topic doc to document the new hint shape, token vocabulary, and client
retry pattern.

Co-Authored-By: Claude <[email protected]>

* test(payments): cover boring-tx lifecycle end-to-end

Finish the pending tests/_shared_utils.ts diff (NonceTracker, nonce resets
on retry, signPaymentWithNonce helper). Add getRetryDecisionContext and
RetryDecisionContext to payment-status.ts — these were already imported in
the committed shared utils but never implemented.

Add X-PAYMENT-ID response header in the middleware success path so lifecycle
tests can extract the relay paymentId from a 200 response without parsing
the settlement result's opaque extensions field.

Add tests/payment-polling-lifecycle.test.ts (runPaymentPollingLifecycle):
- Makes a real x402 payment to /hashing/sha256
- Reads X-PAYMENT-ID from the 200 response header
- Polls GET /payment-status/:paymentId (free DO route) until terminal
- Asserts the DO snapshot has expected shape (paymentId, checkStatusUrl,
  polledAt, pollCount, terminal status)

Register payment-polling in LIFECYCLE_RUNNERS in _run_all_tests.ts.

All 65 payment-*.unit.test.ts pass. npm test (quick mode, 14 stateless
endpoints) passes 14/14. npm run test:full requires X402_CLIENT_PK and
a local worker (X402_WORKER_URL=http://localhost:8787) since X-PAYMENT-ID
header is not yet in the deployed staging worker.

Co-Authored-By: Claude <[email protected]>

* refactor(payments): simplify post-boring-tx adoption

Remove three dead imports from x402.ts middleware (isInFlightPaymentState,
isRelayRetryableTerminalReason, isSenderRebuildTerminalReason) that were added
during Phase 5 but never used in the middleware body — the retry logic that
would have used them lives in tests/_shared_utils.ts instead.

Clean up two stale phase-reference comments in payment-contract.ts that referred
to "Phase 5" as a future event ("will widen this surface", "removes the
x402-stacks dependency") — those phases are now complete.

TERMINAL_STATUSES duplication between payment-hints.ts and PaymentPollingDO.ts
was reviewed and intentionally left — the isolation benefit outweighs the DRY
concern for a 4-element constant across a DO boundary.

Co-Authored-By: Claude <[email protected]>

* chore(planning): phase 9 verification log

All blocking checks pass: npm run check (0 errors), npm run deploy:dry-run
(clean, PAYMENT_POLLING_DO binding confirmed), npm test (14/14), bun unit
tests (114/114). Branch already on origin/main tip — no rebase needed.
Known non-blocker: test:full payment-polling-lifecycle is deployment-gated
(X-PAYMENT-ID header not yet on live staging).

Co-Authored-By: Claude <[email protected]>

* chore(planning): phase 10 PR handoff

Record PR title, body, issue comment text, and all URLs for the
boring-tx state machine PR (#107) and related issue comments on
#94, #106, and #87.

Co-Authored-By: Claude <[email protected]>

* chore: re-trigger Workers Builds after migration bootstrap

---------

Co-authored-by: Claude <[email protected]>
@whoabuddy

Copy link
Copy Markdown
Contributor

Closing — superseded by #107 which integrates the boring-tx state machine and handles nonce conflicts as part of a broader rewrite. The terminalReason values from @aibtc/tx-schemas now map directly to retry categorization, covering what this branch addressed. Thank you for the contribution. Please feel free to reopen if there is a specific aspect of #107 that does not cover what your branch addressed.

@whoabuddy whoabuddy closed this Apr 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Retry settlement on conflicting_nonce with backoff

4 participants