Repository navigation
feat(batch): isolated shadow of legacy uploads through the record pipeline (off by default) - #23003
Conversation
Use idle offers in the existing GPU pool, fence all publication and user accounting, and cap shared paid recovery calls across worker replicas. Record hashed-owner outcomes and VAD speech loss without storing transcripts.
Share live second-provider eligibility, require typed GPU handoffs, retain active recovery custody, erase shadow artifact receipts, and isolate telemetry. Expose off/capped settings and the existing recovery-role target in manifests. Cover v1 uploads and real Firestore offer/spend races without user side effects.
Name the isolated first-writer callback precisely in the policy boundary, and carry the explicit off/capped env fields in unrelated runtime fixtures.
Honor the normal pull's capacity snapshot, fresh reservations and duration ceiling before idle shadow dispatch. Preserve immutable identity for normal jobs created before the shadow field existed, and keep env fixture setup order.
Declare the existing worker principal on integration while leaving its normal worker audience closed. Assert rendered identity/audience parity with both worker profiles so an off-by-default release can activate paid shadow recovery.
# Conflicts: # config/feature-flags.yaml
Pre-push pyright rejected three errors on the shadow modules: a private _next_unit import from intake, a bare priority literal, and an untyped recovery callable passed to run_blocking. Keep a local _next_unit, pass Priority.DEEP (same IntEnum value) and annotate the recovery callable. Runtime behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.
Reviewed commit: c0bf7526ff
ℹ️ 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".
| BATCH_PIPELINE_WORKER_SERVICE_ACCOUNT: | ||
| value: '' | ||
| value: 'batch-pipeline-worker@{compute_project}.iam.gserviceaccount.com' |
There was a problem hiding this comment.
Grant the worker access to the recovery service
When the shadow percentage is enabled, the worker now sends recovery requests to backend-integration, but this change only configures the application-level service-account allowlist and does not grant that principal roles/run.invoker on the Cloud Run service. A repository-wide search found no such binding; the existing deployment contract explicitly says the worker is configured to invoke only backend-sync (backend/docs/batch-pipeline-serving.md:204), and the deployment workflow's only gcloud run services add-iam-policy-binding step targets backend-sync. Cloud Run will therefore reject these requests before /shadow-recover reaches verify_worker, causing every shadow item requiring paid recovery to end as a transport failure instead of producing the intended recovery outcome.
Useful? React with 👍 / 👎.
| except Exception as error: | ||
| if reservation: | ||
| await run_blocking(db_executor, repository.finish, reservation[0], 'error') |
There was a problem hiding this comment.
Clear the completed reservation before decoding the next unit
For a multi-file upload where the first unit reaches ready but decoding a later file raises, reservation still points at the earlier successful unit, so this exception handler settles that unit as error. If the worker has already taken it, the same call replaces its running state; its eventual result or recovery handoff can no longer update the record, corrupting the shadow outcome census because a valid unit is blamed for a later file's decode failure. Reset the active reservation after a successful ready transition, or track the reservation belonging only to the operation that failed.
Useful? React with 👍 / 👎.
| row = { | ||
| 'shadow': True, | ||
| 'state': 'settled', | ||
| 'owner_key': job['owner_key'], | ||
| 'class': job['class'], |
There was a problem hiding this comment.
Retain a deletable conversation binding in terminal rows
When a shadow job settles before a single-conversation deletion sweep reaches shadow_jobs, this replacement removes the only conversation_id by discarding item. purge_batch_owner(..., conversation_id=...) then calls _belongs on the terminal row, cannot associate it with the deleted conversation, and leaves its stable owner_key and outcome until the seven-day TTL; this contradicts the documented guarantee that conversation deletion includes shadow jobs (backend/docs/batch-pipeline-shadow.md:51-54). Preserve a bounded conversation binding that the purge can match, or carry matched shadow segment IDs from the artifact sweep into the shadow-job deletion.
Useful? React with 👍 / 👎.
CI backend shards 4 and 5 failed 22 sync upload tests with a 500: after some tests replace utils.sync in sys.modules, the handler's lazy import of shadow_intake raised AttributeError __path__ and failed the legacy upload. offer_upload already contains its own errors; only the import was unguarded. Route both v1 and v2 handoffs through one wrapper that logs and continues, so the shadow can never fail a legacy upload. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 51675c0a75
ℹ️ 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 self.shadow_result is None: | ||
| raise PermissionError('shadow result sink required') | ||
| self.authorize(item) | ||
| self.shadow_result(item, payload) |
There was a problem hiding this comment.
Defer shadow settlement until CUDA quiesces
When inference produces a result but the subsequent SynchronizedWorker.synchronize() call reports a fatal CUDA error, this callback has already persisted a terminal recovered or empty outcome. ShadowRunner then attempts to finish the unit as error, but _finish ignores an already settled row, so the durable experiment census records a successful result from a GPU chain that was explicitly rejected before publication. Return the outcome to the runner and settle it only after process_batch has returned successfully.
Useful? React with 👍 / 👎.
| @router.post('/shadow-recover', include_in_schema=False) | ||
| async def shadow_recover(body: RedriveRequest): |
There was a problem hiding this comment.
Give shadow recovery a matching server timeout
When a Modulate recovery takes longer than the default 120-second POST timeout but remains within the provider's 300-second timeout, this new route is cut off by TimeoutMiddleware: main.py grants /recover-quarantine 1500 seconds but does not add /shadow-recover, even though the GPU client waits up to 600 seconds. Cancellation does not stop the already-running executor thread, so the worker receives a 504, clears _recovering, and can start another paid recovery while the first provider call is still running, defeating the documented one-outstanding-recovery bound.
Useful? React with 👍 / 👎.
| REPEAT_WORK_REVISION_ENABLED: {value: 'false', category: rollout} | ||
| REPEAT_WORK_LLM_VERSION: {value: 2026-10-16-v1, category: rollout} | ||
| SYNC_POLL_BACKOFF_ENABLED: {value: 'false', category: rollout} | ||
| BATCH_PIPELINE_SHADOW_PERCENT: {value: '0', category: rollout} |
There was a problem hiding this comment.
Configure the dev bucket before enabling shadow intake
When the required dev staging soak raises this percentage above zero, every selected upload fails before becoming ready because all rendered dev Cloud Run hosts still set BUCKET_BATCH_PIPELINE to an empty string, while shadow_intake.stage_upload calls artifacts_for, which rejects an empty bucket. The dev GPU chart already stages against based-hardware-dev-batch-pipeline-staging, so the Cloud Run intake and recovery hosts need that same bucket; otherwise the mandated pre-production qualification cannot exercise either GPU processing or paid recovery.
AGENTS.md reference: backend/AGENTS.md:L153-L153
Useful? React with 👍 / 👎.
Picks up #23013, which fixes the known-red real-clock budget ratchet on main. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8f2ab8d0a3
ℹ️ 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".
| 'privacy_generation': expected_generation, | ||
| 'write_pending_until': datetime.now(timezone.utc) + timedelta(seconds=UPLOAD_PENDING_SECONDS), | ||
| **( | ||
| {'shadow': True, 'cleanup_after': datetime.now(timezone.utc) + timedelta(hours=1)} |
There was a problem hiding this comment.
Run shadow artifact cleanup in development
When the dev shadow is enabled for the required staging soak (after supplying its bucket), this field only schedules deletion through cleanup_completed_artifacts, but that function runs from the batch serving supervisor and every rendered dev Cloud Run profile sets BATCH_PIPELINE_SERVING_ENABLED=false. Shadow audio objects and their owner/conversation-bearing artifact receipts therefore remain past the promised one-hour cleanup indefinitely; enable the maintenance loop on a dev host or provide an independent cleanup runner before staging uploads.
AGENTS.md reference: backend/AGENTS.md:L153-L153
Useful? React with 👍 / 👎.
| outcome = 'paid_skipped' | ||
| else: | ||
| try: | ||
| payload = second_stt(item, audio, empty) |
There was a problem hiding this comment.
Bind the Deepgram key before reserving second-provider calls
When Modulate returns empty for a long-speech shadow unit, this new call always fails before contacting Deepgram because the rendered backend-integration secret lists bind MODULATE_API_KEY but never DEEPGRAM_API_KEY, while deepgram_prerecorded_from_bytes requires that environment variable. The code has already consumed the durable paid reservation at this point and then records failed_held, so the experiment both misreports a provider call and loses every result that depends on the second-provider path; add the required secret binding and deployment validation before enabling shadow recovery.
AGENTS.md reference: backend/AGENTS.md:L171-L171
Useful? React with 👍 / 👎.
| wait_futures([entry[2] for entry in pending_persist]) | ||
| pending_persist.clear() | ||
| results[:] = [result for result in results if result is not None] | ||
| shadow_ids = {item.segment_id for item in items if item.shadow} |
There was a problem hiding this comment.
Suppress synchronous worker metrics for shadow units
When a shadow unit reaches diarization, _diarize_unit has already emitted the normal record_decision/record_compacted_unassigned counters and _diarize_full may have emitted the global batch fallback metric before this late shadow_ids filtering runs. Because shadow owners are deliberately disjoint from normal batch admission and those metrics have no shadow label, activating the shadow contaminates the normal diarization and fallback rollout signals; pass the shadow identity into these helpers and suppress their ordinary metrics, leaving the dedicated omi_batch_shadow_* families as the shadow readout.
Useful? React with 👍 / 👎.
| from database.batch_pipeline_shadow import ShadowStore | ||
| from utils.batch_pipeline.intake import artifacts_for | ||
| from utils.batch_pipeline.shadow_recovery import recover |
There was a problem hiding this comment.
Move the shadow route imports to module scope
These new function-scoped imports bypass the backend's required module-level import graph, so dependency and runtime-image validation cannot inspect the route consistently at startup. Move the shadow store, artifact factory, and recovery helper imports to module scope (or split a dependency-safe adapter if importing them eagerly exposes a cycle).
AGENTS.md reference: backend/AGENTS.md:L163-L169
Useful? React with 👍 / 👎.
CI shards 2 and 3 on the merged head surfaced three gaps: - Live jobs persisted a meaningless shadow: false via asdict(WorkItem), changing the deleted_merged_targets characterization golden. Enqueue already rejects shadow work, so live documents now omit the field and stay byte-identical to main. - The background-task ratchet flagged the six shadow fire-and-forget sites. Baseline them with why a SIGKILL loss only drops one sample: legacy owns processing, the reaper settles stale shadow jobs after 1h and paid reservations count before the call. - The cohort migration tool had no source for batch-pipeline-shadow. It never had an env allowlist, so inventory it as legacy-all, which only stored denials can narrow. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Legacy-served real uploads can now exercise the record pipeline without projecting or charging anything to the user. This catches empty-audio and held-recovery outcomes before the live ramp, using an independent owner-hash cohort and idle capacity in the existing GPU fleet.
BATCH_PIPELINE_SHADOW_PERCENT=0. The lead enables 10% after the carrying train and watches the first hour; zero stops new GPU/paid work.BATCH_PIPELINE_SHADOW_PAID_RECOVERY_PER_HOUR=200is an atomic shared UTC-hour cap across Modulate and Deepgram, with at-most-once provider reservations per unit. Exhaustion or unavailable spend authority recordsshadow_paid_skipped/ outcomepaid_skipped.BATCH_PIPELINE_SHADOW_RECOVERY_API_URLtargets the existing recovery role, with its OIDC audience and the GPU principal, so the terminal policy matches the record lane.Readout contract:
omi_batch_shadow_outcome_total{outcome=recovered|empty|failed_held|error|dropped|paid_skipped,class=fresh|recent|deep}omi_batch_shadow_speech_seconds_total{vad=worker|strict,class}omi_batch_shadow_speech_loss_seconds_total{vad=worker|strict,class}(whole-unit VAD speech when no words survive)omi_batch_shadow_gpu_seconds_totalomi_batch_shadow_paid_calls_total{provider=modulate|deepgram}omi_batch_shadow_paid_audio_seconds_total{provider=modulate|deepgram}Owner concentration comes from hashed
owner_keyterminal records /event=batch_shadow_outcome owner_hash=...logs, never a Prometheus owner label. The lead owns workspacefleet_gate.sh --shadow.At 10%, no extra GPU nodes are requested. Accepted audio depends on owner concentration and idle drops. As a conditional list-price scenario, per 100 eligible audio-hours, 10 shadow hours with 5% Modulate and 1% Deepgram duration cost about $0.0462 in paid recovery; all-duration two-provider recovery costs $3.42. The default 200-call shared cap and <=1h units give a conservative $62.40/hour list-price ceiling, not a measured vendor bill. Actual Modulate/Deepgram usage must be reconciled during the first hour. Rates, assumptions, retention and rollback are documented in batch-pipeline-shadow.md.
Services for the lead's train: backend sync upload hosts, the existing batch API/recovery target, batch-pipeline-worker, and backend/integration hosts that own shared deletion/retention. Carry the sync GMP collector config, which now retains the six shadow counters. Apply the four added shadow job/spend TTL policies using the existing retention operator tool. This PR does not deploy or enable the cohort. Lead ruling
dbc28brequires staging-soak synthetic-corpus qualification on isolated staging (zero user-visible writes, cap, load drop) before production 10%.Validation:
omi-heavy run -- nice -n 19 env BACKEND_UNIT_TEST_FILE_LIST=... bash backend/test.shafter syncing main: real WAL decode and encrypted staging preserve legacy files; full worker path discards transcripts; private recovery route never publishes; cohort, cap, duplicate, kill, admission/load-drop and collector-retention cases.omi-heavy run -- nice -n 19 make runtime-image-source-closure: all 19 registered images passed.fc7e19accepted the fixed delta with no third round, merge on green CI.make preflightand metadata-only preflight pass on the merged head (after the shadow admission clients moved onto the database executor). The pre-push backend pyright lane then caught three shadow-module type errors; the type-only fix gives 0 errors, the 22-file suite passes again, and the full pre-push gate passed on the pushed head.utils.syncinsys.modules, the handler's lazyshadow_intakeimport raised. Both v1/v2 handoffs now go through one best-effort wrapper that logsevent=batch_shadow_intake outcome=errorand continues, so the shadow can never fail a legacy upload.test_sync_cloud_tasks.py(187) andtest_sync_v2.py(182) pass with the 22-file suite; pyright 0 errors.shadow: false(changing thedeleted_merged_targetsgolden), so live job documents now omit it and stay identical to main; the six shadow fire-and-forget sites are baselined in the background-task ratchet with their SIGKILL-safety reasons; the cohort migration tool inventoriesbatch-pipeline-shadowas legacy-all (no env allowlist ever existed). 60 backend unit files (alltest_batch_pipeline*, the CI-failing files and the earlier suite) pass; pyright 0 errors.Backend unit guardrailsreal-clock ratchet) was fixed by test(backend): give the notes-loop deadline test a 0.5s real-clock budget #23013 and merged in.eab308: once feat: isolate heavy owners from partial batch ramps #23004 merges, apply the shared heavy-owner exclusion predicate (batch_ramp_owner_load_v1) before new shadow offers. Shadow-informed 30-minute holds count only matched-population windows after that.Process exceptions:
swarm/contracts.md) came after implementation rather than before; final rows were published and the consumer lane acknowledged them.Product invariants affected: INV-MEM-4. The changed runtime manifest enables no memory route; shadow publication fences prevent canonical intake or promotion from this experiment.
Line-Count-Exception: backend/routers/sync.py | 3826 -> 3863 | Keep the minimal best-effort v1/v2 handoffs at the legacy ownership seams; the implementation lives in dedicated shadow modules.
🤖 Generated with Claude Code