Skip to content

feat(batch): isolated shadow of legacy uploads through the record pipeline (off by default) - #23003

Merged
Git-on-my-level merged 15 commits into
mainfrom
lane/batch-shadow
Oct 21, 2026
Merged

Git-on-my-level merged 15 commits into
mainfrom
lane/batch-shadow

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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.

  • Ship off: BATCH_PIPELINE_SHADOW_PERCENT=0. The lead enables 10% after the carrying train and watches the first hour; zero stops new GPU/paid work.
  • Shadow jobs never claim the legacy ledger, Redis progress/locks, owner scheduler rings or conversation documents. The shadow flag fences projection/publication, user allowance/accounting, live reuse and result persistence. Transcripts stay in memory; terminal records contain only hashed-owner outcomes. Audio retains owner encryption, privacy checks and bounded cleanup.
  • At most four idle offers use the existing pool. Busy/expired offers drop instead of entering a backlog. Shadow never waits behind ordinary GPU work; paid recovery runs outside pump lanes.
  • BATCH_PIPELINE_SHADOW_PAID_RECOVERY_PER_HOUR=200 is an atomic shared UTC-hour cap across Modulate and Deepgram, with at-most-once provider reservations per unit. Exhaustion or unavailable spend authority records shadow_paid_skipped / outcome paid_skipped.
  • V1 inline uploads and V2 legacy claims use the same isolated handoff. The CPU env manifest and Helm chart expose the off/capped settings. Worker-only BATCH_PIPELINE_SHADOW_RECOVERY_API_URL targets 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_total
  • omi_batch_shadow_paid_calls_total{provider=modulate|deepgram}
  • omi_batch_shadow_paid_audio_seconds_total{provider=modulate|deepgram}

Owner concentration comes from hashed owner_key terminal records / event=batch_shadow_outcome owner_hash=... logs, never a Prometheus owner label. The lead owns workspace fleet_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 dbc28b requires staging-soak synthetic-corpus qualification on isolated staging (zero user-visible writes, cap, load drop) before production 10%.

Validation:

  • Final 22-file suite: 945 focused unit/ASGI tests passed through omi-heavy run -- nice -n 19 env BACKEND_UNIT_TEST_FILE_LIST=... bash backend/test.sh after 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.
  • Real loopback Firestore emulator: all 3 concurrency tests passed (shared cap across replicas, duplicate-provider reservation, two uploads/one offer). No real GPU/provider invocation is claimed.
  • Grok full review and delta review completed; all reported findings addressed. R2's integration-role identity blocker is fixed and rendered principal/audience tests pass. Under the swarm's two-round cap, lead ruling fc7e19 accepted the fixed delta with no third round, merge on green CI.
  • make preflight and 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.
  • CI backend shards 4 and 5 then failed 22 sync upload tests with a 500: once tests replace utils.sync in sys.modules, the handler's lazy shadow_intake import raised. Both v1/v2 handoffs now go through one best-effort wrapper that logs event=batch_shadow_intake outcome=error and continues, so the shadow can never fail a legacy upload. test_sync_cloud_tasks.py (187) and test_sync_v2.py (182) pass with the 22-file suite; pyright 0 errors.
  • CI on the main-merged head then surfaced three more gaps, all fixed: live jobs persisted a meaningless shadow: false (changing the deleted_merged_targets golden), 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 inventories batch-pipeline-shadow as legacy-all (no env allowlist ever existed). 60 backend unit files (all test_batch_pipeline*, the CI-failing files and the earlier suite) pass; pyright 0 errors.
  • Known-red on main (Backend unit guardrails real-clock ratchet) was fixed by test(backend): give the notes-loop deadline test a 0.5s real-clock budget #23013 and merged in.
  • Follow-up under lead ruling 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.
  • No production account reads, GCP tier, deployment or live acceptance claimed.

Process exceptions:

  • Cross-lane contract publication (swarm/contracts.md) came after implementation rather than before; final rows were published and the consumer lane acknowledged them.
  • Early heavy checks overlapped before the final serial validation.
  • Source inspection surfaced an existing allowlist fixture identifier in tool output. It is not repeated here and was not a production account read.
  • The original agent died on a model-capacity error mid-lane; a resume agent finished checks and publication from the committed state.

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

Git-on-my-level and others added 11 commits October 21, 2026 13:19
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.
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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-21T10:38:47.347863Z a77600f 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: 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".

Comment on lines 2003 to +2004
BATCH_PIPELINE_WORKER_SERVICE_ACCOUNT:
value: ''
value: 'batch-pipeline-worker@{compute_project}.iam.gserviceaccount.com'

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 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 👍 / 👎.

Comment on lines +196 to +198
except Exception as error:
if reservation:
await run_blocking(db_executor, repository.finish, reservation[0], 'error')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +58 to +62
row = {
'shadow': True,
'state': 'settled',
'owner_key': job['owner_key'],
'class': job['class'],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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]>

@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: 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +201 to +202
@router.post('/shadow-recover', include_in_schema=False)
async def shadow_recover(body: RedriveRequest):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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}

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 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]>

@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: 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)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +203 to +205
from database.batch_pipeline_shadow import ShadowStore
from utils.batch_pipeline.intake import artifacts_for
from utils.batch_pipeline.shadow_recovery import recover

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 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 👍 / 👎.

Git-on-my-level and others added 2 commits October 21, 2026 17:22
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]>
@Git-on-my-level
Git-on-my-level merged commit 0bbf473 into main Oct 21, 2026
63 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/batch-shadow branch October 21, 2026 10:49
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