Repository navigation
harden(billing): add default-off durable Stripe event receipts - #21372
Git-on-my-level wants to merge 18 commits into
Conversation
…dger Co-authored-by: Cursor <[email protected]> # Conflicts: # backend/docs/runbooks/billing-reconciliation.md # backend/routers/payment.py # config/feature-flags.yaml
…age init The webhook ledger loads billing_ledger at import time, and the promotion-code stub only defined record_fallback, so package init failed on bucket_outcome. Co-authored-by: Cursor <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ee370e015d
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| async def dispatch_with_ledger(event: dict, handler: Callable[[], Awaitable[dict]], run_db: Callable) -> dict: | ||
| if not webhook_ledger_enabled(): | ||
| return await handler() | ||
| from database import stripe_event_ledger as ledger |
There was a problem hiding this comment.
Move the ledger imports to module scope
Move this ledger import, along with the get_firestore_client import inside _client(), to module scope. As written, import failures and cycles remain hidden until the first flag-enabled webhook reaches this path instead of being validated at process startup, contrary to the backend import contract. Client construction can still remain lazy by calling get_firestore_client() only at the request boundary.
AGENTS.md reference: backend/AGENTS.md:L161-L169
Useful? React with 👍 / 👎.
| return get_firestore_client() | ||
|
|
||
|
|
||
| def claim_event(event: dict[str, Any], token: str, *, now: datetime | None = None, client=None) -> Claim: |
There was a problem hiding this comment.
Use the standard Firestore injection keyword
Rename the client injection parameter to the required keyword-only firestore_client on claim_event, finish_event, and observe_event. The current one-off name breaks the repository's database-helper injection contract and forces tests and callers to special-case this ledger instead of using the shared Firestore seam.
AGENTS.md reference: backend/AGENTS.md:L173-L175
Useful? React with 👍 / 👎.
|
Hey @Git-on-my-level 👋 Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request. After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:
Before your next PR, please skim:
If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing. Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out. Thank you for being part of the Omi community! |
What changed and why
Add a default-off delivery ledger around signature-verified Stripe webhook ingestion. Completed event ids become no-ops; in-flight duplicates and correctness-critical ledger failures get 503 for retry. Firestore transactions claim receipts and maintain a per-subscription creation-time watermark; older events are detected, never reordered/discarded. Outcomes deliberately describe delivery acknowledgement rather than claiming every ancillary effect succeeded.
Review after audit → state machine → read-only reconciliation. This draft includes prerequisite commits while they remain unmerged; it targets main. INF owns all ingestion/storage code. Minimal shared-file edits: one default-off entry in config/feature-flags.yaml and its generated doc; no other lane product files or workflows changed. No flag activation, prod write or deployment occurred.
Product invariants affected
none. Flag-off behavior remains characterized; existing plan/status/price decisions are unchanged.
Verification and review hardening
Unknown-price lifecycle and checkout skips preserve HTTP 200 but finish their receipt as
failed, so a same-id resend re-enters the handler after price resolution is restored. Successful persistence and permanent ignores still acknowledge. Unresolved checkout retains the original cache effects when the ledger gate is off; both gate modes are tested. Webhook tests cover no write, repeat unresolved delivery, recovery, and subsequent suppression; another test proves replay after successful handler effects whose completion never commits and the five-minute lease expires. Ordering watermarks advance only on successful completion. Receipt errors log bounded exception types without provider text; validation observation failures usemalformed_doc. The generated flag-registry date is restored to 2026-10-13, and the inherited accidentalIFS=change is removed.Additional characterization pins active false cancellation flags, intermediate paid state, schedule overwrite of a different valid paid row, swallowed checkout cancellation failure, missing-profile mutation, creator-only invoice renewal, signature rejection through the real Stripe SDK parser before dispatch, and pre-write observation order. These pin existing behavior, without introducing entitlement policy changes.
Validation:
BACKEND_UNIT_TEST_FILE_LIST=/tmp/inf-r2-ledger-tests bash backend/test.sh: 33 ledger, 232 characterization and 23 behavioral tests passed before schedule extension. Real prices/limits remain covered by the existing plan catalog and billing suites; the broad lifecycle matrix keeps stubs for isolation. No live Firestore contention or provider writes were run.Tests
backend/tests/unit/test_stripe_event_ledger.py: strict read-before-write transactions, duplicate/in-flight/retry, token fencing, expiry, out-of-order claim/completion, malformed metadata, default-off/no IO, bounded waiting, handler/receipt failures, actual webhook entry, complete replay and write failure. Lifecycle payload/effect golden assertions remain unchanged.
UI evidence
UI-Evidence: none -- dark backend ingestion infrastructure.
Failure class (fixes)
Failure-Class: none
Ledger design / cost
Receipts contain event id/type/created, subscription id, outcome, token/attempt/lease and expires_at; no payload/UID/customer/key/exception. Five-minute leases, 90-day retention. Claim + watermark + completion normally cost three writes and four point reads; completed duplicates cost one read and zero writes. About 3k monthly subscriptions imply ~100 renewals/day; conservative ~400 first deliveries/day implies ~1,200 extra writes/day, up to ~2,000 including future TTL deletes, before extra changes/retries. This is an estimate, not a live measurement. TTL fields are present but physical TTL policies were not created. No queries/indexes needed.
Protected initially: lifecycle + checkout. Schedule and creator invoice handlers swallow failures, so their delivery receipts are observation-only; the next separate named schedule bug fix makes schedules safe to protect. Auxiliary observation errors never alter legacy responses. Each ledger wait is bounded to two seconds; correctness failures reject for retry.
Risks for reviewer
Review order and handoff
#21368 → #21370 → #21371 → #21372 → #21373
All four remain drafts against main. #21368 is merged as 764a0ac. Current origin/main was merged into the bottom branch, and review fixes were propagated upward with merge commits. No rebase, force push or skip hatch was used. No runtime acceptance, live reconciliation, secrets, flag activation, deployment or TTL policy creation was performed.
Line-Count-Exception: backend/routers/payment.py | 1641 -> 1645 | Webhook receipt dispatch stays on the existing ingestion owner.