Skip to content

fix: make cap-held recovery durable across restarts - #22388

Merged
Git-on-my-level merged 9 commits into
mainfrom
fix/cap-hold-durable-redrive
Oct 19, 2026
Merged

Git-on-my-level merged 9 commits into
mainfrom
fix/cap-hold-durable-redrive

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

A rollout or SIGKILL could leave paid held audio waiting indefinitely for a client wakeup. Add an awaited periodic server sweep over existing processing choices and abandoned live staging, retaining month/cutoff/reservation/lease/allowance fences and rotating bounded discovery cursors. Remove memory-only wakeups and self-respawn.

Live capture persists at-most-15-second encrypted fragments, freezes their layout and composes one immutable retained source per minute. Socket/lifespan shutdown gives tails a bounded 30-second coordinator wait; parked publications retain scratch until their executors complete, with hard-termination loss still possible. Quota reserves one staging overlap slot per 64-source block, consumes only after durable receipt and withholds ambiguous refunds. Held STT disables nested retries and persists encrypted nonempty provider results before ingest. A conservative SDK encoded-map envelope enforces a whole-document 768 KiB cache budget that preserves earlier results; oversized/aggregate-budget misses continue usable first responses to ordinary ingestion without cache (residual crash window through atomic ingest). Five concurrent owners each visit up to 100 items over bounded 10-row pages with a monotonic 900-second next-item/next-piece budget. Pre-cutoff staging keeps consent open until final seal with original creation time.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page

The stack harness enforces the current recoverable-quarantine contract: HTTP 200 processing, a positive polling hint, zero projected completion and no result/error. It also checks terminal failed-held/no-repay behavior. The exhaustion diagnostic compares current scheduling with the former dispatch rate while preserving paid-call and privacy assertions. Existing isolated fixtures retain their no-consent/no-paid-work guarantees.

Validation (documentation/metadata on 73e1106873438129c1d5dcaa1b4e99608e9bc795; layout evidence from 3577d03c669b14caf290ae6d8d8a9334e91165a5; unchanged production-code evidence retained from 3595366c367afd7ff9746e3570d8c7a84e20b7be):

  • Actual Cloud Tasks emulator stack: all 18 legacy and batch scenarios pass, including polling, graceful/forced replacement, deduplication and privacy.
  • Real loopback Firestore emulator: SDK sizing oracle, 64-minute operation counts, immutable seal retry, expired staging, bounded pagination, lease contention, aggregate result budgeting, provider checkpoint/crash/restart with one mocked POST, pre-seal consent and actual SIGKILL mid-sleep/mid-run followed by scheduler-only resume without double debit.
  • Serial backend/test.sh: 1,624 passing tests across 45 files. Full Python 3.11 Pyright: zero errors. Runtime-image contracts: all 14 images pass. make preflight: all 40 selected checks pass. Normal commit hooks passed.
  • Registry layout only: all 342 parsed flag records remain identical; the owning registry/render check passes. Synthetic merge against main 733a74abd6f5bfc0e243b5c4be9d8ea12a4501be is clean and preserves every incoming flag record.
  • Independent Grok review: APPROVE on 3577d03c669b14caf290ae6d8d8a9334e91165a5; 14 scoped files, 346 tests, runtime contracts for 14 images and the real emulator passed, with no blocking findings. The subsequent change corrects runbook prose only.
  • No live backend/vendor call, production/customer data, GCP tier, deployment or flag change. Remote CI status is recorded by this PR’s checks for the published head.

Deployment prerequisites: approve/build three collection-group indexes (processing_backlog.state, stt_cap_holds.state, stt_cap_holds.staging_cleanup), ship updated sync readers before the listen fragment writer, include pusher shutdown wiring, and complete these steps before cap-cohort activation, then reconcile production-only cap-hold-durable-redrive Scheduler job. Defaults on; rollback switches are CAP_HOLD_DURABLE_REDRIVE_ENABLED=false and CAP_HOLD_LIVE_FRAGMENT_ENABLED=false. Keep redrive on to seal old staging when rolling back the fragment writer. Both existing enforcement flags remain off. Cohort deadline: 2026-10-19 18:00Z.

Limits/cost: SIGKILL can lose the current volatile fragment (15 seconds of accepted samples); a kill between vendor acceptance and result checkpoint may duplicate one provider POST per frozen piece, at most two persisted dispatch attempts, then explicit retained reconciliation failure. For cache-omitted responses that crash window lasts through atomic ingest proof. No exactly-once vendor claim. Measured steady custody per minute: 19.078125 reads / 8.03125 writes / four fragment PUTs + one compose / one retained source; modeled ~$0.00249 per capped hour including one retained month, excluding STT/recovery/compute and vendor/storage retention settings. See backend/docs/runbooks/cap-hold-durability.md for exact assumptions, quota/crash limits, fairness latency and deployment order.

Line-Count-Exception: backend/database/firestore_index_registry.py | 2164 -> 2167 | Declare the three collection-group fields consumed by durable cap-hold redrive in the existing index authority.

Line-Count-Exception: backend/utils/sync/pipeline.py | 3556 -> 3561 | Route held STT through the extracted durable provider-result primitive before existing parsing and ingestion.

Budget encrypted provider caching against the complete Firestore document and continue oversized usable responses into ordinary ingestion. Drain bounded pages across five concurrent owners with a monotonic next-item and next-piece budget, retaining pre-seal consent.

Bound shutdown coordination and keep scratch creation, encoding, publication and cleanup inside the actual storage executor leaf. Cover crash/restart, aggregate cache capacity, throughput, consent sealing and both waiter and publication cancellation.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 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-19T08:11:24.251449Z 73e1106 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.

Use the existing SDK encoded-map envelope for conservative aggregate result sizing without expanding import requirements. Align the stack pending-poll assertions and reviewed simulator traces with main bounded recovery dispatch; repair isolated fixtures while preserving no-consent, no-paid-work and shutdown guarantees.
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…, retry, reasons, runtime percent) (#22420)

Lane-1 stubs for the legacy-sync retirement swarm (contracts (a), (b), (d), (e), (f)):

- database/outbox.py: OutboxKind, Outcome, Claim, EnqueueResult, SweepCounts, Outbox protocol,
  outbox_for selector (NotImplementedError until lane 9's Firestore outbox).
- utils/workers/consumer.py: Role, Result (validated), QueueConsumer protocol, run_push/run_pull
  drivers and the 200/409-only http_response mapping; re-exports Outcome/Claim.
- utils/workers/retry.py: ExpectedRetry and retry_response (409 {"status":"retry","reason":...}).
- utils/observability/reasons.py: ReasonFamily, RetryReason, ConsumerReason, RampReason,
  reason_label with omi_reason_unknown_total{family}.
- utils/rollout/runtime_percent.py: signatures only (lane 6).
- routers/enrichment.py, routers/batch_provider_stt.py: empty routers (lanes 9 and 8); mounted
  after #22388's main.py edit reaches integration.
- scripts/cross_service_contract.py: TaskEdges enrichment and provider-stt; registrations of
  task-target-retry-semantics (lane 4) and staging-mirrors-prod (lane 2) via a lazy loader of
  scripts/cross_service_checks/<module>.py. Known edge-declared gaps until lane 7's ops file.

No behaviour change: nothing on main calls the new modules.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…n lock (B5), worker digest promotion, OMI_ROLE map (B8) (#22430)

* feat(deploy): ops file + config-train (B4), prod-train lock (B5), release-tree check

B4: backend/deploy/ops/{prod,staging}.yaml hold the ops-owned values the
trains must not touch: the sync-jobs-fresh / sync-backfill-fresh re-points
from the 10-18 and 10-19 queue stalls, recovery queue 16/8, the fresh queues'
rates and retries, and service-level scaling (backfill as bounds only while
redis_guard owns it). backend/scripts/ops_train.py plans against the serving
revision (status.traffic, never spec.template), refuses when the template
differs from the serving revision outside ops keys, routes every env change to
its new named revision explicitly (backend-sync-backfill pins traffic) and
verifies it serves. config_train.yml runs plan/apply behind the prod approval
gate. Live ro-prod plan of the Cloud Run half is zero-diff.

B5: every prod deploy writer (backend, listen, LLM gateway, pusher, diarizer
/batch worker, parakeet, config-train) takes the prod-train concurrency group;
break_glass_lock falls back to the pre-B5 per-target lock. The deployment
concurrency policy evaluates the group expressions and enforces both.
backend/scripts/prod_train_lock.py reads the lock from active runs plus their
deployment environment for the ramp controller (fail closed on unknown).

Promotion identity (contract (i)): check_release_tree.py asserts the main merge
tree equals the staging-qualified OMI_RELEASE_TREE read from serving revisions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(deploy): promote batch-worker images by digest with a tree check (B7)

gcp_diarizer.yml labels every image with org.opencontainers.image.revision and
omi.release.tree, and accepts image_digest for batch-pipeline-worker: an
already-built registry digest deploys without the 4.7 GB rebuild only when
check_release_tree.py image confirms its tree equals the admitted source tree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(backend): OMI_ROLE role map with route census (B8)

app_roles.py lists every router in today's mount order with its roles (api,
workers, realtime; default all is behaviour-neutral). The census test pins the
all role to main.py's include order, requires every TaskEdge and backend
Scheduler target to be mounted by workers and every websocket router by
realtime. main.py switches to mount_routers once #22388's main.py edit reaches
integration (frozen until then).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(ci-budget): record the image_digest dispatch input

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): census tolerates lane 1's not-yet-mounted stub routers (shrink-only)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…ep endpoint is deployed

An unreconciled manifest job fails every deploy's full scheduler --check
(2026-09-28 lesson, #19604). Flip to active and reconcile after the sweep
endpoint is serving.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit e983fef into main Oct 19, 2026
57 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/cap-hold-durable-redrive branch October 19, 2026 08:54
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…ce on integration

#22446 (main) allowed the reason-ratio alert to land before its producers, with a test that
fails once a producer is declared. The lane-1 stub (#22420) already declares
omi_reason_unknown_total, so after the #22388 sync every integration PR failed
test_pending_backend_alert_metric_allowances_expire_when_the_producer_lands. Keep only
omi_reason_total pending; lane 14 (#22422) removes it when it lands the denominator.

Verified: pytest tests/unit/test_monitoring_alert_rule_contract.py, 60 passed (unit).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
The sweep endpoint (/v2/cap-hold-recovery/sweep, #22388) is serving on prod
backend-sync at e983fef since 2026-10-19 09:33Z, so the job can leave
lifecycle: planned and be reconciled.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…slice 3, stacked on #22457) (#22467)

* feat(batch): C8 provider-STT stage core (lane 8 slice 1, behaviour-neutral)

Adds the batch provider-STT stage for languages Parakeet cannot serve, so
batch never needs the legacy fallback for them:

- resolve_route(): admission-time stt_route/provider_reason/provider_service
  (contract (c) fields). Unknown language is 'multi' -> Parakeet, as legacy.
  BYOK never changes the STT route (sync prerecorded never used BYOK keys).
- enqueue_in_transaction(): writes a provider unit as provider_pending with
  merge_pending set, outside the GPU DRR ring, keeping the owner revision
  fence and late-capture watermark. Intended for an admit() enqueue hook.
- ProviderSttStore/ProviderSttStage: paid-once job-row intent
  (pending -> running CAS mints the token), one Modulate call with client
  retries disabled, deterministic per-token result object, settle to the
  same result_ready transition Scheduler.complete performs. Redelivery
  reconciles, never re-spends; vendor failure and abandoned intents settle
  failed_held (never 'held', so quarantine recovery cannot pay twice).

Nothing imports the new module yet: intake wiring, the queue consumer and
the router follow once the lane-1 stubs and the admit() hook land.
Expected C8 traces are pinned under pipeline_sim_goldens_pending/ with a
strict xfail until the sim configs exist.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(batch): route the intake language decision through provider_stt.resolve_route

Behaviour-neutral at legacy_sync 'on': unknown and 'multi' languages keep
today's legacy fallback explicitly, and a parametrized test pins the old and
new conditions equal for every language class with and without BYOK. This is
the seam the C8 provider route replaces in draining/dark.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(batch): keep the pending C8 golden check inside the fast-unit CPU budget

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(batch): admit() enqueue= and adopt= hooks (additive, keyword-only)

Contract (a) amendment (lead ruling 10-19): enqueue= lets the C8 provider
stage write its units and their outbox rows outside the GPU ring in the
admission transaction; adopt= lets intake take over a legacy ledger row it
re-validates inside that transaction (a row legacy can no longer finish).
With both unset, behaviour is unchanged. File owned by E1/Sol: needs Sol's
agreement before merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(batch): C8 provider-STT consumer, route and draining/dark admission (lane 8 slice 2)

- ProviderSttConsumer (kind provider_stt, role workers, 1800s lease, no
  heartbeat) maps the stage onto contract (a) results; the route
  POST /v2/batch-pipeline/provider-stt/run answers 200 / 409 retry / 400
  malformed under Cloud Tasks OIDC, never 429/503.
- Intake, with legacy_sync draining or dark: a language Parakeet cannot serve
  is admitted to the provider stage (outbox row in the admission transaction,
  wake after commit); legacy-owned content is fenced per contract (h)
  invariant 4 through lane 10's fence_decision; a stranded legacy row is
  adopted once by the admit() adopt= CAS; a legacy final-pass recording is
  acknowledged, never re-admitted. At 'on' every route is today's.
- BYOK (David, 10-19): routed like every other upload. The batch 503
  sync_batch_byok_unavailable and the live-upload legacy owner choice for BYOK
  are removed; enrichment runs on Omi's keys.
- merge.py (lead sign-off, one line): provider results carry the
  recovery_version marker, so projection uses vendor labels as for recovered
  units.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(batch): resolve the provider-STT outbox off the event loop

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(batch): keep lane-8 tests inside the fast-unit CPU budget

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(batch): record BYOK as the admission-time funding decision (provider_reason='byok')

The route stays language-only; provider_reason='byok' records that admission
funded the unit while the validated keys were present. The provider stage
never re-runs the keyless funding check for it. Writing the same value into
ProjectionBinding.policy (lane 6's GPU dispatch skip) waits for E1 (#22448):
neither ProjectionBinding.policy nor BatchUnitPolicy.provider_reason exists
on integration yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(batch): cap-hold rehome adapter into batch admission (lane 8, C11 precondition)

cap_hold_admission.admit_held decodes a claimed, sealed, unspent hold into
one WAV and admits it through the same batch intake as uploads, under a
content id derived from the hold, so a retried sweep re-presents the same
content and the batch ledger guarantees one unit. Enabled only while legacy
sync is draining or dark (cap_hold_mode batch_hold). Holds legacy recovery
already spent on (piece receipts / processed paths) are refused and finish on
the legacy path. Imports nothing from utils.sync.pipeline (C11).

intake.accept_upload gains decode= for server-held audio; capture_decode
exposes its canonicalization as canonical_pcm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(sync): hand eligible cap holds to batch admission in recover_selected

The one hook in #22388's recovery path (driven by /v2/cap-hold-recovery/sweep):
under the existing row claim, an eligible hold in draining/dark is admitted to
batch, marked batch_admitted, and erased; batch projection owns the
conversation and usage, so the hold is never settled as legacy-transcribed.
At legacy_sync 'on' the legacy path is unchanged. File owned by the
Subscription session: needs its agreement before merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(batch): Firestore outbox for provider_stt (contract (b), lane 8)

One row per provider unit keyed by its batch segment id, in a stage-scoped
collection (dev and prod share a Firestore project). Lease-token fencing on
every post-claim mutation, STALE/BUSY/DEFERRED/DISCARDED claim outcomes,
transactional enqueue in the caller's batch transaction with the wake after
commit, privacy discard at claim and sweep, and a sweep that re-wakes only
lost wakes (older than 600s, no live lease). Wakes are pst- named Cloud Tasks
built in utils/provider_stt_tasks.py, outside the env-ratcheted paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(outbox): route OutboxKind.PROVIDER_STT to lane 8's Firestore outbox

The one-line selector branches in FirestoreOutbox and firestore_outbox (lead
ruling 10-19: lane 8 owns the provider_stt outbox, lane 9's seam). Lane 9's
selector tests now pin the still-reserved CAP_HOLD_REDRIVE as unserved.
Lane 9's file: flagged for lane 9.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(firestore): register the provider-STT outbox claim/sweep query drivers

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(sync): gate cap-hold batch hand-off like legacy dispatch; batch_admitted is terminal

Subscription-session review of #22467 (comment 6264627147):
- The batch branch now runs _new_dispatch_allowed (funded allowance, hard
  restriction, daily audio ceiling) before admit_held; a gated owner's audio
  stays held.
- A batch_admitted row is terminal: re-selecting it never claims, re-admits
  or settles (settlement would bill twice); it only finishes an interrupted
  erase. The adapter treats batch_admitted/completed/retained/purged as
  ineligible.
- Tests pin the summary decrement in checkpoint's own transaction on
  held -> batch_admitted (once, not per retried save) and the re-select no-op.
  The durable sweep's backlog page (held/staging/sealing) and discovery kinds
  already skip batch_admitted rows.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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