Repository navigation
perf(sync): trim no-op preamble and move Dream sweeps off fresh fleet - #24216
Conversation
Warm cohorts only for real work, return the prior job snapshot with valid sequencer claims, and retain all existing retry and terminal fences. Bound cap-hold request waits while preserving active provider checkpoints, route Dream sweeps to backfill, and declare the syncwall cap/rate cuts. Failure-Class: none
There was a problem hiding this comment.
5 issues found across 16 files
Confidence score: 3/5
- In
backend/deploy/ops/prod.yaml, the 40-instance cap makes the existing high-instance alert unreachable because it still evaluates at 72 and documentsmaxScale=80. Update the threshold and annotation to match the cap. - In
backend/routers/sync.py,warm_rollout_cohortsstill runs for account-cutover jobs that are immediately skipped. Move it belowshould_skip_background_account_mutationso those jobs avoid unnecessary cohort-store I/O. - The tests do not enforce two advertised contracts:
test_scheduler_reconcile.pycan accept a service-root OIDC audience, andtest_cap_hold_durability.pydoes not lock down the 240-second work budget or 270-second request ceiling. Assert the endpoint suffix and both timeout constants explicitly.
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_scheduler_reconcile.py">
<violation number="1" location="backend/tests/unit/test_scheduler_reconcile.py:53">
P2: This assertion does not require the OIDC audience to be the sync endpoint: a service-root audience still satisfies the equality because `removesuffix` is a no-op. Assert the `/v2/sync-jobs/run` suffix explicitly so a future audience regression is caught.</violation>
</file>
<file name="backend/tests/unit/test_cap_hold_durability.py">
<violation number="1" location="backend/tests/unit/test_cap_hold_durability.py:234">
P2: This regression test does not enforce the advertised 240-second work budget and 270-second request ceiling. Assert both constants explicitly so an overly aggressive timeout change cannot pass the suite unnoticed.</violation>
</file>
<file name="backend/docs/runbooks/cap-hold-durability.md">
<violation number="1" location="backend/docs/runbooks/cap-hold-durability.md:135">
P3: This sentence describes the wrong lifecycle: a pass that has returned cannot still finish its current item. Say that the tracked pass may finish its current item after the request returns, so operators do not misunderstand whether work remains active after `deferred: true`.</violation>
</file>
<file name="backend/deploy/ops/prod.yaml">
<violation number="1" location="backend/deploy/ops/prod.yaml:75">
P2: The new 40-instance cap makes the existing backend-sync high-instance alert unreachable: both alert definitions still evaluate at 72 and document maxScale=80. Update the alert threshold and annotation to match the 40-instance cap before applying this setting.</violation>
</file>
<file name="backend/routers/sync.py">
<violation number="1" location="backend/routers/sync.py:3392">
P2: `warm_rollout_cohorts` still runs for account-cutover jobs that are immediately finalized as skipped. Move this call below `should_skip_background_account_mutation` so blocked jobs avoid the cohort-store I/O and its failure/deferral path.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| dream = next(job for job in jobs if job['name'] == 'dream-agent-sweep-hourly') | ||
| target = dream['target'] | ||
| assert target['uri'].split('/')[2].startswith('backend-sync-backfill-') | ||
| assert target['uri'] == target['oidc']['audience'].removesuffix('/v2/sync-jobs/run') + '/v2/dream-agent/sweep' |
There was a problem hiding this comment.
P2: This assertion does not require the OIDC audience to be the sync endpoint: a service-root audience still satisfies the equality because removesuffix is a no-op. Assert the /v2/sync-jobs/run suffix explicitly so a future audience regression is caught.
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_scheduler_reconcile.py, line 53:
<comment>This assertion does not require the OIDC audience to be the sync endpoint: a service-root audience still satisfies the equality because `removesuffix` is a no-op. Assert the `/v2/sync-jobs/run` suffix explicitly so a future audience regression is caught.</comment>
<file context>
@@ -45,6 +45,18 @@ def post(self, url, **kwargs):
+ dream = next(job for job in jobs if job['name'] == 'dream-agent-sweep-hourly')
+ target = dream['target']
+ assert target['uri'].split('/')[2].startswith('backend-sync-backfill-')
+ assert target['uri'] == target['oidc']['audience'].removesuffix('/v2/sync-jobs/run') + '/v2/dream-agent/sweep'
+ assert dream['schedule'] == '0,30 * * * *' and dream['attempt_deadline'] == '1740s'
+ cap_hold = next(job for job in jobs if job['name'] == 'cap-hold-durable-redrive')
</file context>
| assert target['uri'] == target['oidc']['audience'].removesuffix('/v2/sync-jobs/run') + '/v2/dream-agent/sweep' | |
| assert target['oidc']['audience'].endswith('/v2/sync-jobs/run') | |
| assert target['uri'] == target['oidc']['audience'].removesuffix('/v2/sync-jobs/run') + '/v2/dream-agent/sweep' |
|
|
||
|
|
||
| def test_sweep_request_ceiling_leaves_headroom_below_five_minutes(): | ||
| assert 0 < cap_hold_redrive.SWEEP_WORK_BUDGET_SECONDS < cap_hold_redrive.SWEEP_REQUEST_WAIT_SECONDS < 300 |
There was a problem hiding this comment.
P2: This regression test does not enforce the advertised 240-second work budget and 270-second request ceiling. Assert both constants explicitly so an overly aggressive timeout change cannot pass the suite unnoticed.
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_cap_hold_durability.py, line 234:
<comment>This regression test does not enforce the advertised 240-second work budget and 270-second request ceiling. Assert both constants explicitly so an overly aggressive timeout change cannot pass the suite unnoticed.</comment>
<file context>
@@ -153,6 +153,111 @@ async def run(uid, **kwargs):
+
+
+def test_sweep_request_ceiling_leaves_headroom_below_five_minutes():
+ assert 0 < cap_hold_redrive.SWEEP_WORK_BUDGET_SECONDS < cap_hold_redrive.SWEEP_REQUEST_WAIT_SECONDS < 300
+
+
</file context>
| assert 0 < cap_hold_redrive.SWEEP_WORK_BUDGET_SECONDS < cap_hold_redrive.SWEEP_REQUEST_WAIT_SECONDS < 300 | |
| assert cap_hold_redrive.SWEEP_WORK_BUDGET_SECONDS == 240.0 | |
| assert cap_hold_redrive.SWEEP_REQUEST_WAIT_SECONDS == 270.0 |
| max_instances: 50 | ||
| # syncwall: source cap 50 -> 40; lead applies after fresh-latency review. | ||
| # Rollback: 50 (floor remains 5). | ||
| max_instances: 40 |
There was a problem hiding this comment.
P2: The new 40-instance cap makes the existing backend-sync high-instance alert unreachable: both alert definitions still evaluate at 72 and document maxScale=80. Update the alert threshold and annotation to match the 40-instance cap before applying this setting.
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/deploy/ops/prod.yaml, line 75:
<comment>The new 40-instance cap makes the existing backend-sync high-instance alert unreachable: both alert definitions still evaluate at 72 and document maxScale=80. Update the alert threshold and annotation to match the 40-instance cap before applying this setting.</comment>
<file context>
@@ -70,7 +70,9 @@ cloud_run:
- max_instances: 50
+ # syncwall: source cap 50 -> 40; lead applies after fresh-latency review.
+ # Rollback: 50 (floor remains 5).
+ max_instances: 40
min_instances: 5
backend-sync-backfill:
</file context>
| # Membership is only needed for actual work. Epoch, migration, lock, | ||
| # expired-job, terminal and reconciled deliveries keep their existing | ||
| # acknowledgement/cleanup paths without a cohort-store round trip. | ||
| await warm_rollout_cohorts(uid) |
There was a problem hiding this comment.
P2: warm_rollout_cohorts still runs for account-cutover jobs that are immediately finalized as skipped. Move this call below should_skip_background_account_mutation so blocked jobs avoid the cohort-store I/O and its failure/deferral path.
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/routers/sync.py, line 3392:
<comment>`warm_rollout_cohorts` still runs for account-cutover jobs that are immediately finalized as skipped. Move this call below `should_skip_background_account_mutation` so blocked jobs avoid the cohort-store I/O and its failure/deferral path.</comment>
<file context>
@@ -3391,6 +3386,11 @@ async def _run_sync_job_attempt(request: Request, task_retry_count: int, attempt
+ # Membership is only needed for actual work. Epoch, migration, lock,
+ # expired-job, terminal and reconciled deliveries keep their existing
+ # acknowledgement/cleanup paths without a cohort-store round trip.
+ await warm_rollout_cohorts(uid)
+
if await run_blocking(db_executor, should_skip_background_account_mutation, uid):
</file context>
| tracked pass retains the active workers through their current checkpoint. The | ||
| next scheduler tick joins that same pass instead of starting an overlapping | ||
| one. Discovery and rotation stop starting work after the pass deadline; workers | ||
| stop between candidates and pieces. A pass which has already returned may |
There was a problem hiding this comment.
P3: This sentence describes the wrong lifecycle: a pass that has returned cannot still finish its current item. Say that the tracked pass may finish its current item after the request returns, so operators do not misunderstand whether work remains active after deferred: true.
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/docs/runbooks/cap-hold-durability.md, line 135:
<comment>This sentence describes the wrong lifecycle: a pass that has returned cannot still finish its current item. Say that the tracked pass may finish its current item after the request returns, so operators do not misunderstand whether work remains active after `deferred: true`.</comment>
<file context>
@@ -124,30 +126,35 @@ serializes regular executions of the same job: a later scheduled execution waits
+tracked pass retains the active workers through their current checkpoint. The
+next scheduler tick joins that same pass instead of starting an overlapping
+one. Discovery and rotation stop starting work after the pass deadline; workers
+stop between candidates and pieces. A pass which has already returned may
+therefore finish its current item after the HTTP response. No new compute pool
+or continuation task is enqueued. On process loss, the durable choice,
</file context>
Leave cap-hold recovery unchanged per the lead's custody ruling rather than introducing a background-work ratchet exception. Keep the Dream sweep move and make its role census and canary audience contracts recognize the target. Failure-Class: none
A cohort-only timeout must retain its preamble 409 after warming moves behind the run lock. Confirm release before retrying; keep the existing delayed continuation if release is uncertain. Paid-work expiry keeps its old fencing. Cover read/budget expiry on direct/sequenced deliveries with both release outcomes. This corrects an edge in the unmerged preamble optimization. Failure-Class: none
Reuse the established in-stub handler-budget expiry helper so the timeout matrix cannot race preamble work on a busy runner. Keep production-sized budgets and preserve every direct/sequenced lock-release assertion.
…ate pass in shadow (#24293) ## Why Dream's weekly state pass has been merged and off since #24166, #24168 and #24171 went live. The rollout lead approved turning it on in shadow (bus 88966c). Until it runs in shadow, we have no numbers to decide whether it should ever serve. ## What Sets `DREAM_STATE_PASS_MODE=shadow` in the prod overlay on `backend-sync`, which runs the sweep today, and on `backend-sync-backfill`, where #24216 moves it once the scheduler is reconciled. Setting both means the flag doesn't get lost in the move. `runtime_env.yaml` and the feature flag registry doc are regenerated, and the flag is added to the deployment-setting classification. In shadow, the pass's people and task cleanup proposals go through staging and the two verifiers and are never applied or offered. It does write: the ref-grounded profile v2 and the planner's notes on each processed owner's user doc (`users/{uid}.ai_user_profile_v2`), and the `last_state_pass_at` cadence stamp on the owner's `dream_users` state record. No product feature reads the profile v2 or the notes yet, so no user sees any change; the state pass itself rereads them for its next run. **Voice fix:** verifier evidence for a person now comes from an allowlist (`PERSON_EVIDENCE_FIELDS` in `dream_verify.py`). Reading a person record in full returns `speaker_embedding`, the speech sample fields and the nested `person_voice_base` and `person_voice_confirmations`, and staging needs them to protect that person, so they can't be dropped at read time. A person with voice data can't be an edit target, but one cited only as evidence would have sent those fields to the verifiers. In a person's evidence row, verifiers now get only the listed fields, plus `has_voice_profile: true` when real voice data exists. A voice field added later stays out by default. This also covers the main Dream loop's verifier calls, which use the same function. **Not fixed here (main loop only, existing live behaviour, flagged to David):** - The main loop's `read` tool (`agent_capabilities/session.py`) can return a full person row, voice fields included, to the planning model. - A staged question's `quote` is matched against the full cited record (`guards.verbatim_quote`) and sent in the verifier payload, so a model that read a person's sample transcript could quote it to a verifier. The state pass reaches neither: its planner gets slim projections, and `StatePlan` has only cleanup and profile ops, so it cannot stage a question. **Data the pass reads:** the planner sees slim projections (people without voice fields, generated tasks, memory facts, conversation titles). Staging and the cleanup verifiers then read the records the plan cites, up to 48 per pass, with person rows narrowed as above; the profile-line check uses the slim projections. A whole-conversation citation sends that conversation's full transcript text to the verifiers. This is the same read path and reserved model the main Dream loop already uses, with no new provider, but this PR does turn that flow on for the state pass. The 1800s backfill request timeout the lead also approved is **not** in this PR. The deploy passes per-service flags only for `backend-integration`, so setting it in source means editing `.github/actions/`, which needs David to name the change. Details are on the bus (253fbd). ## Spend Reserved capacity on gemini-3.8-flash only, so no added vendor spend. Limits: - `DREAM_STATE_PASS_TOKENS_PER_PASS` (120000) covers the planner, cleanup verifiers and profile-line check. - `DREAM_STATE_PASS_SECONDS` (480) covers that same work. The profile write runs after it, on purpose: the transaction refuses to start past the deadline but can finish just after it. - `DREAM_STATE_PASS_MAX_PER_SWEEP` (4), and one complete pass per owner per week. - **Outside those caps:** the shadow value judge that follows a pass. It has its own per-sweep counter, so it adds up to 4 calls per sweep on top of the normal judge's 4, each with a 60000-token allowance (up to 240000 tokens per sweep). It is bounded by the outer Dream pass deadline, and its tokens are not in `levers.state_pass.total_tokens`. ## Rollout - **Metric and gates:** the row for this flag in `backend/docs/feature-flag-registry.md`, measured over at least 300 shadow state passes. - **Who expands it:** the Dream owner reads back after the train. Serving is a later change; this PR only reaches shadow. - **Rollback:** set `DREAM_STATE_PASS_MODE=off`, or revert this PR. That stops new runs but does not cancel one in progress; profile v2 fields already written stay on user docs, unread. - **Readback:** `levers.state_pass` on `dream_pass` lines. ## Product invariants affected - INV-MEM-4: named because `runtime_env.yaml` matches its path glob. Shadow proposals are never applied, and profile v2 lives on the user doc with no reader, so this adds no memory intake or promotion route. ## Review - Luna R1 returned BLOCK on the PR body, not the config: it understated the transcript reads, the 480s scope and the separate judge calls, and put the cadence stamp on the wrong record. All were checked against the code and are corrected above. That code is already merged and behaves as its comments and the runbook intend, so this PR has no code change for them. - Luna R2 returned BLOCK on voice fields reaching the verifiers, and R3 on nested voice fields that the first fix missed. The allowlist above replaces that first fix. - Luna R4 cleared the allowlist and returned BLOCK on the question-quote path above. It is main-loop only, so it is disclosed here and left to the read-tool follow-up. ## Tests `test_person_voice_fields_never_reach_a_verifier` covers top-level, nested and future voice fields; it failed when the first version of the fix was reverted, and the allowlist passes it. `test_dream_verification`, `test_dream_verify_hold` and `test_dream_state_pass` pass. Config: `test.sh` via `omi-heavy` on `test_backend_runtime_env_validator`, `test_render_backend_runtime_env`, `test_check_cloud_run_env_drift`, `test_config_train`, `test_cloud_run_service_identity`, `test_cloud_run_forbidden_env_deploy` and `test_dream_state_pass`: 148 passed. Not run in prod yet. Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Redelivered sync tasks currently warm rollout cohorts even when they cannot run work, and long Dream sweeps hold the fresh Cloud Run fleet. This change removes those no-op cohort reads, carries retry history back from a valid sequencer claim, routes Dream sweeps to backfill, and declares the syncwall capacity/rate cuts.
Changes:
begin_jobreturns the prior Redis job snapshot in its DB executor leaf; the necessary Redis read remains there, while the separate route executor dispatch disappears. Cohort-only timeouts retain the original queue-owned 409 after a confirmed lock release; uncertain release uses the existing safe continuation. Paid pipeline timeout behavior, run-lock re-reads, retry counts, five attempts and the final terminal check remain authoritative.Validation:
make preflight: all 38 selected checks passed, including async/import/runtime-image source closure, Firestore guards, route policies, lifecycle and documentation checks.Rollout is lead-owned. This PR does not apply live settings or deploy. Deploy the worker changes to backend-sync and backend-sync-backfill, reconcile the Dream scheduler, and apply the ops config separately. Review fresh latency/backlog after cap 40 before applying queue smoothing. Restore cap 50/rate 25 or the prior worker revision for rollback.
Coordination: #23973 proposes a later retirement cap 20/min 3 and backfill ceiling 10; its cap hunk and sizing test conflict with this intermediate max 40/min 5. Audio-merge is intentionally excluded per the lead's ruling because it has no prod ops entry and #24215 changes its load. The meta-repo sentinel expectation needs a lead update. No listen/pusher env or workflow changes.
Cap-hold is deliberately unchanged per the lead's custody ruling. Its sweep still has a 900-second cooperative owner-work budget, plus provider and storage tails, so these requests continue to hold the hot fleet for up to roughly 15 minutes before trailing IO completes. A hard sub-300-second response must not leave paid work exposed to revision retirement; durable request-owned continuation on the same service is deferred follow-up. The background-work ratchet and its baseline remain intact.
Failure-Class: none
These are performance and scheduling changes; the timeout correction preserves the pre-existing response contract within this unmerged optimization. Existing durable custody, retry and mutation authorities are preserved. No production account data was read or changed.
Line-Count-Exception: backend/routers/sync.py | 4147 -> 4166 | Preserve the cohort timeout retry contract with confirmed lock release and shared bounded continuation cleanup.
Follow-up validation: the exact CI slow-guardrail harness passed 2,050 tests. The cohort timeout matrix now triggers the established budget context from inside the stub, avoiding tiny real-clock deadlines. Production source is unchanged from Luna R2-reviewed
17411d7b; lead ruling237a5eaccepts this test-only follow-up without another review round. Source queue rate 15 does not apply during merge or the normal code train; manual Config Train must wait for the lead's cap-40 peak decision.