Skip to content

test(sync): legacy import ratchet and enrichment outbox contracts - #22390

Closed
Git-on-my-level wants to merge 4 commits into
mainfrom
lane/impl-c1-legacy-ratchet
Closed

Git-on-my-level wants to merge 4 commits into
mainfrom
lane/impl-c1-legacy-ratchet

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

PR C1 of plan C (legacy sync consolidation into the batch pipeline): two guards that later moves and deletions must keep green. Tests only. Nothing changes at runtime.

1. Legacy import ratchet (tests/unit/test_sync_legacy_import_ratchet.py + tests/unit/fixtures/sync_legacy_import_baseline.json)

  • Freezes the import edges into the 19 legacy sync modules scheduled for retirement (sequencer, legacy redrive/dead letters, legacy_fresh, WAL trims, legacy empty-ASR recovery, pipeline.py).
  • Importers are every backend/**/*.py except tests/, utils/sync/, routers/sync.py and the retiring modules themselves. Function-local imports, relative imports and literal importlib.import_module calls all count.
  • A new edge fails the test. A baseline edge that has disappeared also fails, so the baseline only shrinks. Each edge carries a reviewed why.
  • Today's baseline has 10 edges:
    • pipeline: 4 (batch enrichment.py, plus 3 harness apps)
    • sync_backfill_sequencer: 2 (operator scripts)
    • uid_sequencer: 1 (operator script)
    • sync_dead_letters: 1 (database/sync_jobs.py)
    • backfill_order: 1 (utils/cloud_tasks.py)
    • staged_prefetch: 1 (utils/other/storage.py)
  • Deletion PRs C10 and C11 must take these edge lists to zero.
  • Named test_sync_* so the existing utils/sync / routers/sync area selector picks it up.

2. Enrichment outbox contracts (tests/integration/test_enrichment_outbox_contract_emulator.py)

Runs against a real Firestore emulator and today's utils/sync/reprocess.py. Only the Cloud Tasks client leaf is captured. 16 cases:

  • First-summary dispatch: the wake's schedule_at is no later than first_pending_at + 120s, despite the 600s settle window and an over-configured deadline. Appends never extend it. Without the policy, the trailing settle window applies.
  • Coalescing: five marks produce one document, one wake and one run. Keys are per (owner, conversation).
  • Stale-token refusal: unknown, rotated (deferred) and replayed tokens never run work. The batch adapter rejects malformed bindings.
  • Lease expiry: a crashed worker's lease (1800s, or 120s for a first summary) answers busy and blocks the sweep. After expiry, the sweep re-wakes the row under a new token and the old token goes stale. A lost enqueue ack is repaired by the sweep.
  • Custody transfer: a merged donor's debt moves to the canonical row with the earliest acceptance and deadline, and the donor's token goes stale.
  • Privacy fence: a user-deleted conversation, a blocked privacy generation or an account-deletion marker discards the row without running work, and a late redelivery returns stale. Invalid redirect topology (a cycle) keeps the debt.

Test plan

  • cd backend && nice -n 19 .venv/bin/python -m pytest tests/unit/test_sync_legacy_import_ratchet.py: 22 passed.
  • Emulator: started cloud-firestore-emulator-v1.22.0.jar on loopback 127.0.0.1:18573, then ran FIRESTORE_EMULATOR_HOST=127.0.0.1:18573 PROVIDER_MODE=offline nice -n 19 .venv/bin/python -m pytest -m integration tests/integration/test_enrichment_outbox_contract_emulator.py tests/integration/test_sync_reprocess_emulator.py tests/integration/test_sync_enrichment_custody_emulator.py.
    • Result: 35 passed, run twice against the same emulator state. The 16 new cases pass alongside the 19 existing reprocess and custody cases.
  • No cloud credentials or production data were used.

Notes

  • tests/integration/ is not part of selector auto-discovery, and the Backend Emulator Proofs workflow runs only scripts/run-emulator-proofs.sh. CI therefore does not run the new emulator file, just as it does not run the existing test_sync_reprocess_emulator.py. Wiring tests/integration/*_emulator.py into that workflow is a separate change and is deliberately not in this tests-only PR.
  • The plan named the unit file test_legacy_sync_import_ratchet.py. It is renamed test_sync_legacy_import_ratchet.py so that existing selection covers it.
  • This PR touches no file edited by any open PR.

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

@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-19T23:46:17.256490Z ff6be00 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: f0b32bbf28

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

@Git-on-my-level

Copy link
Copy Markdown
Member Author

CI: the 3 red checks (Backend unit shard 1/6, shard 4/6, suite) are pre-existing on main. test_pipeline_characterization goldens (empty_asr_terminal / privacy_fence_midflight / provider_failure_quarantine) and test_pipeline_sim_scenarios::test_provider_exhaustion_turns_empty_asr_into_paid_recovery_and_a_quarantine_tail fail identically in main's run 39200781257 at this PR's base b553997. This tests-only PR does not touch them. The full suite ran because the new tests/integration file sits outside selector discovery. The new ratchet passed 24/24 in CI.

@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: 385757b367

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

@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: f8c36534c5

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

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor run — review feedback addressed (head bbdfe54b1c → f8c36534c5)

All four Codex review threads on this PR were fixed in one tests-only commit:

Thread Fix
Hoist integration-test imports (P1) All function-local imports in tests/integration/test_enrichment_outbox_contract_emulator.py moved to module scope (AGENTS.md import rules)
Delete dormant receipts during teardown (P2) outbox fixture now deletes outbox rows by document key for every conversation id the module touches (dormant receipts clear uid, so the uid-query teardown missed them) and removes the synthetic users/{uid}/conversations documents (Firestore parent deletes leave subcollections)
Detect keyword-form import_module calls (P2) Detector inspects name= keyword; parametrized cases added (keyword literal detected, non-literal ignored)
Run the ratchet for every importer in its declared scope (P2) New shared scope predicate tests/support/sync_legacy_ratchet_scope.py wired into scripts/select_backend_unit_tests.py (SYNC_LEGACY_RATCHET_TESTS), mirroring the background-task ratchet selection; the ratchet imports its exclusion constants from the support module and new contract tests pin the selector predicate to the ratchet's scope. A change under e.g. backend/utils/apps now selects test_sync_legacy_import_ratchet.py on changed-file CI

The rebased baseline also gained the reviewed upstream edge scripts/cap_hold_durability_emulator_test.py → utils.sync.pipeline (cap-hold durability proof introduced on main after this branch's original base).

Verification: targeted files green through the repo runner (BACKEND_UNIT_TEST_FILE_LIST=… bash test.sh: 94/13/37 passed, including the ratchet's new cases); selector proof for the utils/apps scenario; black (120) clean; full bounded pre-push gate passed before the push. CI on f8c36534c5: 57/57 checks completed, no failures.

@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: 68c9099f8d

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

Git-on-my-level and others added 3 commits October 20, 2026 06:06
Plan C (legacy sync consolidation) PR C1. Tests only; no runtime change.

- tests/unit/test_sync_legacy_import_ratchet.py + fixtures/sync_legacy_import_baseline.json:
  freezes the 10 current importers (outside utils/sync and routers/sync.py) of the
  19 legacy sync modules scheduled for retirement; new edges fail, stale edges must
  be removed, every edge carries a reviewed "why".
- tests/integration/test_enrichment_outbox_contract_emulator.py: Firestore-emulator
  contracts for the sync enrichment outbox that the utils/enrichment move must keep:
  first-summary wake within 120s, coalescing, stale-token refusal, lease expiry
  repaired by the sweep, redirect custody transfer and the privacy fence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ure teardown

- Ratchet now runs for every in-scope importer on changed-file CI, not only
  the post-merge --all run: new shared scope predicate
  (tests/support/sync_legacy_ratchet_scope.py) wires the selector the same
  way the background-task ratchet is wired, so an importer under e.g.
  backend/utils/apps selects test_sync_legacy_import_ratchet.py. Contract
  tests pin the predicate against the ratchet's own scope.
- import_module detection also accepts the keyword form
  (name='utils.sync.pipeline'); non-literal names still detect nothing.
- Enrichment outbox emulator fixture deletes dormant receipts and synthetic
  conversation documents by key on teardown (uid is cleared on dormant rows,
  so the uid-query teardown misses them; parent deletes keep subcollections).
- All function-local imports in the integration test hoisted to module
  scope (backend AGENTS.md import rules).
- Baseline gains the reviewed upstream edge
  scripts/cap_hold_durability_emulator_test.py -> utils.sync.pipeline
  (rebased onto main that introduced cap-hold durability).
…elector tuple

- import_module detection now resolves aliases bound by
  'from importlib import import_module as load'; calls through the alias
  with a literal module name are dynamic-import edges. Non-importlib
  aliases with the same call shape still detect nothing (parametrized).
- The ratchet no longer excludes the whole utils/sync/ package: only the
  retiring modules themselves and routers/sync.py are out of scope, so
  surviving in-tree callers (cap-hold core, recording_session_target)
  are scanned and their legacy edges are frozen in the baseline with
  reviewed whys. These are exactly the edges C11 (#22635, keep the
  cap-hold core) must cut; the shared selector predicate keeps its
  cheap superset and still defers narrow area selection to AREA_TESTS.
- SYNC_LEGACY_RATCHET_TESTS now selects only the ratchet itself.
  test_workflow_contracts.py has no legacy-ratchet assertions; it keeps
  its own selection via workflow contract sources and backend/testing/
  full-run prefixes, instead of riding every backend-Python selection.
@Git-on-my-level
Git-on-my-level force-pushed the lane/impl-c1-legacy-ratchet branch from 68c9099 to a383e00 Compare October 19, 2026 23:10

@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: a383e00bf0

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

…targets, fence/IO contracts

- Dynamic-import detection now requires proven importlib bindings: attribute
  receivers bound by 'import importlib [as imp]' and bare names bound by
  'from importlib import import_module [as load]'. An unrelated
  obj.import_module(...) or a local function named import_module no longer
  fabricates a legacy edge and fails changed-file CI (V8).
- Relative import_module targets ('.pipeline', package='utils.sync') resolve
  against the literal package argument — positional or keyword — with each
  leading dot beyond the first trimming the package, mirroring the
  interpreter. A relative name without a literal package detects nothing (-s).
- Privacy-fence contract now exercises the race it names: phase 1 keeps the
  pre-blocked discard (entry fence), phase 2 lands the block between the
  entry fence and the claimed callback and proves the adapter's inner
  discard_blocked discards without ever invoking work; blocks are cleared
  between phases so each parametrized block path is really driven (-z).
- Malformed-binding rejection now proves 'before any IO': the Firestore
  client accessor is replaced with a fail-fast mock for both the adapter and
  the outbox, so any pre-validation read/write fails the test (WB).
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor run — review feedback addressed (head f8c36534c5 → ff6be004b0, rebased onto current main)

All seven Codex review threads on this PR were fixed in two tests-only commits. No runtime code changes.

Round 1 (a383e00bf0, includes rebase onto latest main):

Thread Fix
Resolve aliased import_module calls (P2) Detector resolves aliases bound by from importlib import import_module as load
Scan surviving modules inside utils/sync (P2) Scope now excludes only the retiring modules and routers/sync.py; baseline gained 6 reviewed survivor edges (cap-hold core, cap_recovery_audio, recording_session_target, minimal_redrive from main #22503) — exactly the edges C10/C11 must cut
Limit the cross-cutting selector set to the ratchet (P2) SYNC_LEGACY_RATCHET_TESTS is now just the ratchet; test_workflow_contracts.py keeps its own declared selection

Round 2 (ff6be004b0, fresh threads from the re-review):

Thread Fix
Bind dynamic-import calls to proven importlib bindings (P2) Only import importlib [as imp] receivers and from importlib import import_module [as load] names count; obj.import_module(...) and local functions no longer fabricate edges
Resolve relative import_module targets (P2) ('.pipeline', package='utils.sync') resolves against the literal package (positional or keyword), interpreter dot semantics
Exercise the post-claim privacy fence (P2) Fence test phase 2 lands the block between the entry fence and the claimed callback; the adapter's inner discard_blocked must discard without running work, across all three block kinds
Assert malformed bindings do not reach Firestore (P2) Fail-fast mock on the client accessor for both adapter and outbox; both malformed deliveries raise ValueError with zero client accessions

Verification: ratchet + selector contracts green through the repo runner (50/50 locally, includes baseline ratchet-vs-tree consistency); black (120) clean; integration file byte-compiled and flow-verified statically (no local Java/emulator). CI on ff6be004b0: all backend unit shards, guardrails and suite pass; no failed checks; all seven threads replied and resolved.

@Git-on-my-level
Git-on-my-level marked this pull request as draft November 4, 2026 07:01
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 4, 2026 07:27

@cubic-dev-ai cubic-dev-ai 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.

4 issues found across 5 files

Confidence score: 3/5

  • sync_legacy_import_baseline.json omits the existing empty_recovery_intent.py importer, so the new ratchet test fails on the current tree. Reconcile the baseline with that importer before relying on the ratchet.
  • select_backend_unit_tests.py can run the legacy-sync ratchet for unrelated repo-level Python changes because it accepts both repo-relative and backend-relative paths. Normalize the path handling so unrelated changes don’t trigger it.
  • sync_legacy_ratchet_scope.py says retiring modules are excluded, but the predicate only excludes routers/sync.py; the AREA_TESTS claim also doesn’t hold for database/.... Align the docstring and predicate with the intended scope.
  • test_enrichment_outbox_contract_emulator.py says only the Cloud Tasks client leaf is replaced, but the fixture also stubs reprocess._wake_exists. Update the docstring or stub utils.cloud_tasks.named_task_exists instead.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/tests/unit/fixtures/sync_legacy_import_baseline.json">

<violation number="1" location="backend/tests/unit/fixtures/sync_legacy_import_baseline.json:19">
P2: This baseline omits the existing `utils/sync/empty_recovery_intent.py` importer, so the new ratchet test fails immediately on the current tree. Add that importer with a reviewed rationale, or remove the import before landing.</violation>
</file>

<file name="backend/scripts/select_backend_unit_tests.py">

<violation number="1" location="backend/scripts/select_backend_unit_tests.py:580">
P3: This hook runs the backend legacy-sync ratchet for unrelated repo-level Python changes. `changed_paths` contains repo-relative paths, but `is_sync_legacy_ratchet_path` also accepts backend-relative paths and therefore treats files such as `scripts/*.py` as in scope; require `path.startswith('backend/')` before calling the predicate.</violation>
</file>

<file name="backend/tests/support/sync_legacy_ratchet_scope.py">

<violation number="1" location="backend/tests/support/sync_legacy_ratchet_scope.py:34">
P3: This docstring says retiring modules are excluded here, but the predicate only excludes `routers/sync.py`. Retiring modules are selected by the predicate itself, and the `AREA_TESTS` claim does not hold for `database/sync_*.py`. Reword to state that only `routers/sync.py` is excluded and that retiring modules select the ratchet directly.</violation>
</file>

<file name="backend/tests/integration/test_enrichment_outbox_contract_emulator.py">

<violation number="1" location="backend/tests/integration/test_enrichment_outbox_contract_emulator.py:19">
P3: The docstring says only the Cloud Tasks client leaf is replaced, but the fixture also stubs `reprocess._wake_exists`. Either narrow the docstring to name that stub, or stub `utils.cloud_tasks.named_task_exists` instead so the sweep's wake probe is still exercised.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

},
"database.sync_empty_recovery": {
"retire_in": "C11",
"importers": {}

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: This baseline omits the existing utils/sync/empty_recovery_intent.py importer, so the new ratchet test fails immediately on the current tree. Add that importer with a reviewed rationale, or remove the import before landing.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/fixtures/sync_legacy_import_baseline.json, line 19:

<comment>This baseline omits the existing `utils/sync/empty_recovery_intent.py` importer, so the new ratchet test fails immediately on the current tree. Add that importer with a reviewed rationale, or remove the import before landing.</comment>

<file context>
@@ -0,0 +1,108 @@
+    },
+    "database.sync_empty_recovery": {
+      "retire_in": "C11",
+      "importers": {}
+    },
+    "database.sync_redrive": {
</file context>

selected.update(test for test in FIRESTORE_INDEX_GUARD_TESTS if test in all_tests)
if any(is_background_task_ratchet_path(path) for path in changed_paths):
selected.update(test for test in BACKGROUND_TASK_RATCHET_TESTS if test in all_tests)
if any(is_sync_legacy_ratchet_path(path) for path in changed_paths):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This hook runs the backend legacy-sync ratchet for unrelated repo-level Python changes. changed_paths contains repo-relative paths, but is_sync_legacy_ratchet_path also accepts backend-relative paths and therefore treats files such as scripts/*.py as in scope; require path.startswith('backend/') before calling the predicate.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/select_backend_unit_tests.py, line 580:

<comment>This hook runs the backend legacy-sync ratchet for unrelated repo-level Python changes. `changed_paths` contains repo-relative paths, but `is_sync_legacy_ratchet_path` also accepts backend-relative paths and therefore treats files such as `scripts/*.py` as in scope; require `path.startswith('backend/')` before calling the predicate.</comment>

<file context>
@@ -565,6 +577,8 @@ def tests_for_changed_paths(changed_paths: list[str], all_tests: list[str]) -> t
         selected.update(test for test in FIRESTORE_INDEX_GUARD_TESTS if test in all_tests)
     if any(is_background_task_ratchet_path(path) for path in changed_paths):
         selected.update(test for test in BACKGROUND_TASK_RATCHET_TESTS if test in all_tests)
+    if any(is_sync_legacy_ratchet_path(path) for path in changed_paths):
+        selected.update(test for test in SYNC_LEGACY_RATCHET_TESTS if test in all_tests)
     backend_paths = [path for path in changed_paths if is_selectable_backend_path(path)]
</file context>
Suggested change
if any(is_sync_legacy_ratchet_path(path) for path in changed_paths):
if any(path.startswith('backend/') and is_sync_legacy_ratchet_path(path) for path in changed_paths):

ratchet's exclusions are mirrored so ``tests/`` edits and
environment/cache trees do not widen a narrow selection; the ratchet test
pins these constants against its own so the two scopes cannot drift
apart. Retiring modules and ``routers/sync.py`` are excluded for edge

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This docstring says retiring modules are excluded here, but the predicate only excludes routers/sync.py. Retiring modules are selected by the predicate itself, and the AREA_TESTS claim does not hold for database/sync_*.py. Reword to state that only routers/sync.py is excluded and that retiring modules select the ratchet directly.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/support/sync_legacy_ratchet_scope.py, line 34:

<comment>This docstring says retiring modules are excluded here, but the predicate only excludes `routers/sync.py`. Retiring modules are selected by the predicate itself, and the `AREA_TESTS` claim does not hold for `database/sync_*.py`. Reword to state that only `routers/sync.py` is excluded and that retiring modules select the ratchet directly.</comment>

<file context>
@@ -0,0 +1,47 @@
+    ratchet's exclusions are mirrored so ``tests/`` edits and
+    environment/cache trees do not widen a narrow selection; the ratchet test
+    pins these constants against its own so the two scopes cannot drift
+    apart. Retiring modules and ``routers/sync.py`` are excluded for edge
+    purposes, but they still select the ratchet through the ``utils/sync`` /
+    ``routers/sync`` AREA_TESTS mapping (``test_sync_*``).
</file context>

6. privacy fence: a deleted conversation or blocked owner discards the row
without running work; invalid redirect topology keeps the debt.

Only the Cloud Tasks client leaf is replaced (captured in memory). Run under a

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The docstring says only the Cloud Tasks client leaf is replaced, but the fixture also stubs reprocess._wake_exists. Either narrow the docstring to name that stub, or stub utils.cloud_tasks.named_task_exists instead so the sweep's wake probe is still exercised.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/integration/test_enrichment_outbox_contract_emulator.py, line 19:

<comment>The docstring says only the Cloud Tasks client leaf is replaced, but the fixture also stubs `reprocess._wake_exists`. Either narrow the docstring to name that stub, or stub `utils.cloud_tasks.named_task_exists` instead so the sweep's wake probe is still exercised.</comment>

<file context>
@@ -0,0 +1,405 @@
+6. privacy fence: a deleted conversation or blocked owner discards the row
+   without running work; invalid redirect topology keeps the debt.
+
+Only the Cloud Tasks client leaf is replaced (captured in memory). Run under a
+loopback Firestore emulator, for example::
+
</file context>

Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
# Conflicts:
#	backend/scripts/select_backend_unit_tests.py
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
…ed tree

The ratchet fixture arrived from #22390 with a baseline ~4.5k commits stale:
main gained nine importers of the retiring legacy sync modules (staging
syncsplit proof, backfill worker control/job, empty-success guard, watch
recovery e2e, capture coverage lanes) and lost two baseline edges
(enrichment callback, cap_recovery_audio coverage replay). Regenerated with
the ratchet's own --write pass, then reviewed each edge's why against the
retire milestones (C10/C11).
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Folded into survivor #24591 (lane/lcinv, pushed head b8e0b1e0b3). As part of consolidating the open PR batch, origin/main and every other listed PR were merged into the survivor branch; all tests were kept. This PR is being closed as folded — its content lives on in #24591.

Carried: test_sync_legacy_import_ratchet.py, sync_legacy_ratchet_scope.py, the selector wiring (unioned with the survivor lifecycle routes in select_backend_unit_tests.py), and test_enrichment_outbox_contract_emulator.py. The ratchet baseline fixture was ~4.5k commits stale against the folded tree (main had gained nine legacy-sync importers and lost two baseline edges); it was regenerated with the ratchet's own --write pass and each new edge given a reviewed why with its C10/C11 retirement fate (commit b8e0b1e0b3). All 50 tests in the file pass.

@github-actions

github-actions Bot commented Nov 4, 2026

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!

Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
* test(backend): catch main up to the TTS rate-limit rename and retired task wake

#15171 renamed the offloaded rate-limit call to
redis_db.check_tts_rate_limit_for_user but left the desktop TTS unit
stub and its identity assertion on the old function name, and #20665
retired routers.action_items._wake_task_changes while the shared-task
503 regression still patched it. Both files failed on origin/main and
blocked every backend unit shard. Align the stub and assertion with the
renamed call and drop the stale wake patch.

* test(listen): guard lag-probe wiring and /metrics exposition

Prod listen pods showed no omi_listen_event_loop_lag_seconds series. The
code path is correct: every listen deployment runs an image older than
#22397 (backend:8d7778a is its parent), while Cloud Run backend runs
4f43b2d, which contains it. Pin the two links the D0b gate depends on:
run_listen_session starts the probe before building the runtime, and the
listen /metrics handler renders the histogram from import. Document the
image-tag check for a missing series.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(listen): tie exposition test to the route wiring; fix frame-histogram doc

Grok review on #22608: the exposition test did not use the listen route
import, and the doc said every loop histogram renders from import, which
is false for the codec-labelled frame histogram. Assert the route ->
runtime -> probe module chain and the import-time registry collector, and
document that the frame series appears only after the first timed frame.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(listen): frame histogram child appears at receive-loop entry, not first frame

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(listen): exercise the deployed app's /metrics exposition in a fresh process

Codex review: the exposition test imported routers.listen.runtime itself
and called the metrics handler directly, so it kept passing if main.py
stopped registering metrics.router, and its zero-count check only asserted
the series name after earlier tests in the same file had already
incremented the process-global histogram.

Run the assertion path in a fresh interpreter instead: install the
hermetic network blocker, import main (the deployed listen entrypoint per
backend/Dockerfile CMD), make an unauthenticated request (401) and an
authenticated one (200) through the real app routing, and assert the exact
import-time 'omi_listen_event_loop_lag_seconds_count 0.0' with no probe
started before or after serving. Subprocess CPU is not charged to the
fast-unit duration guard, and the network blocker proves the path stays
hermetic for the no-Redis CI lane.

Failure-Class: none

* test(sync): legacy import ratchet and enrichment outbox contracts

Plan C (legacy sync consolidation) PR C1. Tests only; no runtime change.

- tests/unit/test_sync_legacy_import_ratchet.py + fixtures/sync_legacy_import_baseline.json:
  freezes the 10 current importers (outside utils/sync and routers/sync.py) of the
  19 legacy sync modules scheduled for retirement; new edges fail, stale edges must
  be removed, every edge carries a reviewed "why".
- tests/integration/test_enrichment_outbox_contract_emulator.py: Firestore-emulator
  contracts for the sync enrichment outbox that the utils/enrichment move must keep:
  first-summary wake within 120s, coalescing, stale-token refusal, lease expiry
  repaired by the sweep, redirect custody transfer and the privacy fence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(sync): address review — selector coverage, keyword imports, fixture teardown

- Ratchet now runs for every in-scope importer on changed-file CI, not only
  the post-merge --all run: new shared scope predicate
  (tests/support/sync_legacy_ratchet_scope.py) wires the selector the same
  way the background-task ratchet is wired, so an importer under e.g.
  backend/utils/apps selects test_sync_legacy_import_ratchet.py. Contract
  tests pin the predicate against the ratchet's own scope.
- import_module detection also accepts the keyword form
  (name='utils.sync.pipeline'); non-literal names still detect nothing.
- Enrichment outbox emulator fixture deletes dormant receipts and synthetic
  conversation documents by key on teardown (uid is cleared on dormant rows,
  so the uid-query teardown misses them; parent deletes keep subcollections).
- All function-local imports in the integration test hoisted to module
  scope (backend AGENTS.md import rules).
- Baseline gains the reviewed upstream edge
  scripts/cap_hold_durability_emulator_test.py -> utils.sync.pipeline
  (rebased onto main that introduced cap-hold durability).

* test(sync): address review — aliased import_module, survivor scope, selector tuple

- import_module detection now resolves aliases bound by
  'from importlib import import_module as load'; calls through the alias
  with a literal module name are dynamic-import edges. Non-importlib
  aliases with the same call shape still detect nothing (parametrized).
- The ratchet no longer excludes the whole utils/sync/ package: only the
  retiring modules themselves and routers/sync.py are out of scope, so
  surviving in-tree callers (cap-hold core, recording_session_target)
  are scanned and their legacy edges are frozen in the baseline with
  reviewed whys. These are exactly the edges C11 (#22635, keep the
  cap-hold core) must cut; the shared selector predicate keeps its
  cheap superset and still defers narrow area selection to AREA_TESTS.
- SYNC_LEGACY_RATCHET_TESTS now selects only the ratchet itself.
  test_workflow_contracts.py has no legacy-ratchet assertions; it keeps
  its own selection via workflow contract sources and backend/testing/
  full-run prefixes, instead of riding every backend-Python selection.

* test(listen): keep the child's network guard referenced for its whole body

Codex review: 'block_outbound_network().__enter__()' drops the only
reference to the _GeneratorContextManager, so CPython finalizes it (and
its finally block restores the socket functions) before 'import main'
runs — the hermetic claim was inert, and an environment supplying Stripe
credentials could turn the import into real network calls. Enter the
guard through an ExitStack held for the entire child body.

Failure-Class: none

* test(sync): address review — proven import_module bindings, relative targets, fence/IO contracts

- Dynamic-import detection now requires proven importlib bindings: attribute
  receivers bound by 'import importlib [as imp]' and bare names bound by
  'from importlib import import_module [as load]'. An unrelated
  obj.import_module(...) or a local function named import_module no longer
  fabricates a legacy edge and fails changed-file CI (V8).
- Relative import_module targets ('.pipeline', package='utils.sync') resolve
  against the literal package argument — positional or keyword — with each
  leading dot beyond the first trimming the package, mirroring the
  interpreter. A relative name without a literal package detects nothing (-s).
- Privacy-fence contract now exercises the race it names: phase 1 keeps the
  pre-blocked discard (entry fence), phase 2 lands the block between the
  entry fence and the claimed callback and proves the adapter's inner
  discard_blocked discards without ever invoking work; blocks are cleared
  between phases so each parametrized block path is really driven (-z).
- Malformed-binding rejection now proves 'before any IO': the Firestore
  client accessor is replaced with a fail-fast mock for both the adapter and
  the outbox, so any pre-validation read/write fails the test (WB).

* test(jobstore): port recovery discovery and progress parity invariants

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): carry recovery custody invariants across job stores

Failure-Class: FC-empty-asr-without-context-recovery

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): pin recap fixture to a reproducible admission time

The unmodified main test fails five assertions before noon because its fixture and recap selection use different dates. Pass one explicit afternoon instant through the existing production input seam; keep every assertion and production behavior unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): port recovery and admission parity invariants

Carry PL-057, PL-072 and PL-086 through the shared Store matrix. Keep the new-store cancellation gap strict and linked to issue #23761.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(mobile-perf): upload-success window, sparse scoring, semantics knob; tag lag stalls with work in flight

- --upload accept --upload-wals N appends wal_sync_upload_success: synthetic
  uploads and jobs drive real sync phases, persistence and reconcile.
- cold_start, home_idle_sync_refresh and the upload window are sparse: cold
  readiness keeps the 15% spread gate and each run has a stall budget (<=2
  stalls over 100 ms, <=500 ms). Dense windows keep 15% p90; no run dropped.
- Semantics is off for heavy perf by default; --semantics on is a separate
  dataset and compare refuses mixed settings.
- LagWorkRegistry: bounded, allocation-free begin/end; mobile_lag_stall
  records overlapping sync/upload/reconcile/WAL-load work.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(mobile-perf): dry-run tests pass an explicit artifact root

Without one, device_run.main() exits 2 on hosts with no scratch mount, so
the manifest check failed on ordinary Linux checkouts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(jobstore): qualify fenced shard pulls across stores

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(jobstore): require available backends in the selected proof lane

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(outbox): preserve durable enqueue across wake failures (PL-042)

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(outbox): verify committed enqueue result identity

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): qualify partial-pull leases across store backends

Port PL-194 into the shared scheduler/Store matrix and existing emulator proof lane.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): qualify pending deletion across old and new stores

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): PL-049 positive-speech custody follows the one Soniox second chance

Main a866d27 (10-30) gives Modulate-empty held units with positive speech one independent Soniox
second chance. The PL-049 case written 10-26 asserted no second provider at all, so it failed on every
store after the merge. It now pins the new contract: the second chance is spent at most once across
repeated sweeps, and an uncertain call keeps audio, intent and custody held. Measured silence still
settles without any paid call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: qualify pull-batch parity across Firestore and Postgres

Preserve PL-321/322/323 at frame boundaries, buffered query overlays and bounded walk stops. Register the shared matrix in the existing emulator-proof runner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: clean coordination fixtures within their owned namespace

Include merge holds beside pull claims and prove cleanup preserves foreign namespaces and synthetic customer rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): enforce held-custody and no-spend recovery parity

Qualify PL-061, PL-105 and PL-363 on old Firestore, new Postgres
and the simulator through the existing Store harness.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): keep partial-custody identity distinct from producer outcomes

Use PL-396 for phone custody and leave PL-061 producer client_status
as a separate missing invariant in the parity ledger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): declare isolated stage and fence paid refusal markers

Make the conformance fixture independent of CI stage defaults and
reject paid-attempt metadata on a local no-spend refusal. Clarify
minimum CI stores versus all-store cutover qualification.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* style(firmware): match CI clang-format on the safe-mode snapshot initializer

CI's clang-format 18 attaches the compound-literal brace and drops the
space before it; break nothing else and keep the initializer alignment
one column left.

* test(backend): keep the enrichment proof clock a real clock

The consumer's heartbeat hold cap reads time.monotonic, so the injected
consumer clock must carry the full time module with only the wall-clock
pinned, or every PL-397 delivery dies on AttributeError before the
callback runs.

* style(firmware): drop the compound-literal brace space CI's clang-format rejects

CI formats firmware with clang-format 18, which attaches the brace after
the compound-literal cast; the local 23 kept a space and realigned one
column right, so the Formatting job failed on the merge preview. Commit
with clang-format 18 first on PATH so the pre-commit hook agrees.

* test(backend): inventory lifecycle writers and latch invariant gaps

* test(backend): re-baseline the legacy-sync import ratchet to the folded tree

The ratchet fixture arrived from #22390 with a baseline ~4.5k commits stale:
main gained nine importers of the retiring legacy sync modules (staging
syncsplit proof, backfill worker control/job, empty-success guard, watch
recovery e2e, capture coverage lanes) and lost two baseline edges
(enrichment callback, cap_recovery_audio coverage replay). Regenerated with
the ratchet's own --write pass, then reviewed each edge's why against the
retire milestones (C10/C11).

* test(backend): align partial-pull conformance with the current lease API

The PL-194 file predates two scheduler changes main landed since its base:

- The pull transaction now returns (receipts-or-None, eligible, observations)
  where each receipt is (lease, enqueued_at, relet); Scheduler.pull is what
  unwraps receipts into LeasedWork. The conformance helper treated
  result[0][0] as a lease, so its committed list held receipt tuples against
  pull's LeasedWork list, and aborted['lease'].item raised AttributeError.
  Unwrap receipts to the lease on both sides so the whole test speaks the
  one shape main's lease API returns.

- A multi-lease abort rolls back every receipt in its transaction, so the
  exact 'failing_lease - 1 committed' count only holds one lease per
  transaction; pin the documented BATCH_PULL_MULTI_LEASE_ENABLED kill
  switch (as the file already pins shard spread and cap dispatch).

- Shard-spread selection reads control_candidates (plural fanout), not the
  singular control_candidate the overlap test paused; hook both, each
  wrapping its own original, since the singular delegates to the plural.

All 24 partial-pull parametrizations plus both overlap cases pass on sim
and Postgres locally; emulator legs stay with CI's proofs job.

---------

Co-authored-by: David Zhang <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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