Skip to content

feat(billing): record immutable renewal outcome observations - #25088

Merged
Git-on-my-level merged 6 commits into
mainfrom
lane/churn5-renewal-outcomes
Nov 11, 2026
Merged

Git-on-my-level merged 6 commits into
mainfrom
lane/churn5-renewal-outcomes

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

What changed and why

December renewal outcomes cannot be reconstructed from Omi's subscription-transition counters. Add immutable observation facts after the existing verified Stripe webhook handler returns: subscription-cycle invoice attempts/outcomes plus linked raw subscription creation/status/cancellation snapshots. subscription_created is a provider fact; renewal ordinal remains unknown. Duplicate deliveries and the two paid aliases share semantic keys; late failures cannot overwrite paid facts. Goal: payer-churn measurement; zero direct claimed churn lift.

This is backend-only instrumentation. It performs no Stripe or user lookup and changes no notification, entitlement, checkout, plan, price or historical data. Default-on operational kill switch: BILLING_RENEWAL_OBSERVATIONS_ENABLED=false stops all observation IO. No deployment/runtime setting is included or authorized.

Product invariants affected

none (confirmed by scripts/pr-preflight --suggest).

How it was verified

  • Focused three-file set: 319 checks passed before the final task-order refinement; the final affected file passes all 32 checks under test.sh with the CPU timing guard. Three-file command: backend/.venv/bin/python -m pytest backend/tests/unit/test_renewal_observations.py backend/tests/unit/test_subscription_ingestion_characterization.py backend/tests/unit/test_billing_webhook_delivery.py -q --disable-warnings, through omi-heavy.
  • Real verified-webhook seam fixture checks response preservation and invalid-signature rejection. Existing clock-sensitive entitlement characterization caught an observation-order issue; observation now runs after the owning handler's decision.
  • Feature-flag registry validation and generated-doc drift check passed.
  • Focused exact-runner checks pass both affected payment fixtures (20 + 26), flag-budget (24) and backfill-clear (101 + 1 skip). Static-label follow-up passes observation32 + reason-label19. No local whole backend suite. Historical head5510be65 passed terminal CI after one lead2-authorized unchanged-shard retry. Main test fix fix(tests): keep discard-restore imports outside the call CPU budget #25093 (643c991) is now merged into candidate ac6aebf; Fresh terminal CI is green for this exact head (2026-11-11T06:12:30Z; no failed or pending checks). Actual independent Luna review SHIP was collected forac6aebff4a727d2b805fbdc0f14be569a25014bc (agentctl exec-shuffle-bracket-wreck-dutch-bean-chalk); source acceptance is not inherited from a prior pin.
  • No production writes, traffic, release or live outcome is measured. GCP read tier ro-prod was used only for metadata inventory; no customer rows exported.

Tests

Targeted Python typecheck: 0 errors with the worktree Python. Independent DeepSeek SHIP at the first and refined production heads; parent verified the task-order, fallback-vocabulary and test-import corrections with focused checks. Actual independent Luna review returned SHIP at exactac6aebff4a727d2b805fbdc0f14be569a25014bc after main synchronization. Fresh terminal CI is green at the same exact head; source/CI acceptance does not establish serving.

Core and failure paths: test_renewal_observations.py covers immutable paid/failed facts, retry and paid-alias dedupe, unknown/truncated/mixed price coverage, no content/raw IDs, nonattempt states, scheduled cancellation snapshots, switch-off zero IO, and bounded best-effort failures. Related existing billing characterization/delivery files preserve entitlement effects. Full backend suite intentionally not run under the round-5 host constraint.

Limitations and readout

This is best effort, not a complete lossless ledger. Production observes through the response background task. Bounded, zero-initialized delivery counters expose eligible/created/duplicate/projection-error/write-error/timeout outcomes; these are delivery health counts, not distinct invoice denominators. Production readouts require provider_livemode=true. Mixed/truncated/unexpanded/configuration-unknown price coverage abstains. Observation failure/timeout or a failing owning handler leaves a gap; counters must disclose it. First/later renewal ordinal and unknown plan/interval coverage are explicit unknowns. Finalized, void, uncollectible and out-of-band paid snapshots are not attempts; the readout must use attempted positive-due recognized-consumer facts and distinct invoice/attempt keys.

90-day expires_at is a reader retention contract; no physical TTL policy/deletion job is installed. Lead2 must settle metadata retention/cleanup before claiming bounded stored history. No retention-policy write is authorized here. Read coverage at verified serving+24h, weekly through December, then 2027-01-08 before earliest observations expire; churn-lead reads, lead2/cl2-deploy own ordinary delivery. Source acceptance does not establish serving.

The code-side yearly UX scope and current-stock join are separate scope records under omi-workspace:data/run-2026-11-11-goals/churn-round5/. No reminder or user-facing recovery change is bundled. First-value remains a separate admitted dark build and is not activated by this PR.

UI-Evidence: none -- backend observation only; no user interface change.

Failure-Class: none

Line-Count-Exception: backend/routers/payment.py | 2093 -> 2100 | Seven net adapter lines wire the isolated observation module after the existing verified handler; billing decisions and effects remain at their original boundary, while projection/persistence and tests live separately.

Line-Count-Exception: backend/utils/metrics.py | 1730 -> 1742 | The bounded six-outcome observation counter belongs beside existing billing counters and zero-initializes every reachable label; no identifier dimensions are added.

Focused follow-up: test_renewal_observations.py (32 passed) and test_reason_label_enums.py (19 passed) through the exact test.sh guard, sequential via omi-heavy. Metric labels are explicit literals; no reason-label debt or test-duration waiver is added.

Observation-only Stripe webhook facts for subscription-cycle invoice attempts and subscription cancel/status transitions. Hashed invoice/subscription join keys, create-only semantic keys for retry and paid-alias dedupe, 90-day expires_at, default-on ops kill switch. No entitlement, notification, Stripe-read or historical-backfill effect.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 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-11T03:37:05.273544Z 5510be6 New commits
ℹ️ 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: 534d1ba7c7

ℹ️ 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".

Comment on lines +55 to +56
def _dimensions(items):
from config.plan_catalog import RECOGNIZED_STRIPE_PRICE_PLAN_TYPES, LADDER_V1_STRIPE_PRICES

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 function-local imports to module scope

The new helper introduces function-local imports here, again in _dimensions, and in persist_observation; the new tests also introduce local imports. This violates the explicit Import Rules in backend/AGENTS.md: “All imports at module top level — never inside functions.” Move these imports to module scope while keeping Firestore client construction at call time. Importing the getter does not require constructing its client.

AGENTS.md reference: backend/AGENTS.md:L166-L168

Useful? React with 👍 / 👎.

Comment on lines +73 to +75
if price_id not in RECOGNIZED_STRIPE_PRICE_PLAN_TYPES and price_id not in LADDER_V1_STRIPE_PRICES:
plans.add(None)
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Let the catalog resolver recognize configured billing prices

When a supported Stripe price is supplied through a billing environment variable but is not in the retained price constants, this prefilter rejects it before resolve_stripe_price_plan can resolve it. The resolver explicitly supports these configured prices through configured_billing_price_plans. For example, setting STRIPE_UNLIMITED_V2_ANNUAL_PRICE_ID=price_configured_fixture makes the resolver return unlimited_v2, but _dimensions returns plan='unknown'. Those valid consumer renewals are consequently excluded from the documented recognized-consumer denominator. Call the resolver for each price and use its existing exception handling to classify genuinely unknown prices.

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Coordination note: a separate isolated candidate (a7bc158218f8c8a23c357190c5b8b1eb39b6153c, branch lane/churn5-renewal-observation-isolated) adds a bounded delivery counter, provider_livemode, items.has_more abstention and production background-task deferral, and has an independent SHIP review with three P2s. This PR is the earlier head plus subscription_created/_dimensions fixes. Do not merge this PR until churn-lead picks one candidate; I have not touched the isolated worktree.

…sses

The webhook seam now imports utils.observability.renewal_observations. Two payment test harnesses stub utils.observability.fallback with an incomplete module and preload sibling modules to avoid executing the package __init__; preload the new sibling the same way so the parent package is not imported against the stub.

@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: 5510be65fe

ℹ️ 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".



def _dimensions(items, *, truncated=False) -> dict[str, str]:
from config.plan_catalog import resolve_stripe_price_plan

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 new function-local imports to module scope

The new module imports dependencies inside _dimensions, _record_outcome, and persist_observation, violating the explicit backend convention: “All imports at module top level — never inside functions.” Move these imports to module scope while keeping the get_firestore_client() invocation inside persist_observation, so client construction remains lazy without bypassing the documented import structure.

AGENTS.md reference: backend/AGENTS.md:L166-L168

Useful? React with 👍 / 👎.

Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
…25093)

## Summary

Fixes a main flake introduced with #25020's backfill test. The first
parametrized case of
`test_backfill_cleared_discard_restore_recovers_only_owed_unarmed_debt`
imported `database.conversations` and
`tests.support.lifecycle_state_table` inside pytest's call phase. The
lifecycle state table builds `FIELD_BUILDERS` by scanning source when it
loads. On CI runners that one-time import cost exceeded the backend
fast-unit 1.00s call-phase CPU guard (observed 1.01 / 1.16 / 1.19 /
1.20s). It failed unrelated PRs #25086 and #25088, for example run
42954652344, shard 8: `1.19s > 1.00s ... [None-still_refused0]`.

## Change

Test-only. The imports move into a module-scoped `restore_deps` fixture,
which runs in the untimed setup phase. The test body, its assertions,
the CPU guard and its limits are unchanged. Nothing is allowlisted.

## Verification

- m1, `pytest --durations=4 --durations-min=0
tests/unit/test_backfill_clear_refused_summary_due.py`: 101 passed, 1
skipped. The import cost now appears as `0.66s setup` on the first case;
the slowest call phase in the file is 0.03s.

Failure-Class: none

## Rollback

Revert this commit.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25093?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/25093?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25093&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
@Git-on-my-level
Git-on-my-level merged commit b1ead9b into main Nov 11, 2026
63 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/churn5-renewal-outcomes branch November 11, 2026 07:46
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