Skip to content

test(backend): regression coverage for preview validation and sync segment outcomes - #22558

Merged
aryanorastar merged 4 commits into
mainfrom
fix/backend-typecheck-preview-sync
Oct 21, 2026
Merged

aryanorastar merged 4 commits into
mainfrom
fix/backend-typecheck-preview-sync

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Regression tests for desktop-preview validation and sync segment outcomes.

This PR originally restored type checking in backend/database/desktop_previews.py and backend/utils/sync/pipeline.py. Main's #22539 has since fixed the same problem in both files, so the production changes were dropped in favor of main's code. What remains is test coverage that passes against main's implementation:

  • test_database_desktop_previews_resilience.py: untrusted preview metadata (non-dict payloads, wrong types, bad generations) is rejected by the validators rather than crashing.
  • test_sync_capture_pipeline.py: segment assignment outcomes through process_segment.

Verification

  • Both files pass on the merged tree against main's code (82 passed), each run in its own pytest process.
  • No production code, flag, deployment or data change.

Failure-Class: none

Product invariants affected

none

🤖 Generated with Claude Code

Accept unknown preview inputs at the validation boundary while preserving runtime guards. Extract sync segment failure reporting without changing retry, custody, fence or cleanup behavior.

Refs #22552. Failure-Class: none
Document the phase extraction and unchanged custody, retry, fence and turnstile contracts. Failure-Class: none
@aryanorastar
aryanorastar marked this pull request as ready for review October 19, 2026 17:03
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 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-20T03:22:22.426859Z fc5975a 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.

@cubic-dev-ai

cubic-dev-ai Bot commented Oct 19, 2026

Copy link
Copy Markdown

Auto-fix isn't included in your plan ↗

Upgrade to Team

@Git-on-my-level

Copy link
Copy Markdown
Member

The substance here is solid: this is a faithful, behavior-preserving cleanup and the guard changes are the right kind — but the red Backend unit suite needs to be re-run green on this head before merge.

Findings on the current head (158afa8):

  • backend/utils/sync/pipeline.py — _record_sync_segment_exception is a line-for-line move of the generic-handler body out of process_segment (the old if phase == 'persistence' / if phase == 'finalize' log blocks, the _persistence_failure_fingerprint retryability split, the repeat_failure_key / provider_invalid_input deferred-outcome writes, and the _record_sync_segment_failure call all match the removed block argument-for-argument). The is_destructive_operation_in_progress(e): raise fence and the finally: turnstile completion stay in the coordinator. I diffed the moved block line-by-line and found no policy change.
  • backend/database/desktop_previews.py — validators now accept object at the boundary but every runtime guard survives: _required_string/_optional_string still reject non-dict payloads before cast(dict[str, Any], data).get(key), _slug/_source_sha/_sha256 still reject non-strings, and publish_preview retains its bool/negative/"2"-string rejection for expected_generation. The cast calls sit strictly after the isinstance checks, so this widens annotations, not behavior. This is the right fix for the type errors rather than deleting guards.
  • backend/tests/unit/test_database_desktop_previews_resilience.py — good additions: test_untrusted_preview_payloads_fail_before_any_database_access (asserts client.assert_not_called()), bool-coercion generation params, and non-coerced updated_at. I ran this file locally on the PR head: all pass.
  • backend/tests/unit/test_sync_capture_pipeline.py — the new phase-preserving parametrized suite and the destructive-fence propagation test are exactly the right coverage for this refactor. Ran locally: all new tests pass.
  • backend/docs/listen_pusher_pipeline.mdx — the new "Segment failure-reporting boundary" section is accurate against the code (reporting moved to the helper; fences and turnstile stay in the coordinator).

On the failing Backend unit suite check: I pulled the shard logs. Every failure is in modules this diff does not touch — test_users_joan_followup_tombstone_guard.py (delete_person_endpoint() got an unexpected keyword argument 'memory_id'), test_developer_from_segments_idempotency.py (process() got an unexpected keyword argument 'trigger', plus ADC stub errors), and an llm_gateway collection ImportError on JIT_BUDGET_CONTRACT_ENV. None of these import or execute desktop_previews or utils/sync/pipeline. The same suite was passing on main runs before and after this PR's CI window, so this looks like a transient base-window breakage, not something this PR introduced — but CI on this head is still formally red.

Security: the boundary change keeps all rejection behavior, and logging in the extracted helper stays bounded (no exception text, paths, doc IDs, or transcript leakage — the new test asserts the private marker string never reaches the log capture).

USER IMPACT: none — internal type-checking and refactor; users should see no behavior change.

What I'd still want as a reviewer: (1) a green Backend unit suite run on this head (re-run if the failures were the transient base breakage — the specific failures above don't reproduce against this diff), and (2) nothing else — test coverage for the refactor is genuinely good. Since this touches the untrusted-input boundary of the preview publish path and the sync coordinator's exception handling, leaving the final sign-off to a human maintainer.

Feedback is AI-generated on behalf of the maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the backend Backend Task (python) label Oct 19, 2026
…-preview-sync

# Conflicts:
#	backend/database/desktop_previews.py
#	backend/utils/sync/pipeline.py
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed f9cb996: merged current main (8edd56d) and resolved the conflicts by taking main's code.

  • Why main's code: main's fix(backend): restore pyright-clean main after #22207 and #22326 #22539 ("restore pyright-clean main") fixed the same preview-validation and sync-pipeline typing problem in backend/database/desktop_previews.py and backend/utils/sync/pipeline.py, with shared _payload / _string / _expected_generation validators. Both conflicted files now match main exactly, so this PR no longer changes production code.
  • What remains: this PR's regression tests (test_database_desktop_previews_resilience.py, test_sync_capture_pipeline.py) and the listen_pusher_pipeline.mdx ownership note. Against main's implementation, those tests pass (82 passed).
  • CI's earlier failures: cannot import name 'JIT_BUDGET_CONTRACT_ENV' came from a stale test that main has since changed; nothing in the merged tree references it.
  • Local check: running preview, sync and gateway files in one pytest process shows 33 llm_gateway failures, identically on clean main. That is cross-file pollution in a combined local run, not this change; CI shards run separately.
  • Worth a decision: with the code half superseded, this PR could merge as tests + docs, or close in favor of fix(backend): restore pyright-clean main after #22207 and #22326 #22539.

Main's #22539 restored type checking by keeping process_segment whole with
an analyzer-ceiling ignore instead of extracting
_record_sync_segment_exception, so the boundary note this PR added no
longer describes the code. The regression tests stay; they exercise
behavior and pass against main's implementation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aryanorastar aryanorastar changed the title fix(backend): restore preview validation and sync type checking test(backend): regression coverage for preview validation and sync segment outcomes Oct 20, 2026
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed fc5975a: removed the listen_pusher_pipeline.mdx note, and retitled this PR to its remaining scope.

  • Why: the note described a _record_sync_segment_exception helper this PR had extracted from process_segment. After merging main, pipeline.py is main's version from fix(backend): restore pyright-clean main after #22207 and #22326 #22539, which keeps process_segment whole with an analyzer-ceiling ignore, so the note no longer described real code.
  • Now: the PR is test-only: test_database_desktop_previews_resilience.py and test_sync_capture_pipeline.py, both passing against main's code. The title and description are updated to match.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Test-only PR (no production code change per body); the production fix was already landed on main via #22539. Not a 'fix' under the confidence gate (test(backend) title, no linked bug) -> approve only.

aryanorastar added a commit that referenced this pull request Oct 20, 2026
…sites

Main's backend CI is green on its own, so the preview/sync and backend
test repairs merged in for validation (#22558, #22595) are no longer
needed here; those files now match main and remain in their own PRs.
This branch's diff against main is the checkout-first protection only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aryanorastar
aryanorastar merged commit ea5c7ec into main Oct 21, 2026
56 checks passed
@aryanorastar
aryanorastar deleted the fix/backend-typecheck-preview-sync branch October 21, 2026 02:18
aryanorastar added a commit that referenced this pull request Oct 21, 2026
…from upgrade's

Merging main kept this branch's earlier reverts of #22558 and #22595's
test files, which would have undone their now-merged coverage; those
files now match main. The branch's diff is the checkout protection plus
the client fix below.

The new checkout 409 means an existing subscription, but Flutter, macOS,
web and Windows mapped every 409 to "Resubscribe first", which is only
the upgrade route's pending-cancellation refusal. Checkout errors now
show the existing-subscription reason; the upgrade mapping is renamed so
it cannot classify checkout responses again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
aryanorastar added a commit that referenced this pull request Oct 23, 2026
## Summary

Refs #21869. Follow-up to #22193: protect users who go directly to
checkout before subscription-read reconciliation has healed their stored
paid plan.

- Extend the existing shared checkout/reactivation boundary to verify
the raw stored Stripe subscription ID even when the effective local plan
is Free and the root customer ID is absent.
- Keep same-plan/interval pending-cancellation reactivation. Other
nonterminal subscriptions return HTTP 409; unverified Stripe state or
failed reactivation returns retryable HTTP 503, never a second Checkout
session.
- Allow confirmed terminal subscriptions and definitive retrieve-only
`resource_missing`/404; preserve new-buyer, referral and one-time
PaymentIntent-grant behavior.
- Keep storefront reads, plan-change/upgrade rails, customer identity
and blocked-path entitlements unchanged. Log error types only, not
Stripe response bodies.

## Root cause and durable prevention

The validity projection can discard a stale paid record's Stripe ID when
presenting it as Basic. Customer-based eligibility cannot recover it
when the root customer ID is missing. The existing reactivation helper
already retrieves the raw stored ID, but previously returned `None` for
active subscriptions and swallowed provider/modify/persistence errors,
allowing fresh checkout.

The shared primitive is that existing boundary: `None` now means no
existing recurring subscription was found or the stored one is confirmed
ended/missing, not simply "reactivation did not happen." Regression
tests execute the real HTTP route, real eligibility and actual Checkout
builder with fake persistence and Stripe SDK objects, asserting no
billing creation on blocked requests. No additional standalone checker
or storefront mutation was introduced.

Failure-Class: new

New class: `FC-checkout-falls-through-unverified-subscription`.

## Verification

- Regression reproduced before the fix: active/trialing/past_due
subscriptions incorrectly returned HTTP 200 and reached new Checkout
creation.
- 266 targeted tests passed in isolated per-file pytest processes: 35
new checkout-first HTTP regressions plus 231 existing payment,
eligibility, subscription healing/state/plan, terminal-status and
webhook tests.
- All 34 selected `make preflight` checks passed on commit
`0e5f5f642c3ac64014b58b84ccf7e13a4bd80683`. The history-dependent
failure-class recurrence audit explicitly skips on this shallow clone;
CI with full history remains authoritative for that audit. Catalog
consistency and async-blocker scan passed; PR metadata/failure-class
validation passed.
- The remaining bounded push checks passed, including the two changed
test files (55 tests), runtime-source closure, released app-client
OpenAPI compatibility/export, generated Dart/TypeScript/Swift model
checks and pinned formatting. Only the documented local skips below were
used. GitHub CI is not claimed green.
- Local uvicorn/curl smoke passed with the real payment router,
overridden auth, and mocked provider/persistence boundaries. No real
Stripe or Firestore writes. Example request:

  ```bash
  curl -sS -X POST http://127.0.0.1:58550/v1/payments/checkout-session \
-H 'Content-Type: application/json' -d
'{"price_id":"price_checkout_current"}'
  ```

  | Fixture | HTTP | Fresh Checkout creates | Existing reactivations |
  | --- | --- | --- | --- |
  | Active subscription, missing root customer ID | 409 | 0 | 0 |
  | Stripe unavailable | 503 | 0 | 0 |
  | Confirmed ended subscription | 200 | 1 | 0 |
  | Same-plan pending cancellation | 200 | 0 | 1 |

  Local fixture-backed server stopped after smoke testing.

The CI-selected 52-file run passed: **1,770 tests passed**, with 37
tests deselected by the normal `not integration and not slow` expression
(two files entirely deselected). The 34 subscription-restructure tests
also passed separately without that marker filter in the targeted run
above. An initial local run hit the stricter default 0.30-second CPU
guard on the unchanged generated-compute inventory test; the
verification run uses CI's existing 1.0-second budget, without changing
any repository setting.

Reproduction commands (from `backend/`, with a repository-relative
changed-path list):

```bash
.venv/bin/python -m pytest tests/unit/test_checkout_first_subscription.py -q
.venv/bin/python scripts/select_backend_unit_tests.py \
  --changed-files /private/tmp/omi-21869-checkout-changed.txt \
  --output /private/tmp/omi-21869-checkout-tests.txt
BACKEND_UNIT_TEST_FILE_LIST=/private/tmp/omi-21869-checkout-tests.txt \
  BACKEND_PYTEST_WORKERS=4 BACKEND_FAST_UNIT_FAIL_SECONDS=1.0 \
  PYTHON=.venv/bin/python bash test.sh
.venv/bin/python scripts/generate_plan_catalog.py --check --base-ref origin/main
.venv/bin/python scripts/scan_async_blockers.py --dirs routers utils
```

### Validation on current main (2026-10-20)

This PR no longer bundles #22558 or #22595. They were merged in earlier
only to get backend CI green; main's backend CI is green on its own now,
so those files match main here and stay in their own PRs. The diff
against main is the checkout-first protection alone:
`routers/payment.py`, its two test files, `checkout-admission.md` and
the failure-class record.

- The 20-file billing selection (checkout-first, promotion codes,
payment, Stripe ledger and subscription tests) passes under `test.sh`:
279 passed.
- `routers/payment.py` passes the pinned type check (0 errors).
- The four local fixture-backed curl admission outcomes described above
are unchanged by this rebase; they were not re-run.

### Client handling of the new 409

Checkout's new 409 means the account already has a subscription.
Flutter, macOS, web and Windows had mapped every 409 to "Resubscribe
first to change plans.", which is only the upgrade route's
pending-cancellation refusal. Checkout errors now show the
existing-subscription reason ("You already have a subscription. Manage
your existing subscription instead of starting a new checkout."); the
upgrade route keeps "Resubscribe first". The upgrade-only helpers are
renamed (`isUpgradePendingCancelConflict`,
`SubscriptionPlanPresentation.upgradeErrorMessage`, web
`purchaseErrorMessage(error, route)`, Windows `startCheckout` returning
`existing_subscription`) so a checkout response can't be misclassified
again.

UI-Evidence: none

Only which error sentence appears changes; no layout or control changes.
Reproducing it live needs a real account with an existing subscription.
Covered instead by Flutter (`plans_sheet_cancel_pending_test.dart`,
`paywall_cancel_pending_test.dart`), macOS
(`SubscriptionPlanPresentationTests`), web
(`PlansSheet.cancelPending.test.tsx`, `cancelPending.test.ts`) and
Windows (`billing.test.ts`, `PlanUsageTab.cancelPending.test.tsx`)
tests.

## Architecture and release scope

Architecture and implementation/release checklist:
`backend/docs/checkout-admission.md`.

Line-Count-Exception: backend/routers/payment.py | 1789 -> 1809 | Keep
this 20-line safety expansion in the existing checkout/reactivation
boundary; extracting unrelated payment routes would broaden this billing
fix and its regression surface.


This PR does not deploy, flip flags, repair customer data, cancel
subscriptions, deduplicate historical purchases or serialize concurrent
first-time checkout requests. Accounts missing both stored subscription
ID and customer ID remain outside this bounded repair. Keep #21869 open
pending separately authorized rollout and affected-account verification.

GCP deployment verification is not claimed. Prior browser attempts could
not list Cloud Run resources, and no usable ADC/read-only profile was
found then. This code-only task performs no deployment or
serving-revision verification.

## Product invariants affected

none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/22552?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/22552?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F22552&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-off-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-off-auto-fix-light.svg"><img
alt="Turn off auto-fix"
src="https://www.cubic.dev/buttons/turn-off-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->




## 2026-10-23 maintainer review and merge gates

Ready for code review at Aryan's request; pushed 5d2f03f. The
checkout-vs-upgrade mapping and earlier stacked-test reversals have
already been repaired on this head. Fixed the remaining Flutter
conflict-message localization using the existing l10n tool across every
current locale (49 at verification). Both purchase surfaces select the
localized string from checkout HTTP 409; the upgrade
pending-cancellation message is unchanged. Fourteen focused Dart tests
pass, including English, German and Arabic on both surfaces; the two
isolated backend checkout/promotion files pass 55 tests. Localization
checks and all 60 selected preflight checks pass. The push used the
documented PRE_PUSH_SKIP_DESKTOP_SWIFT=1 hatch for an unchanged native
subtree under local memory pressure; git verified no macOS source
changes since the preceding remote head. Exact-head CI remains
authoritative for that compile. The prospective merge also preserves the
five previously repaired regression files. No actual Stripe/Firestore
writes or customer repair were performed. Stripe sandbox pass on
5d2f03f (2026-10-23, test mode only): the real checkout and
customer-portal routes ran against a Stripe sandbox with real
subscriptions, in-memory Firestore rows only. 10/10 scenarios behaved as
specified: new buyer gets a session; an active subscription is refused
with no session created (400 from the existing eligibility check when
the customer ID is known, the new 409 when it was lost locally); pending
cancellation on the same plan reactivates without checkout, including
when the local row is missing; a different plan stays blocked; canceled
and deleted subscription IDs get a fresh session; unverifiable Stripe
state returns 503 with no session; the billing portal opens. Exact-head
CI is green. Installed-client check (2026-10-23): the Flutter dev build
of 5d2f03f on the iOS Simulator, signed in as the synthetic local-dev
user against a local backend using the same Stripe sandbox, showed "You
already have a subscription. Manage your current subscription instead of
starting a new one." for a stale record whose Stripe subscription was
incomplete (the read-heal only promotes active/trialing, so this is the
state that reaches checkout from the app). No Checkout Session was
created. Still required before merge: maintainer review.

The first exact-head Linux helper packaging attempt failed while
downloading Ubuntu runtime packages: the dependency-install step timed
out at five minutes, before helper smoke execution. No application error
was shown by that failure. Re-ran only that failed job once; the retry
is not counted as a pass until it completes. No pipeline timeout,
dependency pin or security gate was weakened.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants