Skip to content

feat(batch): cap-hold rehome + provider-STT Firestore outbox (lane 8 slice 3, stacked on #22457) - #22467

Merged
Git-on-my-level merged 19 commits into
integration/legacy-retirefrom
lr/08-cap-hold
Oct 19, 2026
Merged

Git-on-my-level merged 19 commits into
integration/legacy-retirefrom
lr/08-cap-hold

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Lane 8, slice 3: rehome cap-held audio into batch admission, plus the provider-STT Firestore outbox. Stacked on #22457; review the last two commits only.

What

  • utils/batch_pipeline/cap_hold_admission.py (new): admit_held(uid, snapshot, row) admits one claimed hold.
    • The hold must be sealed and unspent: no piece receipts and no processed paths.
    • It is decoded with fix: make cap-held recovery durable across restarts #22388's cap_hold.read_audio into one WAV, split into units on the capture clock, and admitted through the same batch intake as uploads.
    • The content id is derived from the hold (sha256('cap_hold_v1', uid, hold_id)). A retried sweep re-presents the same content, so the batch ledger guarantees exactly one unit.
    • Unsupported languages take the C8 provider route.
    • It imports nothing from utils/sync/pipeline.py (C11).
  • utils/sync/cap_hold_recovery.recover_selected gets one hook. Under the existing row claim, in draining/dark, an eligible hold is admitted, marked batch_admitted and erased.
    • Batch projection owns the conversation and usage, so the hold is never settled as legacy-transcribed.
    • At on, the path is unchanged.
    • This file belongs to the Subscription session; the commit needs its agreement.
  • intake.accept_upload(decode=...) is added for server-held audio. capture_decode exposes canonical_pcm.

Provider-STT Firestore outbox (lead ruling 10-19: lane 8 owns it)

  • database/outbox_provider_stt.py: one row per provider unit, keyed by its segment id, in a stage-scoped collection.
    • Every mutation after a claim is fenced by the lease token.
    • Claims return STALE, BUSY, DEFERRED or DISCARDED as contract (b) requires.
    • A transactional enqueue writes in the caller's batch transaction; the wake happens after commit.
    • Privacy-fenced rows are discarded at claim and at sweep.
    • The sweep re-wakes only lost wakes.
  • utils/provider_stt_tasks.py creates the pst- named Cloud Tasks. It lives outside the env-ratcheted paths.
  • database/outbox_firestore.py gets the one-line selector branches, with lane 9's selector tests updated. This file belongs to lane 9; the commit is flagged for them.
  • Tests: test_provider_stt_outbox 11 passed; test_outbox_firestore 16 passed.

Paid exactly once

  • Kill after the admission commits, before _save: the next sweep admits the same derived content again (202 from the batch ledger), then saves. No second unit is created.
  • Holds legacy already spent on: they are refused and finish on legacy during draining.

Verification (unit, m5, serial)

  • test_cap_hold_batch_admission: 18 passed.
  • test_sync_cap_hold: 21 passed. test_sync_cap_hold_recovery: 29 passed. test_cap_hold_durability: 23 passed.
  • test_batch_provider_stt: 66 passed, 3 xfailed. test_batch_pipeline_intake: 22 passed.
  • Pyright: 0 errors.

Open

  • The held-audio summary counter after a hand-off is the Subscription session's call.
  • Funding: the dispatch re-check runs keyless and outside backlog_consent. That item is routed to lane 6/E1.

Product invariants affected

  • INV-DATA-1 (only through the integration base's lane-7 workflow files; this PR changes no workflow or data plane)

Failure-Class: none

🤖 Generated with Claude Code

Git-on-my-level and others added 12 commits October 19, 2026 13:28
…utral)

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]>
…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]>
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]>
…ion (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]>
Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ider_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]>
…1 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]>
…ected

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]>
@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-19T11:24:52.521584Z b389a5b 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: 5adb123feb

ℹ️ 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".

record_origin=record_origin,
)
wakes: dict[str, str] = {}
outbox = await run_blocking(db_executor, outbox_for, OutboxKind.PROVIDER_STT) if provider else None

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 Register the provider outbox before selecting it

When draining or dark mode selects the provider route for an unsupported language, this call always evaluates outbox_for(OutboxKind.PROVIDER_STT). In the reviewed commit, database/outbox_firestore.py lines 351-355 supports only ENRICHMENT and raises NotImplementedError for this kind, so accept_upload returns sync_batch_unavailable after staging the audio and never admits the provider job. A provider-STT outbox implementation must be registered before this path is activated.

Useful? React with 👍 / 👎.

Comment on lines +60 to +61
@router.post(ROUTE, include_in_schema=False)
async def run_provider_stt(request: Request, _retry_count: int = Depends(verify_provider_stt_task)):

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 Mount the provider-STT router before creating wake tasks

Provider wake tasks target this route, but in the reviewed commit backend/main.py neither imports nor includes batch_provider_stt.router; backend/tests/unit/test_app_roles_route_census.py also still lists it in STUB_ROUTERS_PENDING_MOUNT. Consequently, once provider outbox rows can be created, every Cloud Tasks delivery receives a 404 and no provider unit is consumed. Mount the router and wire its role in the same change that starts producing these wakes.

Useful? React with 👍 / 👎.

Comment on lines +396 to +398
if not await _save(uid, snapshot, row, {'state': 'batch_admitted', 'batch_job_id': admitted.batch_job_id}):
return False
await run_blocking(storage_executor, _erase, uid, snapshot, row)

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 Reconcile the original held ledger before erasing the hold

For normal sync holds, the encrypted metadata contains the original content_id, whose stt_cap_hold_v1 ledger has pending_cap_hold_ids and deliberately no expiry. In draining/dark mode this new early branch skips _recover_row and sync_cap_holds.settle_hold, admits under an unrelated derived content ID, and then erases the only hold manifest; no retained state links the eventual batch result back to the original ledger. That ledger therefore remains held forever, duplicate syncs continue returning the stale held result, and the row never regains a TTL. Preserve a durable handoff or reconcile the original ledger before deleting the manifest.

Useful? React with 👍 / 👎.

Comment on lines +57 to 60
if existing and not (adopt is not None and adopt(existing)):
# Never take a legacy content owner, including ambiguous/expired
# Redis ownership. Its existing recovery path remains authoritative.
return {'outcome': 'busy', 'job_id': existing.get('job_id')}

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 Preserve legacy checkpoints when adopting stranded content

When a legacy attempt becomes retryable after processing some segments, its ledger deliberately retains partial_result, processed_segment_ids, and potentially already-recorded usage. stranded_adopter classifies such a row as stranded, this condition permits adoption, and the later tx.put('content', ...) replaces the entire ledger; the batch job consequently cannot skip the completed work and can repeat conversation effects and account the full speech again. Restrict adoption to rows proven to have no committed side effects, or migrate the legacy checkpoints and accounting fence into the batch owner.

Useful? React with 👍 / 👎.

or not _bounded(body['wake_token'])
):
return _malformed()
result = await run_blocking(sync_executor, run_delivery, body['row_id'], body['wake_token'])

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 provider execution out of the shared sync pool

Each delivery runs the entire provider consumer in the 16-worker sync_executor, including artifact download, local VAD, and a synchronous Modulate request whose configured timeout is 300 seconds; the consumer's 1,800-second lease confirms this is expected to be long-running. Sixteen concurrent provider tasks can therefore occupy every sync slot for minutes and starve the ordinary sync upload and Cloud Tasks pipelines mounted by the same workers service. Keep the coordinator async and offload only individual DB, storage, and provider operations to their appropriate bounded pools.

AGENTS.md reference: backend/AGENTS.md:L268-L274

Useful? React with 👍 / 👎.

Comment on lines +396 to +398
if not await _save(uid, snapshot, row, {'state': 'batch_admitted', 'batch_job_id': admitted.batch_job_id}):
return False
await run_blocking(storage_executor, _erase, uid, snapshot, row)

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 Resume erasure directly for batch-admitted hold rows

The row is checkpointed as batch_admitted before _erase deletes its blobs and finally deletes or purges the manifest. If blob deletion succeeds but the final Firestore mutation fails, the next sweep claims the surviving row, enabled_for treats batch_admitted as eligible, and admit_held tries to read the now-deleted audio before it can retry _erase; this leaves the manifest in a hot retry loop even though admission already committed. Special-case batch_admitted rows to resume erasure without rereading or readmitting the source.

Useful? React with 👍 / 👎.

Comment on lines +48 to +54
def enabled_for(row: Mapping[str, Any], mode: LegacySyncMode | None = None) -> bool:
"""cap_hold_mode == 'batch_hold' (contract (c)) while legacy is draining or dark."""
if mode is None:
from utils.sync import legacy_dark

mode = legacy_dark.current_mode()
return mode is not LegacySyncMode.ON and eligible(row)

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 Keep non-cohort holds on the legacy recovery path

In draining or dark mode this predicate returns true for every eligible hold without checking whether its owner is admitted to the batch cohort. recover_selected therefore bypasses _recover_row, but batch_pipeline_intake.admit later rejects any non-cohort owner with AdmissionDisabled; the adapter converts that into a retry, so these already-accepted holds repeat forever instead of draining through legacy or entering batch. Include the UID/cohort gate in this decision, with an appropriate draining fallback when admission is disabled.

Useful? React with 👍 / 👎.

Comment on lines 233 to +236
route = resolve_route(language, byok=byok_enabled)
# C8: with legacy draining or dark, a language Parakeet cannot serve goes
# to the batch provider-STT stage instead of the legacy fallback.
provider = mode is not LegacySyncMode.ON and route.stt_route == 'provider'

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 Attribute provider-STT usage to the actual provider

This branch sends unsupported-language units to Modulate, but BatchProjectionStore.prepare_accounting still hard-codes every batch usage update as provider: 'parakeet' in backend/database/batch_pipeline_projection.py line 243. All successful provider-STT work is therefore charged to the correct number of speech seconds but attributed to the wrong provider, corrupting provider cost and usage analytics. Carry the immutable provider_service or result words_provider into accounting instead of using the GPU default.

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Subscription-session answers (owner of utils/sync/cap_hold_recovery.py and the held-audio/backlog UX from #21488 / #22388):

1. Held-audio summary counter after hand-off. Treat the hold as no longer held the moment it is batch_admitted.

  • Decrement the held count and held seconds in the summary doc in the same transaction that marks the row batch_admitted. The summary has been an exact running total since feat: ladder v1 plans and funded processing cap (default off) #21488; the client shows "N recordings waiting" from it. Don't re-derive it later.
  • While the batch unit is in flight, the backlog state the client sees should stay processing. Derive that from the batch side, either in-flight units for the uid or the same marker the batch projection clears, rather than from the held total.
  • Once batch projection finishes, nothing more to do on the cap-hold side.
  • Retried sweeps must not double-decrement. Key it on the row's state transition (held → batch_admitted happens once), not on the call.

2. Legacy ledger row final state. A terminal batch_admitted, never transcribed/settled.

  • Store the derived batch content id on the row and keep the existing erase.
  • The row must be skipped by the recovery sweep (fix: make cap-held recovery durable across restarts #22388's cap-hold-durable-redrive), by legacy usage settlement, and by the summary backfill.
  • Re-running on a batch_admitted row is a no-op.

3. The hook in recover_selected. Agreed, with these conditions:

  • Consent stays the gate. recover_selected only runs for holds the user chose to process (backlog consent, or upgrade-fits per the 10-18 halt-at-cap ruling). The hook must not admit anything outside that selection.
  • Funding is a blocker for draining. The PR's open item says the dispatch re-check runs keyless and outside backlog_consent. Before any environment runs this at draining, batch must debit the user's funded allowance/ladder budget the same way legacy recovery does, and must hold again if the budget is exhausted mid-backlog. Otherwise held audio gets processed on Omi's dime past the cap, which is exactly what halt-at-cap prevents. Fine to merge dark at on with that open; please don't move any env to draining until lane 6/E1 closes it.
  • Lanes. The cap-enforcement cohort work (feat/stt-cap-cohort-lanes, PR coming) adds a lane scope. Recovered holds admitted via batch should count as the batch lane for enforcement, so the batch-lane cap check (which also has to move out of the GPU lock first) governs them.

Happy to re-review the last two commits once 1 and 2 are in.

Git-on-my-level and others added 6 commits October 19, 2026 17:04
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]>
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]>
@Git-on-my-level Git-on-my-level changed the title feat(batch): cap-hold rehome into batch admission (lane 8 slice 3, stacked on #22457) feat(batch): cap-hold rehome + provider-STT Firestore outbox (lane 8 slice 3, stacked on #22457) Oct 19, 2026

@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: 920a9cd9d2

ℹ️ 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 +194 to +195
if new != old:
transaction.set(ref, new)

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 Buffer the outbox write until transaction reads finish

For every provider admission, this calls raw transaction.set while the surrounding FirestoreStore intentionally buffers writes; afterward FirestoreTransaction.flush() performs privacy reads, and a multi-unit admission also reads the next outbox row. Firestore rejects reads after the first write, so these admissions return 503 instead of atomically enqueueing provider work. Buffer the outbox row through the transaction wrapper, and cover the path with the repository's strict transaction fake.

AGENTS.md reference: backend/AGENTS.md:L225-L225

Useful? React with 👍 / 👎.

Comment on lines +344 to +348
for row_id, wake_token in wakes.items():
try:
await run_blocking(db_executor, outbox.wake, row_id, wake_token) # type: ignore[union-attr]
except Exception as error:
# The row is durable; the outbox sweep re-wakes it (contract (b), invariant 4).

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 Wire the provider outbox sweeper before swallowing wake failures

When this post-commit wake fails because of incomplete task configuration or a transient Cloud Tasks error, the exception is suppressed on the promise that the outbox sweep will repair it. A repository-wide search finds FirestoreProviderSttOutbox.sweep only in its definition and tests, with no service or scheduled caller, so the row remains permanently unwoken; expired provider leases have the same problem. Wire a recurring sweep before relying on it, or propagate a retryable admission failure.

Useful? React with 👍 / 👎.

Comment on lines +187 to +188
# BYOK uploads are admitted like every other upload (David, 10-19); the
# stage never needs request-scoped keys and enrichment runs on Omi's keys.

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 Persist the BYOK decision for Parakeet jobs

When a BYOK upload resolves to Parakeet, this newly admitted path computes route.provider_reason == 'byok' but discards that route when constructing ProjectionBinding. Execution admission recognizes BYOK only through projection_binding.policy.provider_reason, so with cap enforcement enabled and no funded allowance the GPU job is re-held on every lease after the client has already received 202. Persist the immutable BYOK policy in the binding before admitting these uploads.

Useful? React with 👍 / 👎.

Comment on lines +48 to +50
'kind': OutboxKind.PROVIDER_STT.value,
'segment_id': row_id,
'owner_id': owner_id,

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 Purge provider outbox rows during account deletion

When an account is deleted after a provider row is created, the account wipe's purge_batch_owner scans the batch jobs, results, artifacts, projections, and intakes collections but never this new provider-outbox collection. Claim and sweep only close blocked rows while retaining owner_id, and acknowledged rows also have no expiry, so the raw UID remains in a global Firestore document indefinitely after the wipe reports completion. Add this collection to the retryable purge or erase/anonymize closed rows.

Useful? React with 👍 / 👎.

conversation_id=meta.get('target_conversation_id'),
client_device_id=meta.get('client_device_id'),
client_platform=meta.get('client_platform'),
intake_context={'origin': 'cap_hold', 'recording_session_id': meta.get('recording_session_id')},

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 Preserve held capture context during batch handoff

When a cap-held capture contains geolocation metadata, this handoff passes only the origin and recording-session ID into accept_upload. Batch projection obtains geolocation from the authenticated intake context, while the bypassed legacy recovery path explicitly forwarded meta['geolocation']; consequently, untargeted holds rehomed during draining or dark mode create conversations without their original location. Carry the preserved geolocation and other required intake provenance into this context.

Useful? React with 👍 / 👎.

Comment on lines +23 to +24
queue,
handler + ROUTE,

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 Pass the configured provider handler URL unchanged

When PROVIDER_STT_TASKS_HANDLER_URL is configured according to the provider-STT TaskEdge in backend/scripts/cross_service_contract.py, it already contains /v2/batch-pipeline/provider-stt/run because that edge does not set append_route=True. Concatenating ROUTE here therefore creates a doubled path ending in /run/v2/batch-pipeline/provider-stt/run, so every wake receives 404 even after the router is mounted. Either pass handler unchanged or change the deployment contract to require a bare origin.

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Re-review at 920a9cd (subscription session).

  • Summary counter: it already decrements. _save → cap_hold.checkpoint applies the remaining_seconds delta in the same transaction, and batch_admitted counts as 0. Please add a test that pins this.
  • Ledger row: terminal batch_admitted + batch_job_id is correct, not completed (that would settle legacy usage too). Please add a test that re-selecting a batch_admitted row is a no-op and is skipped by claim and the durable sweep.
  • Required fix: the batch branch skips _new_dispatch_allowed(uid) (sync_allowed / hard restriction / daily audio ceiling), which legacy _recover_row enforces. Gate admit_held on it the same way, and return False so the row stays held. The ladder-budget debit remains a blocker for draining (lane 6/E1).

…dmitted 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]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Correction to my earlier funding note: batch projection does debit transcription_seconds. The real gap for draining is timing.

  • Stale capacity in the backlog worker: processing_backlog_worker.work ~L181-205. Legacy debits synchronously per hold; batch debits only at projection. With remaining=None, consecutive holds are admitted against capacity that doesn't yet include each other.
  • Period attribution: projection runs outside backlog_consent, so a month rollover charges the new period instead of the consented one.

Details have gone to lane 6, which owns the fix. Merging dark at on is still fine.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Re-reviewed b389a5b (subscription session). All three conditions are addressed. LGTM from the cap-hold owner side.

  • The dispatch gate runs before admit_held, and the lease is still released via the finally on the gated return.
  • batch_admitted is terminal in both recover_selected and eligible.
  • The summary decrement is pinned by the StrictFirestore test.

Still standing, enforced by #22479: no environment leaves on until lane 6 closes the stale-capacity and period-attribution gaps (comment 6265912525).

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

ℹ️ 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 +302 to +303
# Provider units are funded by the provider stage, not GPU compute admission.
items.append(replace(item, audio_uri=uri, requires_compute_admission=not provider))

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 Preserve intake context for provider-routed units

When draining or dark mode selects the provider route, this sets requires_compute_admission to false, but BatchProjector.assign_parts also uses that flag to decide whether to read the authenticated intake manifest and call resolve_context. Consequently, a provider-routed upload with a recording_session_id but no explicit conversation skips recording-lineage resolution and can be attached to the closest or a newly created conversation; ordinary upload geolocation is dropped as well. Decouple manifest availability from compute admission so provider units still project their intake context.

Useful? React with 👍 / 👎.

Comment on lines +354 to +356
if route.provider_reason != 'byok' and not self.allowed(
item.owner_id, item.duration_seconds, route.provider_service
):

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 Reserve backfill capacity before provider execution

For an unsupported-language upload classified as backfill, the provider unit bypasses admission.authorize, while this check only invokes sync_allowed. The GPU path's reserve_backfill_speech call is therefore never made, so provider-routed historical uploads can issue Modulate calls beyond the per-user and global backfill speech budgets. Apply the same once-per-content backfill reservation before allowing the provider spend.

Useful? React with 👍 / 👎.

Comment on lines +320 to +321
.where(filter=FieldFilter('state', '==', OPEN))
.limit(max(1, min(limit, 500)))

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 Page the provider outbox past ineligible open rows

When the collection contains more than 500 open rows, this query repeatedly returns the same un-ordered first page and then filters future-due, recently woken, or live-leased rows in Python. A due row with a lost wake outside that page is never examined by later sweeps, so its provider job remains permanently unwoken even after a recurring sweeper is wired. Query/order by eligibility or paginate through open rows until the requested repair limit is reached.

Useful? React with 👍 / 👎.

Comment on lines +40 to +41
def _bounded(value: object) -> bool:
return isinstance(value, str) and 0 < len(value) <= _BOUNDED_ID and '/' not in value

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 Reject noncanonical task IDs at the route boundary

For an authenticated delivery with the correct three fields but a non-hex row_id or wake_token, this predicate accepts the body and FirestoreProviderSttOutbox.claim_key then raises ValueError because it requires 64- and 32-character hex values. The route consequently returns 500 and Cloud Tasks retries a permanently malformed delivery instead of returning the documented 400 response. Validate the canonical ID formats before invoking run_delivery.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 31cb000 into integration/legacy-retire Oct 19, 2026
24 checks passed
@Git-on-my-level
Git-on-my-level deleted the lr/08-cap-hold branch October 19, 2026 11:39
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…weep (lane 9, C4) (#22517)

* refactor(enrichment): move the sr- outbox into utils/enrichment (C2 slice 1)

Plan C2, swarm lane 9. Pure move, no behaviour change:

- utils/sync/reprocess.py        -> utils/enrichment/outbox.py
- utils/sync/enrichment_custody.py -> utils/enrichment/custody.py
- utils/sync/enrichment_scan.py  -> utils/enrichment/scan.py

The old paths become sys.modules aliases of the new modules, so every
importer, mock.patch target and monkeypatch keeps reaching the same module
object. A star import gives pyright the public names. Batch projection
imports the new path; the frozen prod-track files (serving.py,
routers/batch_pipeline.py, batch_pipeline/enrichment.py) keep the shim until
their PRs reach integration.

Collection, document ids, field names and the sr- task prefix are unchanged
(contract (b) invariant 7). The query-shape driver and background-task
baseline follow the moved function.

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

* refactor(enrichment): drop the test-only custody and scan aliases

Only tests imported utils.sync.enrichment_custody and enrichment_scan, so the
dead-code ratchet counts the aliases as new dead files. The tests now import
utils.enrichment.scan directly; utils.sync.reprocess keeps its alias for the
production importers.

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

* test(enrichment): import the probe modules at collection time

The fast-unit CPU guard charged utils.cloud_tasks' first import to the probe
test's call phase (0.53s > 0.30s) once this file was selected. Module-level
imports keep the assertions unchanged and the call phase cheap.

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

* fix(enrichment): own the sr- callback and absorb lifecycle fences (C2 slice 3)

Plan C2, swarm lane 9. Batch enrichment no longer imports legacy
transcription (utils/sync/pipeline.py):

- utils/enrichment/callback.py: enrich_conversation, extracted verbatim from
  pipeline._reprocess_conversation_after_update with its webhook helper,
  persistence fence and lineage sentinel. pipeline.py is frozen behind
  #21932/#20662 and keeps its copy for the non-coalescing direct path, so
  test_enrichment_callback_parity.py (a static tripwire, labelled as such)
  keeps the two bodies identical until C11 deletes the legacy one. The new
  copy logs no conversation id.
- utils/enrichment/custody.py now owns discard_blocked. The batch adapter
  re-exports it for its existing importers.
- Absorbs #21968 (lead ruling 10-19): a SyncConversationPersistenceFenced
  from the callback settles the claim as superseded. The obligation is
  retired when no newer mark landed and re-armed when one did, and the
  handler ACKs 200 instead of answering 500 to a delivery that can never win.
  Other errors keep their taxonomy. #21968's conversation_id log line is not
  carried; the event is logged without identifiers.

Failure-Class: none

Verification (local unit, serial, nice 19):
- test_enrichment_callback_fence 4 passed (fenced+unchanged -> retired;
  fenced+newer mark -> re-armed; ValueError propagates; the default callback
  is the package)
- test_enrichment_callback_parity 3 passed
- test_batch_pipeline_serving 31 passed
- test_listen_finalization_cloud_tasks 278 passed
- test_sync_reprocess_coalesce 88 passed
- test_sync_enrichment_custody 10 passed
- test_background_task_ratchet, test_llm_gateway_coverage_guardrails and
  test_generated_compute_inventory_guardrails passed
- pyright 0 errors
- test_sync_reprocess_emulator now patches the package callback (CI emulator lane)

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

* feat(enrichment): Firestore Outbox for OutboxKind.ENRICHMENT (C2 slice 2)

Plan C2 / contract (b), swarm lane 9. database/outbox_firestore.py
implements the Outbox protocol over sync_reprocess_outbox, row-compatible
with mark/run: same collection, document ids, field names and sr- names.
Additive fields: policy_id, claim_attempts, a transient summary_seen_by.

- lease_token is the per-claim owner uuid and wake_token is task_token.
  heartbeat/ack/defer/release are fenced on both (invariant 1).
- claim_key: privacy discard first (invariant 6), then demand admission,
  a stale or busy check, and a not-due re-arm that wakes itself and returns
  DEFERRED. Wake ownership follows the lead's 10-19 ruling: this
  implementation creates the tasks through the existing _enqueue.
- ack keeps today's finish rules: retire when unchanged, a dormant receipt
  when record_summary marked the lease, re-arm when the version moved.
- enqueue shares mark's CAS operation (mark_update), with explicit
  available_at and min/max coalescing (invariant 3). With tx= it writes in
  the caller's transaction and returns the wake token; the caller calls
  wake() after commit (invariants 4-5). wake() is idempotent per token.
- sweep delegates to the existing sweep with a privacy discard hook. Pull
  claim() goes through the new utils.enrichment.outbox.due_rows
  (single-field due_at index), registered in the query-shape drivers.

Batch projection's mark_enrichment now calls enqueue(tx=...) and then
wake(), using its own client for both. A backfill binding is still resolved
only for a new row (new_dispatch callable), so a coalesced append never
raises on a missing backfill env, as before.

database.outbox.outbox_for is lane 1's stub; firestore_outbox(kind) is the
implementation it should return (wiring requested from the captain).

Verification (local unit, serial, nice 19):
- test_outbox_firestore 13 passed
- test_batch_pipeline_projection 40 passed
- test_sync_reprocess_coalesce 88 passed
- test_firestore_query_shapes 481 passed
- the outside-query, runtime-witness and index-oracle suites passed
- test_listen_finalization_cloud_tasks 278 passed
- pyright 0 errors
The emulator conformance suite is lane 12's and has not landed yet.

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

* feat(enrichment): outbox_for selects the Firestore enrichment outbox

Lane 1 signed off on this one-function edit of its stub (10-19): in this
window the selector always returns the Firestore implementation; the
BATCH_JOBSTORE_MODE switch is lane 12's.

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

* feat(enrichment): /v2/enrichment/run on the outbox consumer, 409-only retries (C3)

Plan C3 / contracts (a) and (d), swarm lane 9.

- utils/enrichment/consumer.py: EnrichmentConsumer, a QueueConsumer for
  OutboxKind.ENRICHMENT (workers role; 120s lease, 30s heartbeat on every
  lease). It mirrors reprocess.run outcome for outcome, with settlement
  through the Outbox calls:
  - processed -> DONE (ack; a dormant receipt via record_summary);
  - superseded or lifecycle fence -> DISCARDED;
  - repair race -> outbox.repair;
  - live target or missing conversation -> DEFERRED +120s;
  - redirect -> custody transfer;
  - empty budget spent -> retired;
  - callback pending or empty output -> RETRY callback_pending (409; release
    keeps the wake for the queue retry).
- routers/enrichment.py: POST /v2/enrichment/run with OIDC for the
  enrichment queue (TaskEdge enrichment). It accepts the legacy
  {"kind":"sync_reprocess",...} payload, so rows bound to either handler
  drain. 400 for a malformed task; 500 only for unexpected exceptions.
- config/enrichment.py: ENRICHMENT_ROUTE (sync_handler | enrichment_queue,
  default sync_handler) is the deployment default for the policy field
  enrichment_route until E1 records it per unit. ENRICHMENT_TASKS_* is the
  queue binding. An incomplete binding falls back to the sync handler and
  is counted through record_fallback.
- valid_dispatch_binding and _enqueue accept both handler paths (contract
  (b) invariant 7).

The router mount in main.py is lane 1's. Queue spec for lane 7: enrichment,
max-concurrent 50, 25/s, backoff 10-300s, unlimited attempts.

Verification (local unit, serial, nice 19):
- test_enrichment_route 12 passed (409 callback_pending keeps the wake;
  fence -> superseded; live defer -> new wake; 400s; stale wake -> 200;
  unexpected -> 5xx with the lease kept; route binding with fallback)
- test_outbox_firestore 14 passed
- test_sync_reprocess_coalesce 88 passed
- test_cross_service_deploy_contract and test_background_task_ratchet passed
- pyright 0 errors

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

* fix(enrichment): match moved retry classes so callback-pending stays 409

#22371 classifies expected enrichment retries by (defining module, class
name). #22431 moved FirstSummaryCallbackPending to utils.enrichment.outbox,
so on integration a callback-pending delivery fell through to the
unexpected branch and answered 500. That is the fast-5xx shape that
throttled the queues on 10-18 and 10-19. Match the new defining modules,
and keep the legacy pipeline fence until pipeline.py is deleted.

Failure-Class: none

Verification: test_batch_pipeline_serving 38 passed (it failed with
500 != 409 before this change on the merged integration tree).

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

* feat(enrichment): FirestoreOutbox factory with injected client, privacy check and wake

For lane 12's outbox conformance suite (build_outbox_backend('emulator')):
FirestoreOutbox(kind, client=, privacy_blocked=, create_wake=) binds every
CAS, the sweep and every wake to the injected seams. The default instance
keeps the production paths (discard_blocked, _enqueue, the shared client).
outbox._cas is the client-explicit CAS behind _mutate, and sweep takes
client=/wake= for the same purpose.

A not-due claim_key deferral leaves claim_attempts untouched (attempt stays
1 on the first real claim), as reprocess does today; there is a test for it.

Verification: test_outbox_firestore 16 passed, test_batch_pipeline_projection
40, test_sync_reprocess_coalesce 88, test_firestore_query_shapes 481,
test_sync_enrichment_custody 10; pyright 0 errors.

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

* test(enrichment): a not-due wake re-arms and answers 200 not_due

Exercises #22437's claim_key DEFERRED mapping end to end through
/v2/enrichment/run: the outbox re-arms with a new wake and the delivery is
consumed, not retried.

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

* test(enrichment): load the callback at collection time in the route tests

The fast-unit CPU guard charged process_conversation's first import to the
first route test (6.8s > 0.30s).

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

* fix(batch): recover-quarantine kill switch answers 409; legacy sr- delegates to the consumer

Contract (d), swarm lane 9:
- /v2/batch-pipeline/recover-quarantine returned 503 for "recovery
  disabled" (host or owner). Cloud Tasks system-throttles a queue that
  sees fast 5xx/503 (10-18 18:14Z, 10-19 04:52Z stalls). A switched-off
  target now answers 409 {"status":"retry","reason":"kill_switch_off"}.
  Behaviour is otherwise unchanged: the intent stays prepared, nothing is
  spent, and the queue retries.
- enrichment_response (the legacy /v2/sync-jobs/run sync_reprocess
  delivery) runs through the C3 EnrichmentConsumer when
  ENRICHMENT_ROUTE=enrichment_queue, so one lever moves new rows onto the
  enrichment queue and drains old bindings through the same state
  machine. Default sync_handler keeps today's reprocess.run path.

Failure-Class: none

Verification (local unit, serial, nice 19):
- test_batch_pipeline_quarantine_recovery 67 passed (the disabled-host,
  -cohort and -missing cases assert 409 kill_switch_off)
- test_enrichment_route 14 passed (incl. legacy-handler delegation)
- test_batch_pipeline_serving 39 passed
- test_revision_drain_harness 7 passed
- test_cross_service_deploy_contract 18 passed

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

* feat(enrichment): enrichment-maintenance scheduler + /v2/enrichment/sweep (C4)

Plan C4, swarm lane 9. One maintenance owner for the enrichment outbox
on the workers role:

- POST /v2/enrichment/sweep (OIDC as /v2/enrichment/run) runs the outbox
  sweep (lost-wake repair, privacy discard), then summary_debt_repair.tick.
  It answers 200 with counts; a summary-debt failure is counted, never 5xx.
- deploy/scheduler/jobs.yaml: enrichment-maintenance (*/2) against
  backend-integration, lifecycle: planned until the route serves there.
  Prod ENABLED; dev PAUSED (dev shares prod Firestore, as the sequencer).

Both halves are safe beside the legacy sequencer sweep: the outbox sweep
is per-row CAS and the summary-debt tick holds its own cursor lease. The
sequencer sweep's reprocess.sweep and summary_debt_repair.tick calls
(routers/sync.py:1958) are deleted by lane 10's slice. Summary-debt
repair on backend-integration needs SUMMARY_DEBT_REPAIR_ENABLED in lane
7's ops file (today it is set on backend-sync only).

Verification: test_enrichment_route 16 passed; test_scheduler_reconcile
24 passed (job sets plus lifecycle/state pinned).

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

* refactor(outbox): selector returns the Outbox protocol; one shared provider-STT instance

Follow-up nits from lane 9's sign-off on #22467: FirestoreOutbox and
firestore_outbox are annotated as returning the Outbox protocol, which drops
the type-ignore (both implementations satisfy it under pyright), and the
provider-STT branch caches one lazily built instance like enrichment's
module singleton.

Verification: pyright 0 errors; test_outbox_firestore 16,
test_provider_stt_outbox 11, test_enrichment_route 16,
test_batch_pipeline_projection 40, test_scheduler_reconcile 24 passed.

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

* chore(enrichment): route policy for /v2/enrichment/sweep

Mirrors /v2/enrichment/run: service OIDC, internal task surface, no rate
limit, sync_job timeout class, conversations data domain.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…dow (ladder debit) (#22513)

* feat(funding): cap-hold units handed to batch are charged without a stale window

Subscription ruling 10-19 on #22467 (cap-hold rehome). This closes the
cap_hold_ladder_debit draining precondition (#22479).

A: legacy recovery debits the ladder budget synchronously, but a hold
handed to batch is debited only when projection commits. The backlog
worker therefore checked the next candidate against stale capacity, and
with remaining=None a whole page overshot (60-unit allowance, three 40-unit
holds: 3 admitted, now 1).
- recover_selected reserves the hold's units (the worker's own candidate
  units) before the hand-off is durable.
- work() subtracts open reservations for the current period from
  capacity().
- A reservation settles when the batch outcome is known. Projected means
  the usage is committed atomically with the ledger; briefly both count,
  never neither. Failed or abandoned releases it. A 6h TTL releases it
  with an error log and a counter.
- Previous-period reservations never shrink the new month.
- The real job lease serializes two workers for one owner; a test proves
  it.

B: cap-hold admission carries usage_period (the funded choice's month).
Projection backdates the hourly stamp to that period's last second only
across a rollover, never forward. Transcription has no day rollup, and
the month query reads the doc id/year/month from the stamp. Usage
sessions re-read a closed month in full.

C: a test asserts the cap-hold path (accept_upload) never builds a
native_record binding, which would skip the usage write.

Lane 8 signed off on the edits in its files (recover_selected,
intake.accept_upload usage_period, its hook test expectations). Worker
test harnesses stub the reservation read; the new behaviour is covered in
test_cap_hold_batch_debit.py.

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

* refactor(funding): pyright-clean reservation arguments

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

* feat(funding): never release a still-pending cap-hold reservation by age

Subscription session review of #22513 (PR comment 6270782314). A batch job
that is still pending past the threshold is slow, not lost; a lost job
already reads as abandoned. Releasing it would let the backlog worker
over-admit while batch still owes the debit, which reopens gap A.

Such a reservation is now kept and still counted. It is marked stale once,
with an error log and omi_cap_hold_reservations_released_total{outcome=
"stale"}. Release happens only on projected, failed or abandoned.
Other-period entries stop counting at once and are pruned after 7 days.

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