Skip to content

fix(sync): keep job reads behind terminal ownership - #19379

Merged
kodjima33 merged 2 commits into
BasedHardware:mainfrom
aryanorastar:codex/sync-lifecycle-audit
Sep 27, 2026
Merged

kodjima33 merged 2 commits into
BasedHardware:mainfrom
aryanorastar:codex/sync-lifecycle-audit

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #19373. Reading an upload's status could turn a live worker's job into a failure or overwrite its completed result. get_sync_job() performed an unconditional stale-state Redis write before the authenticated status route could enforce its existing run-lease ownership checks.

This fixes the backend ownership boundary; it does not change mobile or hardware code.

What changed

  • Make get_sync_job a read-only lookup. A stale progress timestamp is not permission to publish a terminal result.
  • Keep stale Cloud Tasks recovery in the existing authenticated route: acquire the worker's run lease, re-read, and invoke the existing finalizer. Standby and active-ledger gates remain effective.
  • Consolidate the private raw reader into this single read-only primitive and migrate all four internal finalization callers.
  • Add HTTP regressions that compose the real route, Redis reader, lease operations, and finalizer. Only identity and storage are synthetic; the ownership policy is not mocked.
  • Add the behavioral guard to the sync workflow contract and the existing failure-class guard inventory, and document the read/recovery boundary.

Reproduction and verification

On unchanged main (ab7f480795), the initial five regressions all failed:

  1. A stale legacy job with an unexpired worker lease was changed to failed by a status poll.
  2. The same happened to an active/fenced job.
  3. A poll terminalized inline work instead of leaving it to its coordinator.
  4. A poll mutated a job even in standby mode.
  5. A deterministic interleaving completed the job after the reader's snapshot; the reader then overwrote the completed result with failure.

After the fix:

  • 12 HTTP/reader contract tests pass, including unmigrated jobs with no ledger-mode field and positive controls proving abandoned processing and never-started queued Cloud Tasks still recover with sync_worker_stale / sync_dispatch_lost.
  • 379 focused backend tests pass, file-isolated across status ownership, stale reads, corrupt blobs, v2 sync, Cloud Tasks, dead letters, lane policy, and backfill admission:
    BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-19373-tests.txt bash backend/test.sh.
  • bash backend/scripts/typecheck.sh: 0 errors (existing warnings remain).
  • Local Uvicorn + curl smoke on 127.0.0.1:10273 exercises the actual status endpoint: a lease-owned worker and inline worker remain processing; an abandoned worker and lost dispatch become reasoned failures through the finalizer; a completed job remains completed with its result. Fake Redis/identity only; outbound network blocked. No production requests, user recordings, or quota changes.
  • OMI_PR_BODY_FILE=/tmp/omi-19373-pr-body.md make preflight: 32 checks passed. The history-dependent failure-class recurrence check explicitly skips on this shallow checkout; CI's full history remains authoritative.

Why some existing tests change

The old database-reader tests explicitly expected blind read-side failure writes. That contradicts the existing ownership and inline-recovery contract in backend/docs/runbooks/sync-two-lane.md, and the already-present route checks. The route-only tests mocked get_sync_job, hiding the contradictory implementations. The new HTTP composition tests execute both, including the positive recovery cases, rather than merely rewriting expected status values.

Scope and limitations

  • No new queue, schema, deployment, provider call, TTL, or retry policy.
  • Inline recovery keeps the documented degraded path: the coordinator owns completion; retained audio is retryable after job/content-claim expiry. This does not promise ten-minute recovery of dead inline work.
  • Adjacent PR feat(sync): per-UID backfill sequencer with 202 admission #19362 adds a per-UID backfill sequencer and exempts its new dispatch mode from read-side mutation. It retains the bug for direct jobs. This PR fixes the shared reader, not the sequencer. That branch must rebase its raw-reader wrapper/callers onto the single read-only get_sync_job if this lands first.
  • Verified locally with synthetic storage and identity, not against deployed production or a physical recording device.

Product invariants affected

none — preserves the existing sync terminal-ownership contract; no locked product policy is changed.

Failure class

Failure-Class: FC-split-mutation-authority

The shared primitive is the read-only job lookup plus the already-existing lease-owning finalizer. The new behavioral guard composes those production paths; no source-string checker or competing recovery owner is added.

Review in cubic

Reproduce five live-reader failures, including completed-result clobbering. Keep lookups read-only and let the existing run-lease finalizer own recovery. The real-route regression matrix preserves legacy, active, inline, standby and abandoned-task semantics.

Verified: 379 focused backend tests; 0 pyright errors; local Uvicorn + curl with fake Redis and outbound network blocked; 32 repository preflight checks.

Refs BasedHardware#19373

Failure-Class: FC-split-mutation-authority
@Git-on-my-level

Copy link
Copy Markdown
Member

Verified the ownership violation this fixes: on main, get_sync_job() in backend/database/sync_jobs.py performed an unconditional stale-state Redis write (status=failed + dead-letter pending + r.set) on every read and for every dispatch mode, before the authenticated route could enforce anything. The reader could fail a job whose worker still held an unexpired run lease and overwrite a concurrently written 'completed' result. The fix direction is correct and well-executed.

File-by-file:

  • backend/database/sync_jobs.py — get_sync_job is now a pure read (json parse of _as_redis_text, no mutation); _read_raw_sync_job is consolidated into it and the four finalization callers (finalize_sync_job, _fenced_finalize_sync_job, mark_job_failed, fenced_mark_job_failed) are migrated with identical read semantics. I checked routers/sync.py get_sync_job_status at this head: the lease-owned stale-recovery branch (acquire lock, re-read, standby/active fence gates, fenced finalizer, SyncJobRunLeaseLost handling) is intact, so abandoned cloud_tasks jobs still recover with sync_worker_stale / sync_dispatch_lost. I also checked the only other production caller, backend/utils/sync/pipeline.py (~line 2030), which reads partial_result mid-run and never depended on the self-heal.
  • backend/tests/unit/test_sync_status_read_ownership.py (new) — this is the strongest part of the PR: HTTP-level tests through the real route with fakeredis and the real reader, parametrized over fence modes, including a lease-held poll that must not mutate, a standby-fence poll, a deterministic interleaving where a worker completes after the reader's snapshot, and positive controls proving abandoned processing/queued cloud_tasks jobs still finalize through the owned path. Only identity/storage are synthetic, as the description claims.
  • backend/tests/unit/test_sync_job_stale_self_heal.py and backend/tests/unit/test_sync_v2.py — expectations inverted to the new read-only contract (status preserved, no Redis set); consistent with the code.
  • backend/tests/unit/test_sync_dead_letters.py — the renamed poll test now models a live worker by stubbing try_acquire_job_run_lock to return None and asserts the job stays 'processing' with no dead-letter publish and no inflight-slot release; the stale-read test asserts zero Redis calls. Both match the new semantics.
  • backend/docs/listen_pusher_pipeline.mdx and backend/docs/runbooks/sync-two-lane.md — the new 'Offline upload status ownership' section and runbook paragraph accurately describe the behavior I verified in the route; no aspirational claims found.
  • backend/testing/workflow_contracts.json and .github/failure-classes/FC-split-mutation-authority.json — register the new test in the sync workflow contract and the mutation-authority guard inventory; appropriate.

One product/ops tradeoff for a maintainer to sign off on: with the read-side self-heal gone, a dead inline coordinator's job stays 'processing' until the 24h job TTL / client WAL reconcile instead of healing in ~10 minutes on poll. That reverses the dispatch-agnostic self-heal added on 2026-07-23 for the 'Uploaded - processing on Omi for 12+ hours' reports (#10033). The runbook already frames inline recovery as a deliberately degraded durable-retry path (lease renewal is not a terminal-write fence, executor leaves can outlive coordinator cancellation), so this looks intentional and the correctness argument is sound — but the recovery-latency change for inline workers deserves an explicit maintainer decision, so I'm leaving this for human review rather than sign-off.

Housekeeping: the branch currently conflicts with main (#19362 and #19421 both touched backend/database/sync_jobs.py after this head) — a rebase will be needed before merge, and the migrated callers are worth re-checking against the new sequencer code after it.

Thanks @aryanorastar — the issue report (#19373) with failing-on-main regressions and the ownership-preserving test design made this a very reviewable change.

[AI-generated review posted on behalf of the maintainers]

@Git-on-my-level Git-on-my-level added backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge labels Sep 27, 2026
…audit

# Conflicts:
#	backend/database/sync_jobs.py
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Conflicts resolved on 099f6ae00c — merge of current main (23 commits). Back to MERGEABLE.

One file conflicted, backend/database/sync_jobs.py, and it collided with this PR's central change, so I read both sides before touching it.

What the two sides were doing

Since this branch's base, main landed #19362 (per-UID backfill sequencer). It kept get_sync_job's read-side stale write, but exempted dispatch_mode == 'sequenced' jobs from it and added get_raw_sync_job / sync_job_run_lock_present for the sequencer.

That is a subset of this PR's fix, not an alternative to it. Regressions #1 and #5 in the description — a live legacy worker marked failed, and a completed result overwritten — are both legacy direct-dispatch jobs, which main's exemption leaves exposed. So get_sync_job takes this PR's read-only version outright: no write, for any dispatch mode.

main's get_raw_sync_job and sync_job_run_lock_present are kept verbatim.

A resolution I tried first and reverted

get_raw_sync_job becomes behaviourally identical to the now read-only get_sync_job, and this PR's stated design is a single read-only primitive. So I first consolidated: removed get_raw_sync_job and migrated its callers.

That broke test_sync_task_persistence_fence_terminalizes_backfill_and_releases_its_slot — it passes on pristine main, returned sequenced_legacy_job instead of superseded after my change. The cause is instructive: the shared fixture mocks get_sync_job with a side_effect sequence of exactly three reads. main's legacy-migration check calls get_raw_sync_job, so it never consumed from that sequence. Renaming it to get_sync_job made it consume admitted_job first, fire the migration branch, and shift every later read by one.

That was the signal I had over-reached: consolidating #19362's brand-new reader rewires its read accounting, which is refactoring someone else's fresh work inside a merge. The four main-only files I had touched (routers/sync.py, utils/sync/uid_sequencer.py, test_sync_cloud_tasks.py, test_sync_backfill_uid_sequencer.py) are restored to main's exact bytes, and the one line I had renamed inside test_sync_dead_letters.py is reverted — matched by surrounding context, since the same call already appears a few lines later for an unrelated reason.

Worth a follow-up: there are now two read-only readers with identical behaviour. Collapsing them is the right end state, but it wants its own PR that updates the sequencer fixtures deliberately rather than as merge fallout.

Verified on the merged head

check result
every test_sync_* suite 952 passed, 0 failed
test_sync_status_read_ownership (this PR's regressions) 12 passed
test_sync_job_stale_self_heal 4 passed
test_sync_cloud_tasks 101 passed (the one that broke)
test_sync_backfill_uid_sequencer (#19362) 13 passed
bash backend/scripts/typecheck.sh 0 errors

Diff scope is the PR's own 9-file list, byte-for-byte — checked by diffing the merged file list against the PR's.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

The reader consolidation mentioned above is now #19437, opened as a draft stacked on this PR.

It removes get_raw_sync_job / _read_raw_sync_job once this PR has made get_sync_job read-only — the two are AST-identical modulo a local variable name at that point. The one fixture that needed care is fixed deliberately rather than with a sentinel: the persistence-fence test now pins its scenario to the legacy direct path (sequencer disabled, no owner, nothing pending) instead of relying on an auto-mock to skip the migration branch. 952 sync tests pass there.

Nothing on this branch changes; merging this PR first is what unblocks #19437.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

The housekeeping item in the review above is done — it was written against cd6b2c1c3c, before the merge on 099f6ae00c.

The recovery-latency tradeoff for a dead inline coordinator is untouched and still the maintainer's call; nothing in the merge changes it.

@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.

Confirmed the read-side stale-write race is still live on main (get_sync_job unconditionally flips processing->failed on read); this PR makes it read-only and moves recovery behind the lease-owning finalizer. 379 backend tests + new HTTP ownership regressions, CI green. Trusted contributor, confidence 5/5. Merging.

@kodjima33
kodjima33 merged commit 336b1af into BasedHardware:main Sep 27, 2026
40 checks passed
aryanorastar added a commit that referenced this pull request Oct 5, 2026
…job (#19437)

* fix(sync): keep job reads behind terminal ownership

Reproduce five live-reader failures, including completed-result clobbering. Keep lookups read-only and let the existing run-lease finalizer own recovery. The real-route regression matrix preserves legacy, active, inline, standby and abandoned-task semantics.

Verified: 379 focused backend tests; 0 pyright errors; local Uvicorn + curl with fake Redis and outbound network blocked; 32 repository preflight checks.

Refs #19373

Failure-Class: FC-split-mutation-authority

* refactor(sync): collapse the two read-only job readers into get_sync_job

Stacked on #19379. Once that change makes get_sync_job read-only, main's
get_raw_sync_job (added by #19362 for the per-UID sequencer) is the same
function: both read the job key, return None on a missing, corrupt or non-dict
blob, and write nothing. Checked structurally rather than by eye -- the two
bodies are AST-identical modulo the local variable name. Two copies of one
read-only primitive is exactly how read-side mutation creeps back into one of
them, so this keeps a single reader.

- database/sync_jobs.py: remove get_raw_sync_job and _read_raw_sync_job.
- routers/sync.py, utils/sync/uid_sequencer.py: point the five callers at
  get_sync_job and drop the now-duplicate import name.
- Tests that patched the removed name now patch get_sync_job.

One fixture needed a deliberate change rather than a rename.
test_sync_task_persistence_fence_terminalizes_backfill_and_releases_its_slot
runs a backfill task with no sequencer epoch, which first reads its own job to
decide whether the UID sequencer should adopt it. Its harness stubs the whole
database.sync_jobs module with a bare MagicMock, so before this change that read
returned an auto-mock whose status never equalled 'queued' and the migration
branch was skipped by accident. After consolidation the read consumes from the
test's explicit get_sync_job sequence, sees the real 'queued' job, and migrates.

Rather than feed it a sentinel, the test now states its scenario: the legacy
direct path with the sequencer disabled, no owner and nothing pending, and the
migration read gets its own entry ahead of the processor's three. Flipping the
sequencer on makes the test fail, so the gate is load-bearing rather than
decorative.

Verified: every test_sync_* suite, 952 passed and 0 failed; typecheck 0 errors.
No behaviour change.

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

* fix(sync): finish consolidating read-only job lookup

---------

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

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sync status reads can fail a live worker and overwrite completed results

3 participants