Repository navigation
Description
Spun out of #3623 step 5 (#3691).
What
Three webhook handlers swallow inner DB errors and return 200, so Stripe never retries. The UNIQUE constraint on revenue_events.stripe_invoice_id makes the legitimate-retry case safe (second INSERT throws on UNIQUE; current swallow is correct), but it also masks transient errors:
- `http.ts:4195` — `invoice.paid` revenue_events INSERT
- `http.ts:4393` — `invoice.payment_failed` failed-payment INSERT
- `http.ts:4469` — `charge.refunded` refund INSERT
Failure mode: transient DB error (statement timeout, connection reset, blip on the revenue_events table specifically) → row lost permanently → Stripe got 200, never retries → admin reporting drift compounds quarter over quarter.
Why this matters
Financial-integrity issue per security review on #3691:
- `revenue_events` feeds admin dashboards, internal reporting, possibly investor/board materials
- The `audit-sync-revenue-backfill` admin tool is a workaround that only covers Stripe's listable invoice window (90 days for some endpoints; refunds older than that never reconcile)
- At AAO's stage today this is "ship-before-EOQ-books-close" not "ship-now"; before any external financial reporting based on this table, fix it.
Fix shape
Distinguish UNIQUE-violation (code: '23505' from PG) from everything else. Swallow 23505 (legitimate dedupe), re-throw the rest:
```typescript
} catch (err: any) {
if (err?.code === '23505') {
logger.info({ invoiceId: invoice.id }, 'revenue_events duplicate, dedupe ok');
} else {
throw err; // let Stripe retry transient failures
}
}
```
Or equivalently: add `ON CONFLICT (stripe_invoice_id) DO NOTHING` to the INSERT (so successful duplicates are silent), then re-throw any error that escapes (because real failures wouldn't be conflict errors).
Same fix applies to all three sites + the `org_activities` INSERT at `http.ts:3956` (no UNIQUE there yet — would need `ON CONFLICT DO NOTHING` keyed on something stable like `(organization_id, activity_type, resource_id)` or a fresh `stripe_event_id` column).
Done state
- Three INSERTs at lines 4195/4393/4469 use the dedupe-on-UNIQUE / throw-on-real-error pattern
- org_activities INSERT at 3956 either gets the same treatment + a UNIQUE constraint, or is documented as best-effort and stays swallowed
- Tests cover (a) duplicate Stripe event → no second row + 200 returned, (b) transient DB error → 5xx returned + Stripe retries
Refs
- Catch-block audit context: fix(billing): re-throw on core subscription UPDATE failure + relink integration tests (#3623 step 5) #3691
- Lazy reconcile (covers the customer-impact side): feat(billing): lazy reconcile on certification paywall hit (#3623 step 3) #3663
Activity
fix(billing): re-throw on transient revenue_events INSERT failure (#3693