Repository navigation
fix(sync): re-home stranded legacy_final_pass_v1 owners to batch once legacy is draining/dark (P46, lead b209a5) - #23129
Conversation
…s draining/dark After legacy sync leaves 'on', a conversation still routed to legacy_final_pass_v1 answers every later upload with the in-progress 409 and the phone keeps that audio for good (M3 Luna review; lead ruling b209a5). utils/sync/final_pass_rehome moves the owner to batch_sync_v1 with the same revision-fenced claim_record_lane_owner CAS every owner transition uses, when no live legacy job holds the uid (the Redis pending index; unknown holds), and the upload is admitted through the unchanged batch intake, so its privacy, binding and predecessor fences apply. A held re-home (a live legacy job, a lost CAS) keeps today's in-progress ACK and the client retries; promote_final_pass_if_current already refuses a batch owner, so a final pass still running cannot promote over batch's work. Wired at both routing points: registered_record_response (the router passes the mode it already read) and batch intake's own legacy_final_pass_v1 branch (the no-owner-discovery dark path). scripts/legacy_dark/final_pass_rehome sweeps the pre-flip stock (dry run by default; a ledger probe stands in for Redis) and is the evidence for the legacy_final_pass_rehomed draining precondition; it needs the new conversations.record_lane_owner collection-group field index (registry and the regenerated manifest). 'on' is today's path byte for byte.
…dark M3 re-review (Luna), forwarded by the lead: both writers of legacy_final_pass_v1 minted new owners without reading legacy_sync, so the re-home gate could be passed and new stranded owners created afterwards. - transcription_shadow._claim_shadow_owner: outside 'on' an unowned conversation gets no claim and no final pass (it stays unowned for batch admission to claim); an owner that already exists keeps its pass until the next upload re-homes it. - live_upload: the ownerless-upload claim for a narrowed uid (batch policy off) takes batch_sync_v1 outside 'on' instead of legacy_final_pass_v1; intake widens such an upload onto batch anyway. The mode is read only when the policy would otherwise pick legacy; a caller's mode is used as is.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ 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".
| tier = os.environ.get('GCP_AGENT_TIER', 'unknown') | ||
| if args.apply and tier.startswith('ro-'): | ||
| print(f'--apply needs an operator tier, not {tier}', file=sys.stderr) | ||
| return 2 |
There was a problem hiding this comment.
Require the operator tier for the selected environment
When --apply is used, this check rejects only tiers beginning with ro-, so an unset tier (unknown), dev-operator targeting --env prod, or prod-operator targeting staging can perform the owner rewrites whenever the ambient ADC has access. Because re-homing changes which production pipeline receives subsequent uploads, require the exact environment-specific operator tier before constructing the client, as the other rollout tooling does.
Useful? React with 👍 / 👎.
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | ||
| parser.add_argument('--env', choices=sorted(ENVIRONMENTS), required=True) | ||
| parser.add_argument('--apply', action='store_true', help='write the owner change (default: dry run)') | ||
| parser.add_argument('--limit', type=int, default=0, help='stop after this many conversations (0: all)') |
There was a problem hiding this comment.
Prevent limited sweeps from reporting CLEAR
When an operator supplies --limit N and the first N matching conversations are successfully re-homed, remaining_stranded becomes zero and the command reports CLEAR even if additional matching conversations were excluded by the query limit. Since CLEAR is documented as evidence for the draining precondition, a bounded diagnostic run can incorrectly authorize the transition; limited runs need to remain non-clear unless exhaustion is established, for example by fetching one extra result.
Useful? React with 👍 / 👎.
| from database.sync_jobs import pending_sync_jobs | ||
|
|
||
| return len(pending_sync_jobs(uid)) |
There was a problem hiding this comment.
Avoid treating the best-effort pending index as a safety lease
When a legacy job is created but its pending-index zadd fails transiently, create_sync_job deliberately catches that failure and leaves the live job stored without an index entry; the index is also truncated to the newest 100 jobs. Once Redis is readable again, pending_sync_jobs(uid) can therefore return an empty list even though an unindexed queued or processing legacy job still exists, causing this helper to transfer the conversation to batch while that legacy job may still write it. The re-home fence needs a durable/exhaustive ownership check rather than interpreting this best-effort UI index's empty result as zero live work.
Useful? React with 👍 / 👎.
| from utils.sync import final_pass_rehome | ||
|
|
||
| rehome = await run_blocking(db_executor, final_pass_rehome.rehome_final_pass_owner, uid, conversation_id) |
There was a problem hiding this comment.
Re-home through the intake store's data-plane client
When this fallback branch runs on a split-project deployment such as dev desktop-backend, batch_artifact_authorize has just loaded target through the store's data-plane client, but rehome_final_pass_owner is called without that client and therefore falls back to get_firestore_client(), whose ADC may point at the compute project. The helper then sees the conversation as missing (or writes the wrong database), returns NOT_APPLICABLE, and every affected upload remains on the 409 path despite the real data-plane row being eligible; pass the same data-plane client used by the store, as the router-side re-home already does.
AGENTS.md reference: backend/AGENTS.md:L26-L26
Useful? React with 👍 / 👎.
…nd never clears a capped scan Luna round 1 on #23129: - P1 stale mode: a request that read 'on' just before the flip can still create a legacy job after it, invisible to the live-job probe until created, while a draining request re-homes the same conversation. upload_rehome now holds until the ramp document is FLIP_GRACE_SECONDS (300) old (legacy_dark.mode_age_seconds; unknown holds): every such request is long over, so the probe sees every boundary job before any re-home. Both upload call sites go through upload_rehome. - P1 stale sweep cache: the sweep runs at 'on' beside live legacy admission, so the ledger probe is read fresh per conversation and any ledger row created in the last QUIET_SECONDS (600) holds the uid as well. - P2 false CLEAR: a --limit run that reached its cap reports PARTIAL (exit 1), never CLEAR.
…e sweep only once admission is quiesced Luna round 2 on #23129 (both P1s share one root: the re-home was not serialized with legacy job creation, and the 300s grace was not a hard bound): - The router re-reads the legacy mode before creating a legacy job when its first read is older than legacy_dark.ADMISSION_REVALIDATE_SECONDS (60). With the 30s ramp cache no stale 'on' creates a legacy job later than 90s after a flip, so the 300s flip grace on upload re-homes is enforced, not assumed (asserted: grace > revalidate + cache TTL). - The sweep's --apply refuses 'on' and the grace: it runs only when the ramp serves draining/dark and is past FLIP_GRACE_SECONDS (served_ramp reads the env entry like ramp_set --show). There legacy admission is quiesced, so the per-uid ledger probe cannot race a new legacy job. A dry run at 'on' sizes the stock; the runbook and the legacy_final_pass_rehomed text say so. - P2: the quiet-window count holds a uid only for recent LEGACY ledger rows; batch_v1 and stt_cap_hold_v1 rows no longer keep active users uncleared.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 753601193a
ℹ️ 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".
| if legacy_allowed and time.monotonic() - legacy_mode_read_at > legacy_dark.ADMISSION_REVALIDATE_SECONDS: | ||
| # A legacy job is created only on a young mode read: a request that read 'on' | ||
| # and then stalled (a long batch decode, a slow fallback) must not carry it past | ||
| # a draining re-home of the same conversation (final_pass_rehome's flip grace). | ||
| legacy_mode = await run_blocking(db_executor, legacy_dark.current_mode) | ||
| legacy_allowed = legacy_dark.legacy_admission_allowed(legacy_mode) |
There was a problem hiding this comment.
Refuse legacy admission when the ramp reread is stale
When a process read on before the flip and subsequent ramp refreshes fail, this reread still returns on from runtime_percent's last-known-good cache indefinitely. The operator sweep assumes no stale on request can create a job after the 300-second grace, so it may re-home the conversation while such a request has not yet created its ledger row; that request can then create a legacy job after the owner has moved to batch, allowing legacy and batch work to write the same conversation concurrently. Revalidation needs proof of a fresh ramp snapshot, or must refuse legacy admission once the served snapshot is stale.
Useful? React with 👍 / 👎.
| if status == 'retryable' or ownership is legacy_dark.LegacyOwnership.ACTIVE: | ||
| live += 1 |
There was a problem hiding this comment.
Stop treating released retryable claims as live jobs
When a legacy job fails, _release_claim_transaction marks its ledger row retryable and deletes the job_id, so that row explicitly has no live writer. This probe nevertheless counts every retryable row forever, regardless of age; because ledger rows are retained for 45 days, any inactive user with both an old failed upload and a stranded final-pass owner remains HELD, preventing the required sweep from ever reporting CLEAR until expiry or another upload happens. Once admission is quiesced, only an actual processing claim or a row within the quiet window needs to block re-homing.
Useful? React with 👍 / 👎.
| # Once legacy sync is draining/dark no new legacy final-pass owner (and no new | ||
| # final pass) may start: the conversation stays unowned for batch admission to | ||
| # claim (M3 re-review; final_pass_rehome moves the owners that already exist). | ||
| if not _legacy_final_pass_allowed(): | ||
| return None |
There was a problem hiding this comment.
Update the owning listen/pusher pipeline document
This changes the conversation lifecycle and audio-upload ownership contract by suppressing new final passes outside on and introducing a legacy-to-batch owner transition, but backend/docs/listen_pusher_pipeline.mdx is unchanged. That document is the required owner for audio, transcription, and conversation-lifecycle changes, so it needs to describe the new mode fence and re-home path in this change.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
| legacy job for the uid, a lost CAS) keeps the LEGACY route: the router's fence | ||
| answers the shipped in-progress ACK and the client retries. | ||
| """ | ||
| from utils.sync import final_pass_rehome |
There was a problem hiding this comment.
Move the new backend imports to module scope
This adds a function-local import for final_pass_rehome, with the same pattern added in the other new helpers and sweep functions. Backend modules require imports at module scope rather than inside functions; move these imports to the module headers and adjust any test seams without relying on lazy function imports.
AGENTS.md reference: backend/AGENTS.md:L161-L169
Useful? React with 👍 / 👎.
| if refusal: | ||
| print(f'--apply refused: {refusal}', file=sys.stderr) | ||
| return 2 | ||
| result = sweep(client, apply=args.apply, limit=args.limit) |
There was a problem hiding this comment.
Abort the sweep if legacy mode changes
When --apply starts in draining or dark but the lead performs the documented one-write rollback to on while this potentially long collection-group sweep is running, the script never checks the ramp again. New legacy admissions can then resume between a per-UID zero-job probe and the owner CAS, allowing the sweep to transfer a conversation to batch while the newly admitted legacy job can still write it. Bind the sweep to the observed ramp revision/mode or revalidate it before destructive writes.
Useful? React with 👍 / 👎.
|
Hey @Git-on-my-level 👋 Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request. After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:
Before your next PR, please skim:
If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing. Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out. Thank you for being part of the Omi community! |
What changed and why
Retargeted to
mainafter M3 (#22427) merged (lead ruling c7d947: merging into integration first would have re-gated M3's staging check); the branch's base c13818a is contained in main's merge commit, and main's line counts for the two declared files match the exceptions below.After legacy sync goes
draining/dark, a conversation whoserecord_lane_owneris stilllegacy_final_pass_v1routes LEGACY, no legacy job may be created, and every later upload for it is answered with the in-progress 409 (router fence and batch intake alike), so the phone keeps that WAL audio for good (M3 Luna review, verified by lane 1; lead ruling b209a5 made the re-home a gate for the draining/dark step). This PR is the re-home:utils/sync/final_pass_rehome.pymoves the owner tobatch_sync_v1with the same revision-fencedclaim_record_lane_ownerCAS every owner transition uses, when no live legacy job holds the uid, and the upload is then admitted through the unchanged batch intake. It is wired at both routing points,registered_record_response(the route the router follows; it now receives the mode the router already read) and intake's ownlegacy_final_pass_v1branch (the no-owner-discovery dark path). A held re-home keeps today's ACK, so the client retries.scripts/legacy_dark/final_pass_rehome.pysweeps the pre-flip stock (dry run by default) and is the evidence for thelegacy_final_pass_rehomedprecondition; it needs the newconversations.record_lane_ownercollection-group field index (registry + regenerated manifest). Prod stayson: nothing here runs atonexcept the explicit operator sweep.Is the state reachable? Yes, three ways, all from code on integration:
live_upload.registered_record_responseclaimslegacy_final_pass_v1for an ownerless conversation's first WAL upload whenever the uid's batch policy is not enabled (the batch ramp before 100%, and owner-load narrowing after). Every such conversation keeps that owner; its later WAL segments (a late tail, a reconnect after a long offline period, a retry) route LEGACY.transcription_shadow._claim_shadow_ownerclaims it before the final pass transcribes. The pass is an in-process background task with no durable retry (maybe_start_shadow->start_background_task; an exception only logsoutcome=failed), and nothing clears the owner on completion or death:_write_processing_resultpreservesrecord_lane_owner, and no code path pops it. A completed or dead final pass leaves the owner on the conversation forever.The M2 staging cycle did not exercise this state:
omi_legacy_dark_ack_totalrose by 0 duringdark(no legacy-owned content was re-uploaded) because the m2reh3/m2reh4 replay conversations were batch-routed, so the 244/244 zero-lost result neither covers nor contradicts it. The lane 1 M3 verification states the 409 behaviour in both call sites. Sizing the prod stock needs the new index (final_pass_rehome --env proddry run onro-prodafterreconcile_firestore_indexes.py --provision-missing); once this deploys,omi_legacy_dark_ack_total{reason="legacy_final_pass_rehomed"}is the live count.No new owner after the gate (M3 re-review scope add, forwarded by the lead). Both writers of
legacy_final_pass_v1minted owners without readinglegacy_sync, so the re-home gate could be passed and new stranded owners created afterwards. Second commit:transcription_shadow._claim_shadow_owneroutsideonmakes no claim and starts no pass for an unowned conversation (it stays unowned for batch admission to claim; an owner that already exists keeps its pass until the next upload re-homes it), andlive_upload's ownerless-upload claim for a narrowed uid (batch policy off) takesbatch_sync_v1outsideon(intake widens such an upload onto batch anyway); the mode is read only when the policy would otherwise pick legacy.Luna round 2 (FIX-FIRST, the round cap) and the fixes, fourth commit. Both P1s share one root: the re-home was not serialized with legacy job creation, and the 300 s grace was assumed, not enforced.
onoutliving the grace: the router now re-reads the legacy mode before creating a legacy job whenever its first read is older thanlegacy_dark.ADMISSION_REVALIDATE_SECONDS(60 s). With the 30 s ramp cache no staleoncan create a legacy job later than 90 s after a flip, so the 300 s grace on upload re-homes is a hard bound with margin (asserted by test: grace > revalidate + cache TTL). The re-read is a cached, off-loop read;ongains no write.on: the sweep cannot serialize with an in-flight legacy upload from an operator shell, so its--applynow refusesonand the grace, and runs only when the ramp servesdraining/darkat least 300 s past its last write (served_rampreads the env entry asramp_set --showdoes). There legacy admission is quiesced (no new legacy job can start beside the sweep), the per-uid ledger probe is exact for what remains, and the upload path re-homes anything still held later. A dry run atonsizes the stock. This changes what thelegacy_final_pass_rehomeddraining precondition can mean (it is confirmed on leavingonwhen the re-home serves on every revision and the dry run has sized the stock; the sweep is applied indrainingand must readCLEARbeforedark): the ramp_controller text and the runbook (on→draininganddraining→dark) say so. Lead ruling requested on the bus; the gate id andramp_setmechanics are unchanged.batch_v1andstt_cap_hold_v1rows no longer keep active users uncleared.apply_refusaloveron/ unknown / inside the grace / draining at the grace / dark;served_rampparsing;main --applyatonrefuses before touching a conversation; recent batch and cap-hold rows do not hold a uid.Luna round 1 (FIX-FIRST) and the fixes, third commit.
onjust before the flip can still create a legacy job after it, invisible to the live-job probe until created, while a draining request re-homes the same conversation.upload_rehomenow holds until the ramp document isFLIP_GRACE_SECONDS(300) old (legacy_dark.mode_age_seconds; an unknown age holds); every such request is long over by then (the mode is read once per request from a 30s cache), so the probe sees every boundary job before any re-home. Both upload call sites go throughupload_rehome.onbeside live legacy admission, so its ledger probe is read fresh for every conversation (no per-uid cache) and any ledger row created in the lastQUIET_SECONDS(600) holds the uid as well.--limit: a capped scan reportsPARTIAL(exit 1), neverCLEAR.mode_age_secondsparsing and fail-closed, intake receives the mode throughupload_rehome, the probe is fresh (a job that starts mid-sweep is seen) and counts recent rows, a capped sweep is PARTIAL.Fences kept.
legacy_owner_job_presentdoes).promote_final_pass_if_currentrefuses a batch-owned conversation, so a final pass still running when the owner moves cannot promote over batch's work (newrehomedfence case).is_soft_deleted) or a deleting account (account_deletions) gets no new route; admission then runs the unchanged intake privacy authorization. An unowned row is admission's to claim, never this helper's.accept_batch_upload->admitpath after the owner change; the helper writes onlyrecord_lane_owner.already_batchwith no probe and no write; the second upload after a re-home followsbatch_sync_v1directly.onis today's path byte for byte:upload_rehomeis inert aton, intake returns its legacy receipt aton, and the route does no read, probe or write there.Product invariants affected
none. No path in this PR is listed on a locked invariant. In spirit it serves INV-CAP-1 (retained pendant audio now gets a serving owner instead of an indefinite hold); nothing here discards audio.
How it was verified
Repository
BasedHardware/omi, branchlr/46-rehomeonorigin/integration/legacy-retirec13818a, worktree/Volumes/Ephemeral/scratch/worktrees/omi/lr46-rehome. Layer: backend unit tests only; no staging or prod run, no live service touched.BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=<list> bash backend/test.shunderomi-heavy/nice -n 19:test_final_pass_rehome,test_batch_provider_stt,test_legacy_dark_router,test_final_pass_promotion,test_legacy_dark,test_record_admission_review_fixes,test_firestore_indexes,test_ramp_controller,test_reason_label_enums): 8 files green;test_final_pass_rehomefailed 6 (test harness: explicitOMI_ENV_STAGE, live admission for the no-loaded-owner route), fixed, then 28/28.test_batch_pipeline_intake,test_mobile_standard_batch,test_sync_cloud_tasks,test_transcription_shadow,test_batch_ramp,test_cap_hold_batch_admission,test_batch_audio_language,test_legacy_dark_lost_recordings,test_sync_v2,test_speaker_audio): 590 passed.test_final_pass_rehome36/36, andtest_record_admission_review_fixes,test_transcription_shadow,test_batch_provider_stt,test_mobile_standard_batch,test_sync_v2green (the existing shadow-claim tests pass unchanged aton).scripts/pr-preflight --lane local --base origin/integration/legacy-retireon the first commit: 35 checks passed (index guard, line-count ratchet with the two exceptions below, failure-class protocol, dead-code ratchet, import purity, route baseline); the pre-push pyright phase passed on the push.python3 backend/scripts/generate_firestore_indexes.py --write: the manifest gains only theconversations.record_lane_ownerfield override (test_firestore_indexesgreen).Tests
tests/unit/test_final_pass_rehome.py(new): the loop closed (test_dark_upload_for_a_stranded_final_pass_owner_no_longer_loops: first upload re-homes and routes BATCH, second follows the batch owner, one CAS), the live-job hold (1, 3, unavailable), batch-owner idempotency with no probe or write, unowned/missing/deleted/deleting-account left alone, the lost-CAS race (one attempt, held or follows a batch winner, no ack), dry run stops before the CAS,oninert, the mode read off the loop when the caller has none, the Redis probe fails closed, the sweep (outcome counts and CLEAR verdict, dry run never writes, the ledger probe counts ACTIVE and retryable legacy rows once per uid and fails closed,--applyrefuses a read-only tier), and the scope add (an ownerless upload for a narrowed uid claims batch outsideonand legacy atonwith no mode read; the shadow final pass takes no new owner and starts no pass outsideon, with live admission on or off, keeps an existing legacy owner's pass, and claims as before aton).tests/unit/test_batch_provider_stt.py: intake re-homes then admits (rehomed,already_batch), a held re-home keeps the in-progress ACK with no batch unit,onkeeps the legacy receipt.tests/unit/test_legacy_dark_router.py: a re-homed BATCH route in draining/dark reaches batch intake with batch enabled, never the fence or a legacy job, and the router hands its mode to the route; the held case keeps lane 1's ACK test.tests/unit/test_final_pass_promotion.py:rehomedfence, the race with a still-live final pass from the promotion side.UI evidence
UI-Evidence: none -- backend only.
Line-count exception
Line-Count-Exception: backend/routers/sync.py | 3966 -> 3977 | The router hands the legacy mode it already read to the record route (one kwarg plus its comment) and re-reads a mode older than ADMISSION_REVALIDATE_SECONDS before creating a legacy job (review round 2); the re-home itself lives in utils/sync/final_pass_rehome.py and utils/batch_pipeline/live_upload.py, and C11 deletes the legacy runner from this file.
Line-Count-Exception: backend/database/firestore_index_registry.py | 2200 -> 2206 | One FieldIndexRequirement row for the conversations.record_lane_owner collection-group index, in the registry every declared index must live in (the lost-recordings census index landed the same way).
Failure class (fixes)
The legacy-dark switch (
legacy_sync=draining/dark) was inert for exactly the conversations it needed to move: leftover flag-on state (thelegacy_final_pass_v1owner) kept routing new uploads into the gated legacy path, which could no longer serve them. The fix branches on the mode before following that owner, re-homes the leftover state so new work takes the ungated batch path, and pins it with tests that set the mode off while the leftover owner is present.Failure-Class: FC-kill-switch-keeps-the-gated-path