Skip to content

fix(billing): closure cleanup ends a renewal Stripe will never collect, so it always reaches the customer delete (ISSUE-1588) - #976

Open
2witstudios wants to merge 11 commits into
mainfrom
pu/closure-uncollected-renewal
Open

2witstudios wants to merge 11 commits into
mainfrom
pu/closure-uncollected-renewal

Conversation

@2witstudios

@2witstudios 2witstudios commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner

Change

ISSUE-1588 is confirmed, and this PR fixes it. A member who closes their account with a renewal Stripe will never collect no longer leaves their closure cleanup owed for ever.

Why it looped. The cleanup cancels the subscription with invoice_now:false. Stripe's cancel turns off collection (auto_advance:false) on the subscription's open and draft invoices without ending them. Two ordinary cases then never finish:

  • A renewal still a draft at closure (Stripe holds it about an hour before finalizing) has no InvoicePayment. Its pass defers zero_membership, so the invoice stays owed.
  • An open renewal after a failed charge has its default InvoicePayment open. Only a paid, pre-closure payment resolved, so it stays owed/payment_unresolved.

In both cases the cleanup restarts instead of deleting, every time, and only the 2 h billing_cleanup_overdue alert named it. The Stripe test world hid both: failRenewal made no payment, and cancel never stopped collection.

The fix.

  1. End it (edge, invoices lane). When the lane reads an owned invoice that moved no money (amount_paid 0, and draft, open or uncollectible, which is still payable), it voids it, then reads it again before the pass. A draft is finalized first with auto_advance:false, so nothing is collected. The decision is pure (uncollectedInvoiceStep).
    • Both calls are idempotent by state: a repeat is refused as no longer a draft or open, and the re-read decides. So no fixed idempotency key can replay an old refusal.
    • Every finalize or void error is reported as billing.cleanup.failed, stage invoice_end.
    • Only Stripe declining the step (HTTP 400, e.g. a payment applied or in flight) leaves the invoice to its pass, whose money facts decide as before. A refused void is tried again when the cleanup restarts its scans.
    • Any other error (timeout, 429, 5xx, 401/403) records a failure, so the job retries with backoff.
    • A draft carrying customer credit (negative starting_balance) is not finalized, so the credit is never spent on a forgiven renewal. It stays owed, as before this PR, until ISSUE-1620 ends it without applying the credit.
    • An invoice with any amount paid is never voided.
  2. Resolve it (protocol + CHECK). A payment Stripe reports canceled resolves on a new basis canceled, beside pre_closure, when nothing was paid, captured or timed as paid. That is no money moved, so no refund action is created. A payment still reported open on a void invoice reads as canceled: void is terminal and a void invoice is never payable. Stripe's docs do not say whether voiding cancels the default payment, so both readings resolve. Every finalized invoice has its default payment, so the pass keeps ADR 0117's nonzero membership and its database guards unchanged. The payment state CHECK gains the basis, added NOT VALID and then validated (two folders, per docs/operations/database.md).
  3. The Stripe test world models Stripe as documented:
    • finalizing creates the default payment, open until paid;
    • cancel turns off collection of open and draft invoices;
    • the finalize and void endpoints exist;
    • void cancels the default payment and is refused while a payment is applied or in flight (beginCollection).

What a member with an uncollected renewal sees. Nothing more from Daisy after closing: no charge, no retry, no dunning. If they open an old Stripe invoice link, it reads void. The Stripe customer is then deleted.

What the owner's Business page counts. Nothing new and nothing lost. No refund action is created (no money moved). MRR and paying counts already drop at closure, when the subscription is cancelled. The overdue cleanup alert stops firing for these accounts.

PageSpace

Builder: ag-ivnoirkw

Criteria

Criterion Code Test Evidence
ISSUE-1588 — Given an account closed with a renewal invoice open that Stripe never collects, should still finish closure cleanup and delete the Stripe customer apps/web/src/features/billing/cleanup-invoice-delivery.ts (endUncollected), uncollected-invoice.ts apps/web/integration/billing-closure-cleanup.integration.ts ('…failed renewal Stripe never collects…') CI integration
1588.a — Given a draft renewal at closure, should finalize it without collection, void it, and reach the customer delete as above; cleanup-vendor.ts (finalizeInvoice with auto_advance:false, voidInvoice) billing-closure-cleanup.integration.ts ('…draft renewal Stripe never finalizes…'); cleanup-invoice-delivery.test.ts ('…ended before its pass reads it') CI integration; unit passes
1588.b — Given an open renewal whose charge failed, should void it and reach the customer delete as above billing-closure-cleanup.integration.ts; uncollected-invoice.test.ts CI integration; unit passes
1588.c — Given a payment Stripe reports canceled, should resolve as no money moved; given one paid or partly paid, should never void its invoice packages/protocol/src/billing-payment-observation.ts (canceledWithoutMoney), billing-payment-observation-retention.ts; packages/db/src/schema/billing-payment-observation-checks.ts; payment-observation-reader.ts (paymentStatus) billing-payment-observation-retention.test.ts (two cases); payment-observation-reader.test.ts; uncollected-invoice.test.ts; cleanup-invoice-delivery.test.ts ('a void Stripe refuses…', '…denied for want of permission is reported…'); cleanup-vendor.test.ts (finalize body auto_advance=false, void body empty) unit passes
1588.d — ADR 0117 and docs/operations/billing-native.md state the rule docs – –

Validation

Machine budget: focused unit tests locally only. CI runs typecheck, lint, knip, integration and e2e.

  • bun test src/billing* (packages/protocol): pass, including the new canceled-resolution cases.
  • bun test src/features/billing/ (apps/web): 272 pass.
  • tsgo --noEmit (packages/protocol, packages/db): clean.
  • ESLint on the touched files: clean.
  • tsgo --noEmit (apps/web, outside Next's generated route types, which CI generates): clean.
  • CI at f92723d, all 27 checks green. Infrastructure contracts ran all three closure journeys:
    • 'a member closes with a draft renewal Stripe never finalizes…' (ISSUE-1588): pass, 92 s;
    • 'a member closes with a failed renewal Stripe never collects…' (ISSUE-1588): pass, 97 s;
    • 'a member closes with a renewal open and Stripe collects it after…' (LAUNCH-15.2, retry in flight): pass, 123 s.
  • Main merged since (club-in-one-sitting's migrations). This branch's two migrations were regenerated on main's chain (bun migrations:check: PASS, 19 committed), and bun pr:prepare 976 --base origin/main is clean. CI is re-running at the merged head.

Changed test assertions

  • uncollected-invoice.test.ts, added in this PR: uncollectible with nothing paid now expects 'void', after review.

  • billing-closure-cleanup.integration.ts (LAUNCH-15.2 journey): the scenario now puts Stripe's retry in flight at closure (world.beginCollection) before the payment lands mid-pass. Its assertion is unchanged: refund in full, then delete. Stripe would otherwise have the cleanup void the renewal, and a void invoice cannot later be collected.

  • The test world's InvoicePayments now carry their real status (open, paid, canceled), and amount_paid is null until paid. A paid payment reads exactly as before.

Operational impact

  • Owner action before production (ISSUE-1618, human-only): the live restricted Stripe key needs Invoices: Write. This PR is Daisy's first invoice write. Until the key has it, closure cleanup reports billing.cleanup.failed (stage delivery) and the account stays owed, as today. docs/operations/production-runbook.md step 2 now says so.

  • Two migrations: payment_canceled_resolution (CHECK replaced NOT VALID) and payment_canceled_resolution_validated (validated in a block that warns rather than fails).

  • The CHECK only widens, so no stored row can break it.

  • No configuration change.

  • New Stripe calls from the cleanup worker: POST /v1/invoices/:id/finalize and POST /v1/invoices/:id/void. Their only target is a closed account's owned invoice with nothing paid.

Architecture

ADR 0117 gains the rule: an uncollected renewal is ended, and a canceled payment resolves. The nonzero-membership rule and its guards are unchanged. The cleanup vendor port gains finalizeInvoice and voidInvoice.

Compliance & telemetry

None. No new data class, purpose, processor, retention, log field or analytics event. Stripe remains the only processor, with two more calls on data it already holds.

🤖 Generated with Claude Code

2witstudios and others added 3 commits November 30, 2026 15:29
…solves (ISSUE-1588)

A partial reread still resolves nothing, except a terminal canceled payment
that was never paid, captured or timed as paid: the default payment of a
voided invoice. Its resolved basis is 'canceled' beside 'pre_closure', and the
payment state CHECK gains it (NOT VALID, then validated).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t, so it always reaches the customer delete (ISSUE-1588)

The invoices lane voids an owned invoice that moved no money (a draft is
finalized with auto_advance off first), then reads it again before its pass.
Its default payment, canceled (or still open on the void invoice), resolves
as no money moved. A void Stripe refuses (a payment in flight) leaves the
invoice to its pass. The Stripe test world gains Stripe's real shapes: the
default payment on finalize, collection off on cancel, finalize and void.
Two closure journeys walk a draft and a failed renewal at closure; the
LAUNCH-15.2 journey's retry is in flight at closure. ADR 0117 and the
billing operations doc state the rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You'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 49 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2dff899b-feb2-4062-973a-ba23c2a7ac8d
Commits

Reviewing files that changed from the base of the PR and between 532e0d6 and bf709a4.

Files selected for processing: 27

  • apps/web/integration/billing-closure-cleanup.integration.ts
  • apps/web/integration/billing-journey.test-support.ts
  • apps/web/src/features/billing/cleanup-delivery.ts
  • apps/web/src/features/billing/cleanup-invoice-delivery.test-support.ts
  • apps/web/src/features/billing/cleanup-invoice-delivery.test.ts
  • apps/web/src/features/billing/cleanup-invoice-delivery.ts
  • apps/web/src/features/billing/cleanup-vendor.test.ts
  • apps/web/src/features/billing/cleanup-vendor.ts
  • apps/web/src/features/billing/cleanup-worker.ts
  • apps/web/src/features/billing/invoice-step-error.test.ts
  • apps/web/src/features/billing/invoice-step-error.ts
  • apps/web/src/features/billing/payment-observation-reader.test.ts
  • apps/web/src/features/billing/payment-observation-reader.ts
  • apps/web/src/features/billing/stripe-test-world.test-support.ts
  • apps/web/src/features/billing/uncollected-invoice.test.ts
  • apps/web/src/features/billing/uncollected-invoice.ts
  • docs/decisions/0117-premium-billing.md
  • docs/operations/billing-native.md
  • docs/operations/production-runbook.md
  • packages/db/migrations/20261130224152_payment_canceled_resolution/migration.sql
  • packages/db/migrations/20261130224152_payment_canceled_resolution/snapshot.json
  • packages/db/migrations/20261130224153_payment_canceled_resolution_validated/migration.sql
  • packages/db/migrations/20261130224153_payment_canceled_resolution_validated/snapshot.json
  • packages/db/src/schema/billing-payment-observation-checks.ts
  • packages/protocol/src/billing-payment-observation-retention.test.ts
  • packages/protocol/src/billing-payment-observation-retention.ts
  • packages/protocol/src/billing-payment-observation.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-30T21:39:01.344997Z 48b6eb3 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@2witstudios

Copy link
Copy Markdown
Owner Author

Review: fix(billing): closure cleanup ends a renewal Stripe will never collect, so it always reaches the customer delete (ISSUE-1588) at 48b6eb3

Reviewer: ag-uvf3wwug · Builder: ag-ivnoirkw

The design holds up. An owned invoice is voided only after readCleanupInvoiceIdentity binds it to the closed account's mode and customer, and only when it moved no money. The canceled basis widens both the protocol and the CHECK without touching ADR 0117's nonzero membership. A NULL in the new CHECK branch fails closed under the outer coalesce(…, false). open → canceled merges without conflict (statusConflict lets open move), and a canceled payment cannot later turn paid. The findings below are about whether this works in production, not about the model.

Checks

  • bun test src/features/billing/ (apps/web): PASS, 270 pass / 0 fail
  • bun test src/billing (packages/protocol): PASS, 103 pass / 0 fail
  • bun test src/schema (packages/db): PASS, 10 pass / 0 fail
  • CI at this SHA, Migration journal collision guard: PASS
  • CI at this SHA: quick-check (typecheck, lint, knip, integration), Playwright, Admin E2E, isolated native browser ×7, dependency audit and advisory reports were all PENDING when this review was written. This review does not count any of them as passed.
  • ISSUE-1588 integration journeys (billing-closure-cleanup.integration.ts:106, :151) and the existing LAUNCH-15.2 journey: NOT RUN locally (machine budget, CI only), pending in CI
  • aidd churn: NOT RUN (it needs npx, and the repository is Bun only)

Findings

  • major · apps/web/src/features/billing/cleanup-vendor.ts:57 · Unchecked production key permission (CONFIRMED: first write; SUSPECTED: the effect). This PR makes Daisy's first Stripe invoice write. Before it, Daisy only listed and retrieved invoices: subscription-reader.ts:50, invoice-pass-vendor.ts:34, club-billing.ts:51. Production runs a restricted live key created "with only what … invoices … need" (docs/operations/production-runbook.md:211, :490). The PR says "No configuration change". If the key has Invoices: Read, finalize and void fail with a permission error. endUncollected (cleanup-invoice-delivery.ts:226-230) turns every rejection into "Stripe refused", with no log. The ISSUE-1588 loop then continues in production while CI is green, and only the 2 h billing_cleanup_overdue alert shows it. Correct looks like:
    • Runbook step 2 names Invoices: Write (finalize, void).
    • The PR's Operational impact lists the key permission change for owner sign-off, since AGENTS.md requires human sign-off on secrets.
    • A rejected finalize or void is told apart from a business refusal and surfaces as a classified code: the Stripe error type/code only, no PII. At minimum, a permission or authentication error does not read as "refused".
    • To confirm the effect, check the live key's Invoices permission.
  • minor · apps/web/src/features/billing/cleanup-vendor.ts:67 · Fixed idempotency keys can replay a refusal for 24 h (SUSPECTED: the test world does not model replay). The keys are fixed per invoice: daisy-cleanup-void-${id} and daisy-cleanup-finalize-${id}. Stripe stores the result of any request that began executing, including 4xx and 5xx errors, and replays it for that key for 24 h. Scenario: the void is refused while a retry is processing (the case beginCollection models), then that retry fails. Every later pass replays the stored refusal for about 24 h, so cleanup stays owed and the overdue alert fires at 2 h. A transient 500 on finalize behaves the same way. Correct looks like: scope the key to the attempt (for example, include the claim id), or drop it. Finalize and void are already idempotent by state: a repeat call is refused as non-draft or not open, and the re-read decides.
  • minor · apps/web/src/features/billing/uncollected-invoice.ts:25 · uncollectible is not ended (SUSPECTED: depends on the account's failed-payment setting). The code and its test (uncollected-invoice.test.ts:22) treat uncollectible as "already ended". In Stripe, an uncollectible invoice is still payable and can still be voided, and its default payment stays open. paymentStatus (payment-observation-reader.ts:115) maps only void. If Stripe's "manage failed payments" setting marks invoices uncollectible, a closed account with one keeps that payment owed/payment_unresolved: the same restart loop. Nothing in docs fixes that setting, and the club page already models uncollectible (billing-page.tsx:33). Correct looks like: void an uncollectible invoice with amount_paid 0 as well. The test world's own error text says Stripe allows it (stripe-test-world.test-support.ts:1017), but its voidInvoice refuses it. Alternatively, pin the required setting in billing-native.md.
  • minor · apps/web/src/features/billing/cleanup-vendor.test.ts:6 · Nothing pins auto_advance:false on finalize (CONFIRMED by reading). This parameter carries the "nothing is collected" guarantee. Removing it leaves every test green: the test world only copies the parameter into autoAdvance (stripe-test-world.test-support.ts:1000), nothing reads autoAdvance to collect, and cancel has already cleared it. The draft journey asserts only that the POST path was called (billing-closure-cleanup.integration.ts:140). Correct looks like: extend the pinned-SDK vendor test (the one that already pins cancel's "no automatic financial changes") with finalizeInvoice and voidInvoice. Assert the body auto_advance=false and the Idempotency-Key header.
  • nit · apps/web/src/features/billing/cleanup-invoice-delivery.ts:233 · The path where the re-read fails after a finalize or void (return null, which becomes failure) has no unit test. Correct looks like: a case where the second invoice() throws and the job records failure, never a pass.
  • nit · apps/web/src/features/billing/uncollected-invoice.ts:10 · The JSDoc sits on the module-private type alias, not on the exported uncollectedInvoiceStep, so editors attach it to the type. Correct looks like: move the comment below the type, onto the function.

Criteria

  • ISSUE-1588 — Given an account closed with a renewal invoice open that Stripe never collects, should still finish closure cleanup and delete the Stripe customer within the stated bound · PARTIAL · cleanup-invoice-delivery.ts:189-198, :213-239 · billing-closure-cleanup.integration.ts:106, :151 (byCleanupDeadline). The code and unit tests pass. The journeys have not yet run at this SHA. The major finding is a production gap that these tests cannot show.
  • 1588.a — Given a draft renewal at closure, should finalize it without collection, void it, and reach the customer delete · PARTIAL · uncollected-invoice.ts:24; cleanup-vendor.ts:57-62 · cleanup-invoice-delivery.test.ts:257; billing-closure-cleanup.integration.ts:106 (CI pending). The "without collection" part has no test (minor finding 4).
  • 1588.b — Given an open renewal whose charge failed, should void it and reach the customer delete · PARTIAL · uncollected-invoice.ts:25 · uncollected-invoice.test.ts:12; billing-closure-cleanup.integration.ts:151 (CI pending)
  • 1588.c — Given a payment Stripe reports canceled, should resolve as no money moved; given one paid or partly paid, should never void its invoice · PASS · billing-payment-observation.ts:262-273, retention.ts:137-142, payment-observation-reader.ts:115-119, billing-payment-observation-checks.ts:113-120, uncollected-invoice.ts:23 · billing-payment-observation-retention.test.ts:273, :341; payment-observation-reader.test.ts:151; uncollected-invoice.test.ts:12; cleanup-invoice-delivery.test.ts:257, :326
  • 1588.d — ADR 0117 and docs/operations/billing-native.md state the rule · PASS · docs/decisions/0117-premium-billing.md:399-413; docs/operations/billing-native.md:152-166 · n/a. The runbook's key-permission step is not updated (major finding).

OWASP Top 10 (2025)

  • A01 Broken Access Control: reviewed. A void is reached only after readCleanupInvoiceIdentity binds mode, customer and invoice id (cleanup-invoice-delivery.ts:189-193), and the binding is checked again after the change.
  • A02 Security Misconfiguration: reviewed. The restricted-key permission is the major finding.
  • A03 Software Supply Chain: not applicable. No dependency changes.
  • A04 Cryptographic Failures: not applicable.
  • A05 Injection: reviewed. The CHECK is static SQL, and Stripe ids come from regex-validated scans.
  • A06 Insecure Design: reviewed. Forgiving the renewal is the plan's recommended answer to open question 1. Money paid is never voided.
  • A07 Authentication Failures: not applicable. The change runs in a server worker with no user session.
  • A08 Software/Data Integrity: reviewed. The migration is NOT VALID and then validated in two folders. The idempotency keys are minor finding 2.
  • A09 Logging & Alerting Failures: reviewed. Rejections are swallowed without a log (part of the major finding).
  • A10 Mishandling of Exceptional Conditions: reviewed. The catch-all at cleanup-invoice-delivery.ts:226-230 treats every rejection as "refused" (part of the major finding).

Privacy & telemetry

Checked:

  • Logs, metrics, analytics: no new log field, metric or analytics event.
  • New stored data: one new JSONB state variant, resolved/canceled with partial facts. Its facts shape (status, amounts, charge id, period) already existed under owed.
  • Vendor calls: the idempotency keys sent to Stripe carry only Stripe's own invoice id.
  • Personal data: none reaches a log, an error report or analytics.

The major finding asks for a classified error code when finalize or void is rejected. That code must carry only Stripe's error type and code.

Verdict

0 blocker / 1 major / 3 minor / 2 nit — CHANGES REQUESTED

@2witstudios 2witstudios left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Inline threads for the review comment at #976 (comment). The finding on cleanup-vendor.test.ts (nothing pins auto_advance:false) is in that comment only: the file is not in this diff.

),
// A closed account's uncollected renewal is ended, never collected: the
// draft is finalized with auto_advance off, so nothing is attempted.
finalizeInvoice: (id) =>

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

major: This is Daisy's first Stripe invoice write; every earlier call only lists or retrieves. Production uses a restricted live key (production-runbook.md:211, :490), which may have Invoices: Read only. A permission error here is swallowed as "refused" by endUncollected (cleanup-invoice-delivery.ts:226-230), with no log, so the ISSUE-1588 loop continues in production while CI is green.

Fix:

  • Name Invoices: Write in runbook step 2.
  • List the key change for owner sign-off in Operational impact.
  • Tell a permission or authentication rejection apart from a business refusal, logged as a classified Stripe type/code only.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in e10be59. A finalize or void error is now classified (stripeRefusedStep in cleanup-invoice-delivery.ts). Only an HTTP 400 invalid request (Stripe declining the step: a payment applied or in flight, no longer a draft or open) leaves the invoice to its pass. A permission, authentication, rate or server error is thrown, so the worker logs billing.cleanup.failed (stage delivery) with its code and sends the raw error only to the scrubbed reporter. Test: '…denied for want of permission is reported, never read as a refusal…' (403 propagates). production-runbook.md step 2 now names Invoices: Write. The key change is the owner's: filed as ISSUE-1618 (human, owner, Pending decisions), and the PR's Operational impact lists it.

stripe.invoices.voidInvoice(
id,
{},
{ ...options, idempotencyKey: `daisy-cleanup-void-${id}` },

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

minor (SUSPECTED): This idempotency key is fixed per invoice. Stripe replays a stored 4xx or 5xx for the same key for 24 h. If a void is refused while a retry is processing and that retry then fails, every later pass replays the refusal for about 24 h, and billing_cleanup_overdue fires at 2 h. The finalize key on line 61 has the same problem.

Fix: scope the key to the attempt (for example, the claim id), or drop it. Finalize and void are already idempotent by invoice state, and the re-read decides.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in e10be59: no fixed keys. Finalize and void are idempotent by state (a repeat is refused as no longer a draft or open, and the re-read decides), so they are sent without an idempotency key, and an earlier refusal can never be replayed.

const parsed = invoice.safeParse(raw);
if (!parsed.success || parsed.data.amount_paid !== 0) return null;
if (parsed.data.status === 'draft') return 'finalize';
return parsed.data.status === 'open' ? 'void' : null;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

minor (SUSPECTED): In Stripe, an uncollectible invoice is still payable and can still be voided, and its default payment stays open. paymentStatus maps only void, so a closed account with an uncollectible invoice keeps that payment owed: the same restart loop, if the account's failed-payment setting marks invoices uncollectible.

Fix: void uncollectible with amount_paid 0 too, and let the test world allow it as its own error text says. Alternatively, pin the required setting in billing-native.md.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in e10be59: an uncollectible invoice with amount_paid 0 is voided too, since it is still payable. uncollected-invoice.test.ts now expects 'void' for it. The reader still maps only a payment on a void invoice to canceled, because an uncollectible one can still be paid; once voided, it reads canceled.

);
try {
current = await input.port.invoice(invoiceId);
} catch {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

nit: No unit test covers a re-read that fails after a finalize or void (null, which becomes failure). Add a case where the second invoice() throws and the job records failure, never a pass.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Added in e10be59: in the same new test, a void whose invoice then cannot be read again records failure and starts no pass.

amount_paid: minor,
});

/**

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

nit: This JSDoc attaches to the private UncollectedInvoiceStep type, not to the exported function. Move it below the type.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in e10be59: the JSDoc now sits on uncollectedInvoiceStep, with the uncollectible case added. The type alias is left bare.

…ead as a refusal; no fixed keys replay a refusal; an uncollectible renewal is voided too; the vendor test pins auto_advance=false; the runbook names Invoices: Write (ISSUE-1588)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@2witstudios

Copy link
Copy Markdown
Owner Author

/review (CHANGES REQUESTED, 0 blocker / 1 major / 3 minor / 2 nit) is answered in e10be59. Each inline thread has its reply. Also: cleanup-vendor.test.ts now pins finalize's body auto_advance=false and void's empty body through the installed SDK. Difference review next.

() => false,
(error: unknown) => {
if (stripeRefusedStep(error)) return true;
throw error;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Important: A Stripe timeout, connection error, 429 (rate limit or lock_timeout) or 5xx on finalize or void is now thrown out of the delivery instead of being recorded as a retryable failure. Any error without statusCode === 400 is rethrown here, and the worker only catches it and reports billing.cleanup.failed. No failure is recorded, so retryAt and attempts never advance and the claim stays held until claimMs (30s) expires. The job is then claimed again every 30s with no backoff, sending another read and void to Stripe and another error report each time. A persistent 403 (a key still on Invoices: Read) repeats every 30s indefinitely. Every other port call in cleanup turns transport failures into failure(); cleanup-subscription-delivery.ts says "only transport failures become vendor retry".

Fix: return failure(input, request) for errors with no statusCode, 429 or >=500, and rethrow only 401/403, or record a failure and report them as well.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 0d34335. Every finalize or void error is now reported through an injected failed. The worker wires it to billing.cleanup.failed, stage invoice_end: classified log, raw error only to the scrubbed reporter. Only a 400 (Stripe declining the step) leaves the invoice to its pass. Any other error (no status, 429, 5xx, 401/403) returns null, so the delivery records failure, and attempts and retryAt advance with the job's backoff. Nothing is thrown out of the delivery any more. Test: '…denied for want of permission is reported and retried…' (403 reported, failure recorded, no pass).

raw,
);
if (!owned || owned.invoiceId !== invoiceId) return failure(input, request);
const ended = await endUncollected(input, invoiceId, raw);

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Important: The uncollected renewal is ended only in startCurrent, before a pass exists. In the LAUNCH-15.2 shape (a retry in flight), the void is refused and the pass starts on the open invoice. If that in-flight retry then fails instead of landing, the invoice stays open with amount_paid 0 and collection turned off. advanceCurrent never tries to end it again, so its payment stays open/owed and the customer is never deleted. That is the ISSUE-1588 stuck state. The same gap applies to accounts whose invoice pass had already started before this deploys.

Fix: retry endUncollected once a pass finds its invoice still open and unpaid, or defer the pass while a refusal was caused by a processing payment. Also check whether any recheck path brings such accounts back through startCurrent.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Covered by the restart, and the ADR now says so. When every lane completes with money still owed, progressCleanupScan returns startCleanup(jobId, retryAt) (billing-cleanup-scans.ts). That re-scans from fresh pages, and selected() builds each invoice frame with pass: null. So on the next round the invoice goes through startCurrent → endUncollected again. A void refused because a retry was in flight is tried again once that retry has failed, and accounts whose pass began before this deploys reach it the same way. endUncollected's doc in 0d34335 states this.

} catch {
return null;
}
if (refused) return current;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Important: After a refusal, this returns the re-read invoice even when that invoice now allows the next step. Example: finalize returns 400 because the draft was already finalized, for instance by a second delivery after the 30s claim expired. The re-read shows open with amount_paid 0, but the loop returns without voiding it, and the pass then starts on an invoice that is never ended (see the comment on line 194).

Fix: on a refusal, keep looping when uncollectedInvoiceStep(current) gives a step other than the one just refused, and stop only when the same step would repeat.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 0d34335. After a refusal the loop stops only if the re-read asks for the same step again. A draft another delivery already finalized re-reads as open, so the loop goes on to void it.

const stripeRefusedStep = (error: unknown) =>
typeof error === 'object' &&
error !== null &&
(error as { readonly statusCode?: unknown }).statusCode === 400;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Important: Every HTTP 400 is treated as Stripe refusing the step because of the invoice's state. Validation errors also return 400: an invalid parameter, or customer_tax_location_invalid from finalize when Stripe Tax is on. Those are silently left to the pass with no report, so a draft that can never be finalized keeps the account owed and nobody is told.

Fix: match Stripe's state-refusal error codes (error.code) explicitly, and rethrow or report every other 400.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Partly changed in 0d34335. Every 400 is now reported (billing.cleanup.failed, stage invoice_end), so a finalize Stripe rejects for a validation reason, such as a tax location, is no longer silent. I did not match specific error codes: Stripe documents no code for 'a payment is applied or in flight', so a code allow-list would turn that expected refusal into a retry loop. Leaving every 400 to the pass is safe for money, because the pass's facts decide and nothing is forgiven without a canceled payment. The report makes a stuck account visible beside the overdue alert.

const ended = await endUncollected(input, invoiceId, raw);
if (ended === null)
return input.running() ? failure(input, request) : ('idle' as const);
raw = ended;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Nit (optional): No running() check follows the vendor awaits in endUncollected. That function returns current when !input.running(), and the loop also exits after its second re-read without checking. startCurrent then goes on to recordInvoices, a database write, after shutdown has begun. Before this change, if (!input.running()) return 'idle' sat directly before that write.

Fix: add if (!input.running()) return 'idle' as const; after raw = ended;.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 0d34335: if (!input.running()) return 'idle' now sits directly after endUncollected and before recordInvoices.

export function uncollectedInvoiceStep(raw: unknown): UncollectedInvoiceStep {
const parsed = invoice.safeParse(raw);
if (!parsed.success || parsed.data.amount_paid !== 0) return null;
if (parsed.data.status === 'draft') return 'finalize';

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Important (please verify): Stripe applies the customer's credit balance when an invoice is finalized. If that credit covers the renewal, finalizeInvoice turns the draft paid with no charge, so the void then fails and the closed account's credit is used up on a renewal this change meant to forgive. Before this change the draft was left alone. Check how the pass handles a paid invoice that has no charge or refundable InvoicePayment, so it does not leave the account owed.

Fix: skip finalizing, or delete the draft instead (Stripe allows deleting draft invoices), when starting_balance is negative, or handle a credit-paid result explicitly.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 0d34335 for the money, and filed for the liveness. A draft whose starting_balance is negative (customer credit), or missing (no credit can be ruled out), is no longer finalized, so the credit is never spent on a forgiven renewal. Such a draft is left to its pass and stays owed, as before this PR, until a follow-up ends it without applying credit (delete the draft, or settle the balance first). That is filed as ISSUE-1620. ADR 0117 names it, and uncollected-invoice.test.ts covers the credit draft.

Comment thread docs/decisions/0117-premium-billing.md Outdated
(ISSUE-1588). Cancelling the subscription turns off collection of its open and
draft invoices without ending them, so a renewal still a draft at closure, or
open after a failed charge, would stay owed for ever. When the invoices lane
reads an owned invoice that moved no money (`amount_paid` 0, `draft` or

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Nit (optional): This ADR text says the cleanup ends invoices that are draft or open. uncollectedInvoiceStep also voids uncollectible invoices, and its unit test checks that. Fix: add uncollectible to the ADR text so the decision matches the code.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 0d34335: the ADR now says draft, open or uncollectible (still payable), and states the error handling and the credit case.

2witstudios and others added 2 commits November 30, 2026 15:52
…e and void (typecheck)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…retried with backoff unless Stripe declined the step; a refusal goes on when the invoice asks for another step; a draft carrying customer credit is left alone (ISSUE-1620); shutdown is checked before the write (ISSUE-1588)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@2witstudios

Copy link
Copy Markdown
Owner Author

Review: fix(billing): closure cleanup ends a renewal Stripe will never collect, so it always reaches the customer delete (ISSUE-1588) at 0d34335

Reviewer: owner · Builder: ag-ivnoirkw

This is a difference review of 48b6eb310..0d343353e. It covers three commits: e10be59, 9723768 and 0d34335. It checks the earlier review's findings and the /code-review inline threads, plus the new code only.

Every earlier finding is fixed. The money model is sound:

  • a credit-carrying draft is never finalized;
  • a non-400 error now records failure, so the job retries with backoff instead of throwing out of the delivery;
  • the refusal loop goes on to void a draft that another delivery already finalized.

I checked the builder's answer on advanceCurrent and it holds. When every lane completes owed, progressCleanupScan (packages/protocol/src/billing-cleanup-scans.ts:53-55) returns startCleanup. selected() then rebuilds each invoice frame with pass: null, so a refused void goes back through startCurrent → endUncollected on the next round.

What remains is about how loudly the cleanup reports, and one fix that has no test.

Checks

  • bun test src/features/billing/ (apps/web) at 0d34335: PASS, 271 pass / 0 fail
  • packages/protocol and packages/db tests: NOT RUN. Nothing in the range touches them, and they passed at 48b6eb3.
  • bun run typecheck (apps/web): NOT RUN locally (it goes through the machine heavy queue). It is left to CI quick-check.
  • CI run 46523535565 (quick-check: typecheck, lint, knip, integration) at this SHA: PENDING when this review was written. This review does not count it as passed.
  • Browser E2E run 46523535575 (Playwright, Admin E2E, isolated native ×7): QUEUED
  • ISSUE-1588 integration journeys (billing-closure-cleanup.integration.ts): NOT RUN locally. They are pending in CI.

Earlier findings

  • major · unchecked key permission: FIXED.
    • A 403 now records failure with backoff and is reported. Test: cleanup-invoice-delivery.test.ts:366.
    • Runbook step 2 names Invoices: Write.
    • The key change is filed as ISSUE-1618 for owner sign-off.
  • minor · fixed idempotency keys: FIXED. The keys are dropped (cleanup-vendor.ts:60-61).
  • minor · uncollectible not ended: FIXED (uncollected-invoice.ts:35). The test world still refuses it (see the nit below).
  • minor · auto_advance:false unpinned: FIXED. The pinned-SDK test asserts the body auto_advance=false (cleanup-vendor.test.ts:68-74).
  • nit · re-read failure untested: FIXED. Test: cleanup-invoice-delivery.test.ts:366 (unreadable).
  • nit · misplaced JSDoc: FIXED
  • /code-review · errors thrown without backoff: FIXED (cleanup-invoice-delivery.ts:237-243)
  • /code-review · advanceCurrent never re-ends: ANSWERED. This is the restart path above, verified.
  • /code-review · refusal ends the loop too early: FIXED (cleanup-invoice-delivery.ts:249). It has no test (minor 2).
  • /code-review · every 400 is read as a state refusal: ANSWERED. Every 400 is now reported. I accept not using a code allow-list, because the pass's money facts still decide. This report is the source of minor 1.
  • /code-review · running() check before the write: FIXED (cleanup-invoice-delivery.ts:199)
  • /code-review · credit spent at finalize: FIXED for the money (uncollected-invoice.ts:31). Liveness is filed as ISSUE-1620.
  • /code-review · ADR omits uncollectible: FIXED

Findings

  • minor · apps/web/src/features/billing/cleanup-invoice-delivery.ts:237 · An expected refusal is reported as an error every cleanup round, and its log line cannot be told apart from a denial (CONFIRMED by reading).
    • input.failed(error) runs for every rejection, including the HTTP 400 this PR expects in the LAUNCH-15.2 shape (a payment in flight).
    • The worker wires it to recoverableFailure (cleanup-worker.ts:60). That calls reporter.capture every time, with no throttle. Only capacity refusals are counted (server/recoverable-failure.ts:93-98).
    • A refused void leaves the pass owed. The cleanup then restarts at now + progressMs (1 s, packages/protocol/src/billing-cleanup.ts:96) and tries the void again. So each restart round sends one more error report for as long as the payment stays in flight. A draft whose finalize gets a validation 400 (for example a tax location) is reported every round, with no end.
    • workerFailures is created without a cause reader, and errorCodeOf answers INTERNAL for a Stripe error. So the billing.cleanup.failed log line reads the same for an expected 400 refusal and for a 403 denial. Only the reporter can tell them apart.
    • Correct looks like:
      • Give this sink a cause reader that returns only a fixed class, such as stripe_refused (400), stripe_denied (401/403) or stripe_unavailable (no status, 429, 5xx). Never Stripe's message.
      • Log an expected 400 refusal without capturing it, or capture it once per job, not once per round.
      • Keep capturing the denials and outages.
  • minor · apps/web/src/features/billing/cleanup-invoice-delivery.ts:249 · The "a refusal goes on when the invoice asks for another step" fix has no test (CONFIRMED by reading). In the scenario it fixes, finalize is refused and the re-read shows open, so the loop should void. The only port whose finalizeInvoice is not unexpected succeeds (cleanup-invoice-delivery.test.ts:275). If line 249 is reverted to if (outcome === 'refused') return current;, every unit and integration test still passes. Correct looks like: a delivery case where finalize throws { statusCode: 400 } and the re-read answers open with amount_paid 0. Assert the calls finalize refused, read, void, read and then the pass start.
  • nit · apps/web/src/features/billing/stripe-test-world.test-support.ts:1015 · voidInvoice still refuses any status other than open, while its own error text and the production code (uncollected-invoice.ts:35) treat uncollectible as voidable. The test world and Stripe disagree on the case this PR now handles. Correct looks like: allow open or uncollectible.
  • nit · apps/web/src/features/billing/uncollected-invoice.test.ts:27 · No test covers the money-safety branch where a draft with no starting_balance is left alone (uncollected-invoice.ts:31). { object: 'invoice' } fails parsing before it reaches that branch. Correct looks like: add uncollectedInvoiceStep({ object: 'invoice', status: 'draft', amount_paid: 0 }) → null.

Criteria

  • ISSUE-1588 — Given an account closed with a renewal invoice open that Stripe never collects, should still finish closure cleanup and delete the Stripe customer · PARTIAL · cleanup-invoice-delivery.ts:196-199, :218-253 · billing-closure-cleanup.integration.ts (…failed renewal Stripe never collects…). The code and unit tests pass, and CI integration is pending at this SHA. A draft carrying customer credit stays owed by design until ISSUE-1620.
  • 1588.a — Given a draft renewal at closure, should finalize it without collection, void it, and reach the customer delete · PARTIAL · uncollected-invoice.ts:30-34; cleanup-vendor.ts:60 · cleanup-vendor.test.ts:68-74; cleanup-invoice-delivery.test.ts:258; billing-closure-cleanup.integration.ts (CI pending). "Without collection" is now pinned.
  • 1588.b — Given an open renewal whose charge failed, should void it and reach the customer delete · PARTIAL · uncollected-invoice.ts:35 · uncollected-invoice.test.ts:12; billing-closure-cleanup.integration.ts (CI pending)
  • 1588.c — Given a payment Stripe reports canceled, should resolve as no money moved; given one paid or partly paid, should never void its invoice · PASS · unchanged in range; uncollected-invoice.ts:28 · uncollected-invoice.test.ts:12
  • 1588.d — ADR 0117 and docs/operations/billing-native.md state the rule · PASS · docs/decisions/0117-premium-billing.md:403-409; production-runbook.md:492-495 · n/a

OWASP Top 10 (2025), new commits only

  • A01 Broken Access Control: reviewed. No change. The binding check still runs before and after ending the invoice.
  • A02 Security Misconfiguration: reviewed. The runbook names Invoices: Write, and ISSUE-1618 carries the owner sign-off.
  • A03 Software Supply Chain: not applicable. No dependency changes.
  • A04 Cryptographic Failures: not applicable.
  • A05 Injection: not applicable. No new queries or input handling.
  • A06 Insecure Design: reviewed. The credit guard keeps a forgiven renewal from spending customer credit.
  • A07 Authentication Failures: not applicable. This is a server worker with no session.
  • A08 Software/Data Integrity: reviewed. With the idempotency keys removed, nothing can replay a stale refusal. Both calls are idempotent by state.
  • A09 Logging & Alerting Failures: reviewed. See minor 1: an expected refusal is reported every round, and the log has no cause class.
  • A10 Mishandling of Exceptional Conditions: reviewed. Non-400 errors now record failure with backoff, and shutdown is checked before the write.

Privacy & telemetry

Checked:

  • Logs: the billing.cleanup.failed stage invoice_end log carries only the operation and errorCode (INTERNAL). There are no Stripe ids, no message and no personal data.
  • Error reports: the raw Stripe error goes only to the scrubbed reporter (ADR 0037). It may hold the invoice id and Stripe's request id, which are not personal data.
  • Stored data and analytics: no new stored field and no analytics event. starting_balance is read but never stored or logged.
  • Vendor calls: finalize and void now send no idempotency key.

If minor 1 adds a cause, it must stay a fixed class and never Stripe's message.

Verdict

0 blocker / 0 major / 2 minor / 2 nit — APPROVE WITH MINORS

).then(
() => 'done' as const,
(error: unknown) => {
input.failed(error);

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

minor: This reports every rejection, including the 400 this PR expects while a payment is in flight. recoverableFailure captures each one with no throttle. A refused void leaves the pass owed, so the cleanup restarts at now + progressMs (1 s) and is reported once more every round. A finalize rejected with a validation 400 is reported every round, with no end. The log line is also errorCode: INTERNAL with no cause, so a refusal and a 403 denial look the same.

Fix: give the sink a cause reader that returns a fixed class only (stripe_refused, stripe_denied or stripe_unavailable). Log an expected 400 without capturing it, or capture it once per job. Keep capturing denials and outages.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Partly fixed in b91e5c2, the rest filed. The invoice step's failures now go through their own sink, which has a cause reader (invoiceStepError, invoice-step-error.ts). Its billing.cleanup.failed log line carries cause stripe-refused (400), stripe-denied (401/403) or stripe-unavailable (no status, 429, 5xx), never Stripe's message, so a refusal and a denial now read differently. Capturing an expected refusal once per job rather than every round needs a per-job memory in the reporter path. That is filed as ISSUE-1621, since it arrived after the clean verdict and is not a few lines.

}
// A refusal ends the attempt unless the invoice now asks for another
// step (a draft another delivery already finalized, say).
if (outcome === 'refused' && uncollectedInvoiceStep(current) === next)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

minor: This fix has no test. If it is reverted to if (outcome === 'refused') return current;, every test still passes: no port refuses a finalize.

Fix: add a delivery case where finalize throws { statusCode: 400 } and the re-read answers open with amount_paid 0. Assert finalize refused, read, void, read, then the pass start.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Added in b91e5c2: 'a refused finalize goes on to void when the invoice already reads open'. Finalize throws a 400 and the re-read answers open; the test expects read draft, finalize refused, read open, void, read void and then the pass start. Reverting line 249 to if (outcome === 'refused') return current; fails it.

function voidInvoice(_call: Call, invoiceId: string): Reply {
const invoice = invoices.get(invoiceId);
if (!invoice) return missing('invoice', invoiceId);
if (invoice.status !== 'open')

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

nit: The production code now voids uncollectible (uncollected-invoice.ts:35), and Stripe allows it, as this function's own error text says. This check still refuses it. Fix: allow open or uncollectible.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in b91e5c2: the world's voidInvoice accepts open or uncollectible, and its Invoice status admits uncollectible. The same commit adds the test for a draft without starting_balance (left alone).

…by its class (stripe-refused, -denied, -unavailable); tests pin the refusal continuation and the draft without a balance; the test world voids an uncollectible invoice (ISSUE-1588)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@2witstudios

Copy link
Copy Markdown
Owner Author

Review: fix(billing): closure cleanup ends a renewal Stripe will never collect, so it always reaches the customer delete (ISSUE-1588) at b91e5c2

Reviewer: ag-38tvs8xj · Builder: ag-ivnoirkw

This is a difference review of 0d343353e..b91e5c220, one commit. It checks the earlier review's findings (comment 7293423650) and its inline threads, plus the new code only.

Every earlier finding is fixed, or answered with a filed follow-up I accept. The new code is small and correct:

  • invoiceStepError maps a status to one fixed class.
  • The delivery's refusal test now reads that class, so its behaviour is unchanged.
  • The worker gives the invoice-end sink that class as its cause.

Checks

  • bun test src/features/billing/ (apps/web) at b91e5c2: PASS, 273 pass / 0 fail. That is two more than at 0d34335: the refusal-continuation case and invoice-step-error.test.ts.
  • packages/protocol and packages/db tests: NOT RUN. Nothing in the range touches them.
  • bun run typecheck and lint/knip (apps/web): NOT RUN locally (they go through the heavy queue). They are left to CI quick-check.
  • CI run 46524374026 (quick-check, integration) at this SHA: PENDING. This review does not count it as passed.
  • Browser E2E run 46524374444 at this SHA: PENDING
  • ISSUE-1588 integration journeys (billing-closure-cleanup.integration.ts): NOT RUN locally. They are pending in CI, as at the last review.

Earlier findings

  • minor · an expected refusal is reported every round, and its log cannot tell a refusal from a denial: PARTLY FIXED, rest filed.
    • The log half is fixed. billing.cleanup.failed stage invoice_end now carries cause stripe-refused, stripe-denied or stripe-unavailable (invoice-step-error.ts:10-19, cleanup-worker.ts:55-60).
    • cause is a listed code field (packages/logger/src/vocabulary.ts:216). The hyphenated values pass the code pattern (vocabulary.ts:190).
    • The capture throttle is filed as ISSUE-1621. Its criterion is written: capture the first stripe-refused per job and log the rest. I accept deferring it: it needs per-job memory in the reporter path, and the noise is bounded by how long a payment stays in flight.
  • minor · the refusal-continuation fix had no test: FIXED.
    • cleanup-invoice-delivery.test.ts:430-477 refuses finalize with a 400, then re-reads open, then voids.
    • It asserts read draft, finalize refused, read open, void, read void, then start.
    • If line 249 is reverted to return current, the calls stop after read open and this assertion fails (CONFIRMED by reading).
  • nit · the test world refused to void an uncollectible invoice: FIXED (stripe-test-world.test-support.ts:146, :1015)
  • nit · no test for a draft without starting_balance: FIXED (uncollected-invoice.test.ts:28-33 → null)
  • The /code-review threads were all resolved at the last review. Nothing in this range reopens them.

Findings

  • nit · apps/web/src/features/billing/cleanup-worker.ts:59 · No test pins that the invoice-end sink is given invoiceStepError (CONFIRMED by reading).
    • No test references invoice_end, invoiceStepError or the cause field outside invoice-step-error.test.ts. So dropping the fourth argument here keeps every test green, and the log goes back to the bare INTERNAL.
    • Correct looks like: a cleanup-worker.test.ts case where a void answers 400 and the logged billing.cleanup.failed line carries cause: 'stripe-refused'. Alternatively, have createBillingCleanupDelivery take the classifier so the delivery's own test pins it.
  • nit · apps/web/src/features/billing/invoice-step-error.ts:18 · Any other status is labelled stripe-unavailable, including a 402, 404 or 409, though the JSDoc says that class means Stripe "could not be reached."
    • The behaviour is right: anything other than a 400 records failure with backoff.
    • But a 404 for an invoice that is gone would read as an outage in the logs.
    • Correct looks like: limit stripe-unavailable to no status, 429 and 5xx, and add a fourth class (for example stripe-rejected) for any other 4xx. Or reword the JSDoc to "any other answer".

Criteria

The plan's criteria are unchanged in this range. They are restated at this SHA:

  • ISSUE-1588 — Given an account closed with a renewal invoice open that Stripe never collects, should still finish closure cleanup and delete the Stripe customer · PARTIAL · cleanup-invoice-delivery.ts:196-200, :219-256 · billing-closure-cleanup.integration.ts (…failed renewal Stripe never collects…).
    • Code and unit tests pass. CI integration is pending at this SHA.
    • A draft carrying customer credit stays owed by design until ISSUE-1620.
  • 1588.a — Given a draft renewal at closure, should finalize it without collection, void it, and reach the customer delete · PARTIAL · uncollected-invoice.ts:30-34; cleanup-vendor.ts:60 · cleanup-vendor.test.ts:68-74; cleanup-invoice-delivery.test.ts:258, :430 · CI integration pending.
  • 1588.b — Given an open renewal whose charge failed, should void it and reach the customer delete · PARTIAL · uncollected-invoice.ts:35 · uncollected-invoice.test.ts:12 · CI integration pending.
  • 1588.c — Given a payment Stripe reports canceled, should resolve as no money moved; given one paid or partly paid, should never void its invoice · PASS · uncollected-invoice.ts:28 · uncollected-invoice.test.ts:12
  • 1588.d — ADR 0117 and docs/operations/billing-native.md state the rule · PASS · unchanged in range

PARTIAL means only that CI integration is pending. Nothing failed.

OWASP Top 10 (2025), new commit only

  • A01 Broken Access Control: not applicable. There is no access path change.
  • A02 Security Misconfiguration: not applicable.
  • A03 Software Supply Chain: not applicable. No dependency changes.
  • A04 Cryptographic Failures: not applicable.
  • A05 Injection: not applicable. A status code is mapped to one of three literals.
  • A06 Insecure Design: reviewed. The refusal decision is unchanged: a 400 only.
  • A07 Authentication Failures: not applicable. This is a server worker.
  • A08 Software/Data Integrity: not applicable.
  • A09 Logging & Alerting Failures: reviewed. A refusal, a denial and an outage are now told apart in the log. The capture throttle is ISSUE-1621.
  • A10 Mishandling of Exceptional Conditions: reviewed. A classifier that throws costs only the cause (recoverable-failure.ts:58-61), never the log line or the report.

Privacy & telemetry

  • New log field: cause on billing.cleanup.failed. It is a listed code field whose value is one of three fixed literals. It is never Stripe's message, ids or request id.
  • Error reports: unchanged. The raw error goes only to the scrubbed reporter (ADR 0037).
  • No new stored field, payload kind or analytics event.

Verdict

0 blocker / 0 major / 0 minor / 2 nit — APPROVE WITH MINORS

'billing.cleanup.failed',
'billing.cleanup',
'Closed-account billing cleanup remains owed',
invoiceStepError,

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

nit: No test checks that this sink is given invoiceStepError. If the fourth argument is dropped, every test still passes, and the invoice_end log goes back to a bare INTERNAL. Fix: add a cleanup-worker.test.ts case where a void answers 400 and the log line carries cause: 'stripe-refused'. Or have the delivery take the classifier, so its own test checks it.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Filed with ISSUE-1621, which owns this reporting path: once-per-job capture of an expected refusal, and a worker-level test that the invoice-end sink logs cause: 'stripe-refused'. The wiring is one argument at cleanup-worker.ts:59, beside invoice-step-error.test.ts, which pins the classes. It arrived after the clean verdict and is not a few lines in this worker, which has no log-capturing test harness for a vendor answer.

if (status === 400) return 'stripe-refused';
return status === 401 || status === 403
? 'stripe-denied'
: 'stripe-unavailable';

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

nit: A 402, 404 or 409 also comes out as stripe-unavailable, but the JSDoc says that class means Stripe could not be reached. Retrying with backoff is still correct, but a 404 for an invoice that is gone would read as an outage in the logs. Fix: keep stripe-unavailable for no status, 429 and 5xx, and give any other 4xx its own class. Or reword the JSDoc.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Reworded in f92723d (a comment only): stripe-unavailable now reads 'any other answer (no reply, a rate limit, a server error, another client error), which the lane retries with backoff'. The behaviour is unchanged. A finer fourth class can ride ISSUE-1621.

2witstudios and others added 4 commits November 30, 2026 16:12
…ackoff (difference review nit)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ISSUE-1588)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… club_manager_admission (ISSUE-1588)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

1 participant