worldmonitor icon indicating copy to clipboard operation
worldmonitor copied to clipboard

test(checkout): close #5380 coverage gaps — false-passing idempotency test, webhook rollback, boundaries

Open lspassos1 opened this issue 4 months ago • 2 comments

Summary

Closes the High and Medium findings of #5380 (adversarial sweep of checkout/payment lifecycle coverage).

The first pass (992bc77) closed census #1–#9. A follow-up adversarial pass then mutation-tested that pass itself and found four of its own assertions were false-passing — the same defect class #5380 is about. Those are fixed here, each proven by execution, and censuses #10 and #11 are addressed too.


Part 1 — original coverage work

High

  1. False-passing idempotency test (census #1). The fixture generator in tests/checkout-transport.test.mts returned a constant literal, so asserting "same key on both attempts" was tautological — a mutant regenerating the key per attempt stayed 9/9 green. The fixture now issues distinct keys per invocation and counts calls; the retry test asserts exactly one generator invocation reused verbatim across both attempts. Mutation-verified. The same test also asserts the retry request is byte-identical (URL/method/headers/body) and that the caller receives the final attempt's Response identity — covering census #5 and #6.
  2. Malformed late webhook rollback (census #2) — permanent regression in convex/__tests__/webhook-rollback-boundaries.test.ts: customer.email arriving as a number crashes the customer upsert after the subscription insert + entitlement recompute in the same mutation; the test proves processWebhookEvent rolls back entirely (zero subscriptions/entitlements/webhookEvents rows) and that Dodo's retry of the same webhookId then processes cleanly.
  3. No-user wiring (census #3) — see Part 2, finding 3; the original source-grep approach did not hold.

Medium

  1. RETRYABLE_CHECKOUT_STATUSES contents pinned literally as {502, 503, 504} (census #4).
  2. Pending-payment block window boundary (census #7) — see Part 2, finding 1.
  3. Cancelled paid-through boundary at the checkout guard (census #8) — see Part 2, finding 2.
  4. Equal-timestamp lifecycle ordering: isNewerEvent rejects equal timestamps, and a same-timestamp cancellation replay leaves the activated subscription untouched (census #9).

Part 2 — hardening pass: four false-passes in the above, each proven by execution

1 + 2. The two "exact boundary" tests never touched the boundary

Both seeded from a live Date.now(), so by query time the row sat a few ms past the edge — where .gt and .gte agree. Mutations against 992bc77, both surviving 8/8 green:

mutation before after
.gt("occurredAt", windowStart) → .gte(...) 8/8 green RED
sub.currentPeriodEnd > now → >= now 8/8 green RED

Fixed by freezing the clock (the convex/__tests__/businessSeats.test.ts pattern) so the seeded value lands exactly on the edge, plus a +1ms partner case for each so the pair pins the edge position, not just its exclusivity.

3. The no-user wiring source-grep guard stayed green with the bug restored — twice

Two mutations, both verified green against the guard at 992bc77:

  • (a) comment-ordering. Moving openSignIn() above the persist calls and leaving a comment naming savePendingCheckoutIntent(intent) above it — indexOf found the comment first, so the ordering assertion held while the real ordering was inverted.
  • (b) helper bypass. Writing sessionStorage.setItem(...) directly in the redirect branch — the negative grep for savePendingCheckoutIntent never fired, so the stale auto-resume leak this suite exists to prevent came back silently.

Fix (small production change): the effect sequencing moves out of checkout.ts's inline if/else into runNoUserPath() in the leaf policy module, reducing the caller to a handler literal. The suite now runs the real function against a recorder and asserts the exact effect sequence — which kills (a). For the residual handler literal, the guard is now a call-site count pin (what regex is actually reliable for), which kills (b): any new write site in checkout.ts moves a count. Both mutations now go RED.

4. Rollback test could silently stop testing rollback

rejects.toThrow() accepted any error, so upfront payload validation would keep it green while it no longer proved anything transactional. Now pinned to the post-insert email.trim crash site.


Part 3 — the two censuses previously left open

Census #10 (Dodo timeout/retry mock contract). isDefinitiveDodoNotFound is the gate that decides whether reconciliation may downgrade a paying customer, but every test drove it through the action's errorInjectionForTest seam — a hand-rolled Object.assign(new Error(), { status }) stub, so the assertions only proved our stub matches our own reader. billing.test.ts additionally vi.mocks the whole dodopayments module with a two-property class, so the real error classes are absent there by construction.

Now pinned against the SDK's actual exported error instances. Statuses the vendor really stamps, verified by probe:

real SDK error .status may downgrade?
NotFoundError 404 ✅ yes — the only one
AuthenticationError 401 ❌
RateLimitError 429 ❌
InternalServerError 500 ❌
APIConnectionError (none) ❌
APIConnectionTimeoutError (none) ❌
APIUserAbortError (none) ❌

Mutating the classifier to .status !== undefined reds 4 of these. This also fails if the vendor renames .status or ever stamps a status onto a timeout error — either of which would convert a transient blip into a customer downgrade.

Census #11 (concurrent webhook exactly-once) — deliberately still open. Probed the harness: convex-test runs mutations to completion one at a time, so dispatching both deliveries without awaiting does not interleave their transactions. Added a test that pins what is provable — two in-flight deliveries of one webhookId leave exactly one activation, the second on the dedup branch, and neither rejects (a rejection would make the HTTP action 500 and have Dodo retry an already-applied event). The genuine interleaving is closed in production by Convex's serializable isolation (the first insert invalidates the second's read set), which is a property of the runtime, not of this code. The test comment says exactly this so it is not mistaken for a race proof.


Type of change

  • [x] Bug fix

Affected areas

  • [x] API endpoints (/api/*)
  • [x] Other: test coverage for checkout transport, webhook lifecycle, checkout guards; small extraction in checkout.ts / checkout-no-user-policy.ts

Checklist

  • [x] No API keys or secrets committed
  • [x] TypeScript compiles without errors (npm run typecheck:all)

Documentation Alignment Checklist

N/A — no documented contract changes. The one production change moves existing effect sequencing into the leaf policy module with identical behavior.

Verification

  • npm run test:convex: 58 files / 1139 tests green.
  • Checkout family tests/checkout-*.test.mts: 169/169.
    • Note: the runNoUserPath rename initially broke 20 of these — three harnesses stub ./checkout-no-user-policy with an esbuild string that only exported decideNoUserPathOutcome. All three stubs repointed and the family is green.
  • Adjacent suites touching checkout.ts (email-masking, pro-checkout-intent-url, funnel-analytics-policy, pro-banner-entitlement-race, product-catalog-freshness, deploy-config): 261/261; chunk-graph guards (panel-cluster-chunks, dashboard-eager-chunks): 10/10.
  • npm run typecheck:all clean; biome check clean on all changed files.
  • Mutation matrix (every claim proven by execution, not inspection):
mutation before after
per-attempt idempotency key regeneration RED RED
.gt → .gte on the pending-payment window 🟢 green (false pass) RED
currentPeriodEnd > now → >= now 🟢 green (false pass) RED
openSignIn() above the persists, comment naming the persist 🟢 green (false pass) RED
direct sessionStorage.setItem in the redirect branch 🟢 green (false pass) RED
isDefinitiveDodoNotFound: === 404 → !== undefined n/a (uncovered) RED

Screenshots

N/A — test-only behavior; the one production change is a behavior-preserving extraction.

lspassos1 avatar Jul 25 '26 19:07 lspassos1

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
worldmonitor Ignored Ignored Preview Jul 29, 2026 10:19am

Request Review

vercel[bot] avatar Jul 25 '26 19:07 vercel[bot]

Greptile Summary

This PR strengthens checkout and billing lifecycle regression coverage.

  • Adds Convex tests for webhook transaction rollback, retry behavior, lifecycle ordering, and checkout-guard boundaries.
  • Strengthens checkout transport assertions for idempotency-key reuse, retry request identity, final response identity, and retryable statuses.
  • Adds source-level assertions for signed-out checkout branch wiring.

Confidence Score: 4/5

The PR appears safe to merge, with non-blocking test-robustness issues in its clock-boundary and source-slicing assertions.

The production behavior is unchanged and the new rollback and transport tests correctly exercise their intended paths, but two boundary tests can miss inclusive-comparator regressions and the source-wiring assertions are sensitive to harmless control-flow restructuring.

Files Needing Attention: convex/tests/webhook-rollback-boundaries.test.ts; tests/checkout-no-user-policy.test.mts

Important Files Changed

Filename Overview
convex/tests/webhook-rollback-boundaries.test.ts Adds valuable rollback and lifecycle tests, but the two exact-time boundary checks do not freeze the clock and therefore do not reliably distinguish strict from inclusive comparisons.
tests/checkout-no-user-policy.test.mts Adds caller-wiring coverage through source inspection, though its textual branch-boundary extraction is fragile around nested or early-return control flow.
tests/checkout-transport.test.mts Correctly removes the constant idempotency-key fixture blind spot and strengthens retry contract assertions without an identified issue.

Reviews (1): Last reviewed commit: "test(checkout): close the #5380 coverage..." | Re-trigger Greptile

greptile-apps avatar Jul 28 '26 21:07 greptile-apps