Repository navigation
feat(sync): add backfill pull cohort with live task fallback (S3) - #24412
Conversation
There was a problem hiding this comment.
6 issues found across 39 files
Confidence score: 3/5
- In
deployment.yaml, an emptyGOOGLE_APPLICATION_CREDENTIALSvalue may make google-auth try to open an empty file and prevent authentication. Avoid setting the variable when no credentials file is configured. - In
worker_runtime.py, a transient heartbeat RPC failure can makeexecuteexit and SIGKILL a healthy child. Catch and log transient RPC errors; treat onlyaccepted: Falseas lease loss. - In
test_sync_worker_runtime.py, the assertion does not verify thattick()passes the lease returned by the claim. Useassert_awaited_once_withto check the exact lease. - In
test_sync_worker_execution.py, the lease-loss and crash tests use real subprocesses and sleeps despite the README classifying these as non-unit tests. Mark them@pytest.mark.slowor move them to the slow manifest lane.
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/test_sync_worker_runtime.py">
<violation number="1" location="backend/tests/unit/test_sync_worker_runtime.py:71">
P3: This assertion does not verify the handoff. Use `assert_awaited_once_with` to pin the exact lease the claim returned, so the test fails if `tick()` passes the wrong value.</violation>
</file>
<file name="backend/utils/sync/pipeline.py">
<violation number="1" location="backend/utils/sync/pipeline.py:2576">
P3: The rename leaves two runbook docs citing the old `_run_full_pipeline_background_async` name, so the lifetime inventory no longer matches the code. Update `sync-request-lifetime-inventory.md` and `diarizer-batch-cohort.md` to `run_full_pipeline_background_async`.</violation>
</file>
<file name="backend/charts/sync-backfill-worker/templates/deployment.yaml">
<violation number="1" location="backend/charts/sync-backfill-worker/templates/deployment.yaml:40">
P1: Setting `GOOGLE_APPLICATION_CREDENTIALS` to an empty string may break Application Default Credentials. google-auth checks this variable with `is not None` and tries to open it as a file, so `""` likely raises instead of falling through to Workload Identity. Drop this env entry and make sure the runtime secret does not carry the key, or pop the variable in `worker_job.bootstrap` before any ADC call.</violation>
</file>
<file name="backend/utils/sync/worker_runtime.py">
<violation number="1" location="backend/utils/sync/worker_runtime.py:67">
P2: A single failed heartbeat RPC raises out of `execute`, and the `finally` block SIGKILLs a healthy child. Only an explicit `accepted: False` should count as lease loss. Catch and log transient RPC errors here, and retry on the next heartbeat interval.</violation>
</file>
<file name="backend/tests/unit/test_sync_worker_execution.py">
<violation number="1" location="backend/tests/unit/test_sync_worker_execution.py:29">
P3: These lease-loss and crash tests spawn real subprocesses and rely on real sleeps, which the backend test README classifies as non-unit. Mark them `@pytest.mark.slow` (or move them to the slow manifest lane) so the PR lane does not run them as hermetic unit tests.</violation>
<violation number="2" location="backend/tests/unit/test_sync_worker_execution.py:94">
P3: The `execution` fixture imports its modules inside the function body. Move these imports to the module top, as AGENTS.md requires, so the patch targets are visible at module scope.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| # The full runtime contract supplies data/provider secrets, while | ||
| # the attached Workload Identity remains the only Google identity. | ||
| - {name: SERVICE_ACCOUNT_JSON, value: ""} | ||
| - {name: GOOGLE_APPLICATION_CREDENTIALS, value: ""} |
There was a problem hiding this comment.
P1: Setting GOOGLE_APPLICATION_CREDENTIALS to an empty string may break Application Default Credentials. google-auth checks this variable with is not None and tries to open it as a file, so "" likely raises instead of falling through to Workload Identity. Drop this env entry and make sure the runtime secret does not carry the key, or pop the variable in worker_job.bootstrap before any ADC call.
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/charts/sync-backfill-worker/templates/deployment.yaml, line 40:
<comment>Setting `GOOGLE_APPLICATION_CREDENTIALS` to an empty string may break Application Default Credentials. google-auth checks this variable with `is not None` and tries to open it as a file, so `""` likely raises instead of falling through to Workload Identity. Drop this env entry and make sure the runtime secret does not carry the key, or pop the variable in `worker_job.bootstrap` before any ADC call.</comment>
<file context>
@@ -34,6 +34,11 @@ spec:
+ # The full runtime contract supplies data/provider secrets, while
+ # the attached Workload Identity remains the only Google identity.
+ - {name: SERVICE_ACCOUNT_JSON, value: ""}
+ - {name: GOOGLE_APPLICATION_CREDENTIALS, value: ""}
+ - {name: FIREBASE_AUTH_CREDENTIALS_PATH, value: ""}
- {name: OMI_ENV_STAGE, value: prod}
</file context>
| 'epoch': payload['sequencer_epoch'], | ||
| 'token': lease['token'], | ||
| } | ||
| if not (await self.client.call('heartbeat', identity)).get('accepted'): |
There was a problem hiding this comment.
P2: A single failed heartbeat RPC raises out of execute, and the finally block SIGKILLs a healthy child. Only an explicit accepted: False should count as lease loss. Catch and log transient RPC errors here, and retry on the next heartbeat interval.
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/utils/sync/worker_runtime.py, line 67:
<comment>A single failed heartbeat RPC raises out of `execute`, and the `finally` block SIGKILLs a healthy child. Only an explicit `accepted: False` should count as lease loss. Catch and log transient RPC errors here, and retry on the next heartbeat interval.</comment>
<file context>
@@ -30,23 +47,70 @@ def __init__(self, client: WorkerClient):
+ 'epoch': payload['sequencer_epoch'],
+ 'token': lease['token'],
+ }
+ if not (await self.client.call('heartbeat', identity)).get('accepted'):
+ return
+ self.active = True
</file context>
| runtime.execute = AsyncMock() | ||
| await runtime.tick() | ||
| assert client.operations == ['claim'] | ||
| runtime.execute.assert_awaited_once() |
There was a problem hiding this comment.
P3: This assertion does not verify the handoff. Use assert_awaited_once_with to pin the exact lease the claim returned, so the test fails if tick() passes the wrong value.
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/test_sync_worker_runtime.py, line 71:
<comment>This assertion does not verify the handoff. Use `assert_awaited_once_with` to pin the exact lease the claim returned, so the test fails if `tick()` passes the wrong value.</comment>
<file context>
@@ -63,8 +64,11 @@ async def call(self, operation, body=None):
+ runtime.execute = AsyncMock()
+ await runtime.tick()
+ assert client.operations == ['claim']
+ runtime.execute.assert_awaited_once()
</file context>
| runtime.execute.assert_awaited_once() | |
| runtime.execute.assert_awaited_once_with({'payload': {'uid': 'synthetic', 'job_id': 'job', 'sequencer_epoch': 1}, 'token': 't'}) |
| @sync_attempt | ||
| @sync_snapshot_resolve_job | ||
| async def _run_full_pipeline_background_async( # pyright: ignore[reportGeneralTypeIssues] — legacy coordinator exceeds Pyright's analyzer complexity ceiling | ||
| async def run_full_pipeline_background_async( # pyright: ignore[reportGeneralTypeIssues] — legacy coordinator exceeds Pyright's analyzer complexity ceiling |
There was a problem hiding this comment.
P3: The rename leaves two runbook docs citing the old _run_full_pipeline_background_async name, so the lifetime inventory no longer matches the code. Update sync-request-lifetime-inventory.md and diarizer-batch-cohort.md to run_full_pipeline_background_async.
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/utils/sync/pipeline.py, line 2576:
<comment>The rename leaves two runbook docs citing the old `_run_full_pipeline_background_async` name, so the lifetime inventory no longer matches the code. Update `sync-request-lifetime-inventory.md` and `diarizer-batch-cohort.md` to `run_full_pipeline_background_async`.</comment>
<file context>
@@ -2573,7 +2573,7 @@ async def _resolve_safety_wal_target(
@sync_attempt
@sync_snapshot_resolve_job
-async def _run_full_pipeline_background_async( # pyright: ignore[reportGeneralTypeIssues] — legacy coordinator exceeds Pyright's analyzer complexity ceiling
+async def run_full_pipeline_background_async( # pyright: ignore[reportGeneralTypeIssues] — legacy coordinator exceeds Pyright's analyzer complexity ceiling
job_id: str,
uid: str,
</file context>
| def execution(monkeypatch): | ||
| # The real pipeline imports lazily, without constructing credentialed | ||
| # clients. Replace provider/storage leaves, retain actual Redis ownership. | ||
| from database import account_deletion_marker as account_deletion |
There was a problem hiding this comment.
P3: The execution fixture imports its modules inside the function body. Move these imports to the module top, as AGENTS.md requires, so the patch targets are visible at module scope.
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/test_sync_worker_execution.py, line 94:
<comment>The `execution` fixture imports its modules inside the function body. Move these imports to the module top, as AGENTS.md requires, so the patch targets are visible at module scope.</comment>
<file context>
@@ -0,0 +1,176 @@
+def execution(monkeypatch):
+ # The real pipeline imports lazily, without constructing credentialed
+ # clients. Replace provider/storage leaves, retain actual Redis ownership.
+ from database import account_deletion_marker as account_deletion
+ from utils.account_cutover import access
+ from utils.sync import ledger_completion, pipeline
</file context>
| } | ||
|
|
||
|
|
||
| async def test_lease_loss_kills_job_and_its_executor_process_group(monkeypatch, tmp_path): |
There was a problem hiding this comment.
P3: These lease-loss and crash tests spawn real subprocesses and rely on real sleeps, which the backend test README classifies as non-unit. Mark them @pytest.mark.slow (or move them to the slow manifest lane) so the PR lane does not run them as hermetic unit tests.
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/test_sync_worker_execution.py, line 29:
<comment>These lease-loss and crash tests spawn real subprocesses and rely on real sleeps, which the backend test README classifies as non-unit. Mark them `@pytest.mark.slow` (or move them to the slow manifest lane) so the PR lane does not run them as hermetic unit tests.</comment>
<file context>
@@ -0,0 +1,176 @@
+}
+
+
+async def test_lease_loss_kills_job_and_its_executor_process_group(monkeypatch, tmp_path):
+ processes = []
+
</file context>
| async def test_lease_loss_kills_job_and_its_executor_process_group(monkeypatch, tmp_path): | |
| @pytest.mark.slow | |
| async def test_lease_loss_kills_job_and_its_executor_process_group(monkeypatch, tmp_path): |
# Conflicts: # backend/config/flag_budget.json
|
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
Marks newly registered, active-fenced backfill cohort jobs worker-eligible and runs them in a dedicated child process. The original named Cloud Task is still enqueued, scheduled five minutes after the head reservation; no worker claim means it runs the existing handler. Redrive and normal worker failure return directly to that fallback. S1 and S2 have merged; this PR targets main. Main was merged locally without rewriting branch history; its new privacy decorator is preserved.
Workers run the existing async pipeline without the Cloud Run handler budget or replacement-enqueue machinery. Sequencer heartbeat remains 120s; Redis renewal remains 300s with the unchanged 1800s TTL. After acquiring Redis, a child revalidates the sequencer token before download or provider work. Lease loss kills the owned process group, including detached executor leaves. Cancellation retains the Redis fence and staged custody. SIGTERM stops intake and drains up to the existing 1500s pod grace.
A separate parent-enforced 1380s work deadline bounds bootstrap, pipeline work and normal flushing even when the child's provider/executor never returns. Deadline expiry stops sequencer renewal and kills the job process group before
/fail; Redis remains held until its unchanged silence TTL and the existing sweep redrives Cloud Tasks. A regression proves child/descendant death, no early fallback acquisition, next-epoch fallback acquisition after simulated 1800s expiry, and rejection of both stale tokens. Minimal redrives refuse before Redis/download whenSYNC_MINIMAL_REDRIVE_ENABLEDis off; enabled mode reaches the pipeline unchanged, with regressions for both cases.The shared pipeline entry, staged download and async custody cleanup now have public names; router callers and existing test/harness seams migrate together. This preserves a single execution implementation without private-API type suppressions or compatibility wrappers. A token-fenced
execution_drive=pulljob marker lets the staging kit distinguish installed-worker execution from Cloud Tasks fallback alone.Normal child exit flushes active holds (30s) and drains tracked background tasks (10s) before process termination. Tests exercise actual hold closure and owned-task cancellation for completion/retry, and verify lease-loss cancellation bypasses flushing after its fence.
Successful worker completion immediately kicks the next queued UID head, matching Cloud Tasks and avoiding an added two-minute sweep wait per job. An integrated sequencer test proves one next-head enqueue and an inert duplicate completion; RPC/sequencer focused tests pass 146 cases.
Available-owner scans stop before owner queries in global legacy dark. Otherwise each poll reads at most 100 candidates and attempts one claim transaction; a per-API-process document-ID cursor reaches filtered later pages on subsequent polls and wraps at EOF. Empty/error claims back off 10/20/40/60s, resetting to 5s on work; health remains fresh during backoff. Tests cover cohort and scoped-dark filtering, cursor continuation/wrap and transactional-attempt bounds. Conservative owner-read ceiling at the 5s floor: 105/poll including five transaction attempts, 1,814,400/day per worker (3,628,800 for two). Sustained empty polling at 60s is 151,200/day per worker plus the initial transition. These bounds exclude existing shared rollout-cache refreshes and transport retries; they are not live billing measurements.
Session privacy integration repair
The public S3 coordinator retains #24402's privacy decorator; its cancellation test now calls the public name with every original assertion unchanged. The pull worker also scopes its entire attempt before the first await, covering ledger convergence, preflight and cleanup outside the nested coordinator. Both Cloud Tasks and pull entrypoints, and the actual pull-to-coordinator call, have cancellation regressions.
The isolated child previously lost process-local privacy metrics on exit. The supervisor now scrapes the child's live Prometheus mmap counters, retains their final values after normal exit or SIGKILL, and removes each owned child directory after reaping the process group.
/metricsexports the seven existing counter families; the worker chart enables PodMonitoring. This is code/chart preparation only, with no deployment, credentials or admission changes. Worker installed-target coverage and successful scrapes are prerequisites for the all-plane 14-day shadow window.Regressions exercise live authority, candidate memo hits, and a deliberately missing writer-token bump that must produce a stale-allow mismatch while retaining the live block. Removing the worker scope makes four regressions fail; removing child counter transport makes two fail. Actual child-process tests verify live and shadow reads/checks, walks, mismatches and memo/denominator counters survive normal exit and SIGKILL without double counting or retained per-job files. An ASGI check exercises the supervisor endpoint with a real child.
The main integration also corrects a stale derived flag-inventory count (225 → 226); declarations and the 169 seeded/replacement budget are unchanged. All 22 flag-budget tests pass. At the preceding privacy repair head, GitHub shard 6 passed; shard 5 exposed this inventory inconsistency, also present unchanged on main.
Product invariants affected
Customer data authority, account-deletion/cutover and content/run fences are retained (INV-DATA-1 / INV-AUTH-1). New worker jobs require active ledger fencing, the sequencer, backfill lane and legacy mode on at registration. Existing accepted workers drain under their tokens. No batch admission, workflow, prod.yaml, IAM or deployment changes.
How it was verified
Hermetic tests through
omi-heavy run -- nice -n 19in BasedHardware/omi task tree: RPC and strict Firestore fence tests; real Redis Lua execution exclusion; admission mode matrix; named-task five-minute fallback; actual subprocess/descendant death on lease rejection and child crash; real pipeline composition with synthetic provider/storage leaves; stale-claim rejection after Redis acquisition; cancelled-job custody/TTL retention. Full localmake preflightand push hook are required before publication.Round-1 repair verification: 177 focused worker/sequencer tests and 815 selected Firestore contract tests passed, each file in its own pytest process. Every review finding has a regression observed failing before its fix. Local preflight passed; normal pre-push gates and exact-head GitHub checks are reported in the handoff, including cancellations.
Live OIDC, real Firestore contention, installed worker image, staging outcomes and cost savings are NOT measured here. The separate staging kit and infracost's authorized window remain gates. No GCP credentials loaded or cloud writes performed.
Ramp and rollback
Percent remains 0. Infracost with lead approval owns synthetic staging qualification, then stable SHA-256 cohorts 5% → 25% → 50% → 100%, at least 24h at 5% and 25%. Gates: zero lost speech/nonterminal ACK; partial_failure no worse than baseline (~5%); no oldest-wait/depth regression at equal admission; cost comparison includes actual node-hours and displaced Cloud Run container-hours. Review activation or report continued darkness blocked by 2026-11-09. Rollback: percent 0 closes new eligibility and claims, accepted workers drain, already-enqueued Cloud Tasks and sweep retain recovery. Full backfill net $40–60/day remains a scope estimate, not measured savings.
Tests
test_sync_worker_execution.py,test_sync_worker_runtime.py,test_sync_worker_rpc.py, andtest_sync_backfill_uid_sequencer.pyexercise core, duplicate/expired ownership, fallback, death and refusal paths. Synthetic process fixtures are bounded and every owned group is reaped.UI-Evidence: none -- backend worker execution only.
Failure-Class: none