Skip to content

fix(sync): never strand backfill pending entries without an owner - #21755

Merged
Git-on-my-level merged 2 commits into
mainfrom
lane/orphan-owners
Oct 15, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
lane/orphan-owners

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Problem and root cause

Accepted backfill pending entries can outlive their sequencer owner and lose the fast owner-based recovery path. Source inspection of Train 1 (#21679, 2bec67dc) and this branch's base 1e4920a143cdcef7f8d5f7770f1f3b13933a9eaa found:

  • register_job writes pending work without creating an owner; duplicate admission also returns before repairing one. A crash or failed immediate kick leaves no owner to reconcile.
  • finish_job unconditionally deletes the owner with waiting jobs present. A lost post-completion kick leaves them ownerless.
  • retire_expired(epoch=...) also unconditionally deletes the dispatching owner with waiting jobs present. Concurrent admission cannot preserve an owner that it never writes. Waiting retirement deletes only the exact pending entry, so it does not cause the root deletion, but previously left an already missing owner unrepaired.
  • No retirement batch-delete path exists in these revisions; the deletes are exact transaction operations.

Evidence qualification: both revisions also contain a bounded due-pending scan, so missing owner documents alone do not prove permanent unreachability. The runbook declares 100 pending entries every two minutes (72,000/day); scanning an 889k backlog once would take about 12.3 days at that cap without direct kicks. This is a capacity calculation, not a live Scheduler measurement. The supplied incident still establishes a broken ownership invariant and stalled recovery.

Read-only production evidence supplied for 2026-10-15 ~18:20Z (not remeasured by this change): 20,000 pending entries across 775 UIDs; 137 UIDs (~18%) missing owners hold 3,045 sampled entries; fleet pending ~889k, with a rough ~130k stranded-entry projection; 712 owner documents total. The supplied David example has 508 pending entries, oldest accepted 2026-10-14 16:09Z, no owner, unchanged since 16:30Z. No additional user identifiers are included here.

Fix and durable prevention

Admission and duplicate admission use a shared transactional owner-creation primitive. Completion, active retirement, and last-pending retirement transactionally recheck pending presence. They clear active fields but retain the fencing epoch. Empty owners omit reconcile_at entirely and never occupy the hot range query; non-empty owners remain discoverable. Admission transactionally wakes a parked owner without resetting its epoch. Empty claims and stale deferral recheck current work before parking, so neither a new claim nor admission can be hidden by stale samples. Retaining one small epoch document per participating UID is intentional.

The existing bounded, rotating pending scan uses the same primitive to repair missing owners, rechecking pending presence and existing ownership in a transaction. Repairs receive a random reconcile_at from 1 second through a configurable window (default 30 minutes), plus the matching repair_not_before. Both normal claims and waiting retirement honor this deadline; the self-heal tick skips its immediate kick. The pending fallback therefore cannot bypass staggering. SYNC_BACKFILL_OWNER_REPAIR_WINDOW_SECONDS controls the shared window; the script accepts --repair-window-seconds. Repeated repair does not reschedule an existing owner. It emits event=sync_backfill_owner_repaired, increments sync_backfill_owner_repaired_total, and reports owner_repaired in sweep outcomes. Each UID gets one reconciliation attempt per tick across the two scans. Flag-off legacy dispatch now checks active ownership rather than document truthiness, so idle retained owners preserve direct-mode rollback behavior.

Why isn't this a shared primitive instead? It is: _ensure_owner creates/wakes owners for admission and repair; the scheduled sweep and operator script share the transactional repair helper. Release and parking share _release_owner after transactional presence checks. Admission reads owner before pending, matching claim/release/parking lock order. Behavioral tests cover those transitions; the emulator covers real contention and a stuck lease with 301 empty owners in a single sweep page. This incident adds FC-pending-queue-without-dispatch-owner and its behavioral prevention artifacts.

Failure-Class: new

Prepared repair procedure — NOT run

backend/scripts/repair_sync_backfill_owners.py defaults to dry-run, uses read-only transactions in that mode, projects only UID fields while paging by document ID, caps pending reads at --limit (default 1,000,000), and limits UID probes to 5/second by default (maximum 20). Apply is idempotent, transactionally rechecks pending presence, and spreads owners over the shared repair window (default 1,800 seconds; override with --repair-window-seconds). Output contains aggregate counts only, including failures; it never prints identities or exception payloads. It recreates owners only, without dispatching tasks or accessing Redis/audio/ledgers. Review the script before running it.

From backend/:

source ~/.local/bin/gcp-agent-env.sh ro-prod
OMI_ENV_STAGE=prod PYTHONPATH=. .venv/bin/python scripts/repair_sync_backfill_owners.py --project based-hardware --dry-run
# After operator review, select explicitly authorized write credentials outside the script.
OMI_ENV_STAGE=prod PYTHONPATH=. .venv/bin/python scripts/repair_sync_backfill_owners.py --project based-hardware --apply

Compare missing_owners, repaired_owners and errors; rerun dry-run after apply. The existing reconcile job discovers repaired owners after their staggered deadlines. Do not run apply before the corrected empty-owner exclusion and staggering are deployed. Counts are bounded scan observations, not a fleet snapshot. Full procedure: backend/docs/runbooks/sync-two-lane.md#backfill-owner-repair.

Validation

All tests ran through backend/test.sh, serial (BACKEND_PYTEST_WORKERS=1, BACKEND_PYTEST_XDIST=0) and prefixed with taskpolicy -b:

  • BACKEND_UNIT_TEST_FILE_LIST=<selected list> bash backend/test.sh: FIX-FIRST follow-up: sequencer/repair 76 passed; Firestore query shapes 472 passed (1 slow case deselected), outside-query contract 29 passed. Initial PR validation also passed sync Cloud Tasks (123 tests); the router is unchanged by this follow-up.
  • firebase emulators:exec --only firestore --project demo-sync-retirement --config <loopback-only config> "taskpolicy -b env BACKEND_PYTEST_MARK_EXPR=integration BACKEND_UNIT_TEST_FILE_LIST=<retirement integration file> BACKEND_PYTEST_WORKERS=1 BACKEND_PYTEST_XDIST=0 bash backend/test.sh": 20 passed. Java emulator limited to two active processors. Covers both admission/release transaction races, parking/admission contention, monotonic epochs, real missing-field exclusion with 301 empty owners and one expired dispatching/running lease, stagger-aware claims/deferral, duplicate admission repair, stale-scan/read-only behavior, real paginated dry-run/apply and idempotency.
  • git diff --check: passed. Follow-up metadata-only preflight: line-count, invariants and failure-class protocol passed. The history-dependent failure-class guard ratchet reported a shallow-clone skip; full-history CI/integration must enforce it. The final idle-owner router expression was also rerun through test.sh as a focused two-case regression: 2 passed.

The initial FIX-FIRST contention run timed out while admission used pending-before-owner reads; the final owner-first implementation passed all 20 emulator tests, including that race. Earlier marker-deselected runs are not counted. Repair code was exercised only with fakes and a loopback demo-project emulator; no operator repair command ran against production. No full local preflight is run in this lane under the explicit overloaded-machine instruction; the integration lead owns that run. No production checks or writes, repair invocation, merge, or deployment have been performed.

View guided diff Turn on auto-fix

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-15T19:14:58.011096Z b265c14 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: 5ffac1d90f

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

)
job_id = owner.get('active_job_id')
if not isinstance(job_id, str) or not job_id:
registry.defer_owner(uid, registry.HEARTBEAT_SECONDS, now=current)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Stop requeueing empty retained owners every heartbeat

Once more than 100 UIDs have completed backfills, every retained idle owner remains eligible for the owner scan forever because this path defers even an empty owner by only 120 seconds—the same interval as the Scheduler—while due_owners() processes at most 100 per tick. These no-work rows can therefore consume the bounded scan and delay reconciliation of an active reservation whose initial Cloud Tasks dispatch was lost; at 72,000 retained owners, a full pass already takes 24 hours, beyond the documented staged-job lifetime, and the pending scan cannot recover it because claiming removed its pending document. Preserve the owner/epoch, but remove empty owners from the heartbeat scan or defer them separately so active owners retain the intended five-minute recovery bound.

Useful? React with 👍 / 👎.

Comment thread backend/routers/sync.py
Comment on lines 1903 to +1904
await run_blocking(db_executor, sync_backfill_sequencer.has_pending, payload['uid'])
if legacy_job and legacy_job.get('status') == 'queued' and not sequencer_on and not owner
if legacy_job and legacy_job.get('status') == 'queued' and not sequencer_on and not owner_job_id

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Recheck ownership after the pending lookup

With the sequencer flag off, a queued legacy task can read an idle retained owner here, then race a concurrent kick() that atomically promotes the last pending entry into that owner and deletes the pending document. The subsequent has_pending() returns false, so line 1924 treats the legacy task as direct and starts it alongside the newly active sequenced job, violating the per-UID serialization guarantee. Determine active ownership and pending presence from one consistent transaction, or re-read the owner after a false pending result before allowing direct execution.

AGENTS.md reference: backend/AGENTS.md:L145-L145

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 8ad1d75 into main Oct 15, 2026
54 of 61 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/orphan-owners branch October 15, 2026 19:36
aryanorastar added a commit that referenced this pull request Oct 16, 2026
…io (#21829)

## What changed and why

Bound a ring-buffer download that becomes silent after READ_BEGIN or
DATA. The
initial five-second timeout was cancelled on BEGIN, leaving only a
30-minute
overall deadline. A connected, stalled read therefore kept the transfer
owner
busy instead of yielding to normal capture/retry orchestration.

- Reset a 15-second idle deadline on the first valid BEGIN and nonempty
DATA,
matching the existing legacy SD idle bound. Repeated BEGIN, empty DATA
and
  control chatter are not progress.
- Observe arrival before queued custody/disk work. On timeout, stop
admitting
notifications, send STOP on the original connection epoch, drain already
received bytes and flush complete records through the existing durable
WAL
owner. Do not acknowledge an unfinished source or advance an unproven
frontier.
- Cancel idle timers on completion/error and put read-command failures
through
the same cleanup. A valid DONE arrival cancels the radio idle deadline
even
while its validation waits behind custody I/O. Healthy DONE and existing
  custody capability gates remain.
- Make the ring custody fixtures wait for read/status admission rather
than
  fixed startup sleeps, keeping the original durable-advance assertions.
- Preserve the saved cause, original stack and phase when a read-command
  failure goes through cleanup; keep catch-and-continue behavior.

Related: #21279 (uploaded jobs queued/429), #21387 (merged polling
backoff),
#21319 (merged short-WAL batching), #21755 (merged backfill
dispatcher-owner
repair), #21823 (merged batch-worker quarantine), and #21362
(retained-upload
recovery). These are separate stages.
This PR does not close the customer case or assert that the reported 1.4
KB/s,
capture interruption, cloud worker state or missing recaps share this
cause.
No firmware version or diagnostic export was supplied for the Discord
0/127
report, and no production repair, storage deletion or deployment is
performed.

Why isn't this a shared primitive instead? The existing ring reader
already
owns read admission, STOP, notification ordering, durable flush and
frontier
validation. Its watchdog belongs inside that owner, not in a parallel
recovery
actor. The injectable timer tests the real owner without waiting 15
seconds.

## Product invariants affected

- INV-CAP-1 — complete received records still use existing durable
file/index
  registration. Timeout leaves the source pending and sends no unproven
advance. Legacy firmware may reclaim on BLE delivery before app
durability;
this does not repair or conceal that existing risk or promise recovery
of
  incomplete records.

## Verification

- Production ring-owner regression: 14 tests passed, including idle
BEGIN,
partial audio, ignored chatter, cancelled deadlines, healthy DONE and
bytes
queued behind a deliberately blocked custody check, with and without
DONE.
- Capture interruption/reconnect journey (`mobile-verify fast --paths
app/lib/services/wals/ring_storage_sync.dart`): 3 checks passed, no
skips.
- Full app analyzer ratchet: passed. `make preflight`: 25 checks passed.
- Broader ring/custody/capture regression suites: all 129 passed on the
final
code, including the diagnostic guard and the 14 ring-owner tests above.
- Diagnostic guard: confirmed red without the transfer failure's saved
error,
then green with its original stack, cause and phase preserved.
Changed-file
  analyzer: no issues found.
- Physical BLE throughput, microphone behavior, customer-account
processing
and released-app retest: not performed; require hardware/account
evidence.

Architecture and implementation/release checklist:
`app/docs/offline-sync-stall-recovery.md`. The listen/pusher pipeline
map is
updated. This needs a mobile release after merge, not a backend
deployment.

## UI evidence

UI-Evidence: none -- transfer lifecycle only; no UI, copy or layout
changes

## Failure class

Failure-Class: FC-sync-failure-records-drop-cause
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