Skip to content

harden(billing): add default-off durable Stripe event receipts - #21372

Closed
Git-on-my-level wants to merge 18 commits into
mainfrom
lane/sub-inf-event-ledger
Closed

Git-on-my-level wants to merge 18 commits into
mainfrom
lane/sub-inf-event-ledger

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

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 use malformed_doc. The generated flag-registry date is restored to 2026-10-13, and the inherited accidental IFS= 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

  1. Crash-after-effects/before-receipt can replay effects; this is at-least-once recovery, not cross-system exactly-once.
  2. Tokens fence receipt completion, not user writes; a worker surviving beyond its lease can overlap recovery.
  3. Different event ids still race, and out-of-order detection does not change legacy entitlement ordering.
  4. SDK work can finish after HTTP waiting times out; an unconfirmed claim never runs the handler.
  5. TTL policies and metric/alert rollout require separate operator authorization; storage is not physically bounded yet.

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.

@Git-on-my-level
Git-on-my-level marked this pull request as ready for review October 13, 2026 10:45
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T10:54:15.454305Z ee370e0 Draft marked ready
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Landed as part of #21373 (top of the stacked branch, which contains this PR's commits; reviewed with it). Closing to avoid repeated squash-merge conflicts. cb81331

@github-actions

Copy link
Copy Markdown
Contributor

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:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

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!

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