Skip to content

v3: fast finish long and multi-unit recordings in concurrent chunks (SCA-4434) - #26344

Merged
Git-on-my-level merged 16 commits into
mainfrom
lane/ff-long-multi
Nov 26, 2026
Merged

Git-on-my-level merged 16 commits into
mainfrom
lane/ff-long-multi

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

DESIGN:

SCA-4434 Lane A. Goal: 95% of deliberate v3 Finishes show a first Home card within 60 s. David approved the extra STT spend at about 23:45Z on 2026-11-25. This revision answers the Owners DESIGN review at 83ea3fe the independent reviews at 9397a50, cc33310, 4b89d6f (SHIP) and 34222fe (SHIP, with one P2 and four P3s fixed here), 3a75ec5 (SHIP; the Owners-required P3-a privacy fix and P3-b to P3-e are in this head), and the Owners and Release design changes on SCA-4434 (02:23Z and 02:25Z on 2026-11-26).

What it reads and writes.

  • The fast first transcript (backend/utils/conversations/v3/fast_finish.py) reads the same retained audio packs from GCS it reads today.
  • It writes the same provisional transcript through update_conversation_segments, fenced inside its transaction, and then the same manual-end cut.
  • Nothing new is stored in Firestore. Admission no longer reads the conversation row before the pass; the pass reads it once (one fewer Firestore read per Finish).
  • New in Redis: one counter per UTC day, v3_fast_finish:long_audio_seconds:<day> (26 h TTL), for the fleet-wide long-recording budget. Only long passes touch it: one GET before a slot is taken, one INCRBYFLOAT+EXPIRE pipeline to reserve, and one INCRBYFLOAT to settle, all on a client with 1 s connect and read timeouts. Cloud Run backend services already get REDIS_DB_HOST from gcp_backend.yml, and v3 code already uses database.redis_db.

One end-to-end deadline: 45 s from record admission (PASS_DEADLINE_SECONDS). That leaves about 15 s of the 60 s first-card budget for the write, the builder and Home.

  • Where the clock starts. Both the 60 s budget and WALL_SECONDS start at record admission, when _manual_finish_admitted runs (backend/utils/batch_pipeline/live.py:449), not at the Finish tap. The time from the tap to admission (upload, seal, admission) is outside both. The production readback below (Finish to first visible card) is measured from the tap and includes it.
  • What counts. Slot wait, every Firestore call (refresh, funding, privacy, the post-chunk refresh, write and cut), every retained-audio reference read, both language probes, chunk queue wait, provider requests and one retry.
  • How each part is bounded.
    • Every Firestore call of a chunked pass is bounded (Owners' blocker; short passes too). The pass runs each call on a small dedicated pool (fast_finish_io, 8 workers) and waits only until its bound: the deadline for the row refresh, funding and privacy (the language probe's privacy check included), and WRITE_GRACE_SECONDS (1.5 s) past it for the post-chunk refresh, the transcript write and the cut. Past its bound the call is abandoned (cancelled if it has not started; a running one ends on the client's own timeouts), the pass yields deadline and the slot is released within the deadline plus 2 s. Reads accept timeout=, but firestore.transactional commits do not (the installed client's Transaction._commit takes no timeout), so abandonment is used uniformly.
    • The write is fenced, and the cut never follows an abandoned write. The default writer's in-transaction guard refuses a transaction body that starts, or reruns after contention, past the bound. It checks the time again after the fence's own reads (34222fe P3), so nothing is written. The pass calls the cut only after the write returned True inside its bound. A commit already sent when the pass stops can still land, but only without a cut from this pass. Because the transaction read the conversation document, a cut or lock committed after that read either waits behind the commit or aborts it; on the rerun the guard refuses. Serial kill-switch passes keep today's unbounded calls and the bare fence.
    • The pass checks the deadline before every reference it reads, including several references inside one chunk.
    • Each reference's storage metadata and download timeouts are capped to what is left (read_reference(read_budget=ArtifactReadBudget(deadline, ...))). The serial kill-switch path keeps today's 30 s and 60 s.
    • Under verification_stt_deadline, a provider request's connect, pool, write and read timeouts share what is left (budget_timeout) instead of each taking all of it.
    • Language probes are bounded as a whole (34222fe P2). The vendor probe and the self-hosted gate keep each part of their own timeouts (connect 2 s; read, write and pool 8 s and 6 s), each capped to what is left (probe_timeout); with 40 s left the gate keeps 2 s connect and 6 s read. Because those parts add up, and an httpx read timeout is per read, the whole language resolution also runs on fast_finish_io and is abandoned at the deadline, so the pass stops as deadline and the slot is released within the deadline plus 2 s. A probe with under PROBE_MIN_SECONDS (3 s) left is skipped and the row's language is kept; the pass goes on. The time is checked before the privacy read, so an abandoned resolution makes no reads (P3-b), and again after it. An abandoned probe that already passed privacy may still finish in the background; its result is dropped and its audio was charged when it was allowed.
    • Chunk send minimum (P3-e): a chunk's first request is sent only with at least CHUNK_SEND_MIN_SECONDS (5 s) left. With less it would almost certainly time out, so it is not paid for and the pass yields deadline. The retry keeps its 10 s minimum.
    • That context also turns off the provider's own retry and Soniox credit failover for these requests. Batch keeps both.
  • At the deadline the pass cancels its queued chunks, waits at most STOP_GRACE_SECONDS (2 s) more for running ones, writes nothing, releases its slot and yields to batch with the bounded outcome deadline. A request still running then ends on its own timeouts, and its result is dropped.
  • An early stop (provider_error, privacy_blocked, audio_error) sets a stop flag. No running chunk sends another request or retry, and a chunk checks the flag again after its privacy answer, just before it is charged and sent. Queued chunks are cancelled, and the slot is released as soon as the requests already in flight end.

Short and long, against the deadline. A pass is long only when its audio exceeds 20 minutes (MAX_SECONDS), never because of its chunk count.

  • A short pass keeps 4 chunks in flight, whatever its chunk count. Up to about 19.8 minutes is one round. A 19.9-minute unit (5 chunks) or a six-minute Finish split into six units takes two rounds, still on the short slots.
  • A long pass keeps 3 in flight and is capped at 9 chunks: three rounds, up to about 44.6 minutes.
  • A 2-hour recording is 25 chunks, about nine rounds of 3, so it returns too_long before any read or spend.

Fairness.

  • Length, canary and daily-cap refusals are decided from the units alone, before any slot is taken (fast_finish.screen). A Finish they refuse is counted as too_long, long_canary or long_cap, never busy, and never holds or waits for a slot.
  • Short and serial passes share two pass slots. A long pass takes its own single slot.
  • A short Finish waits up to 10 s, inside its deadline, for a slot instead of answering busy.
  • On the 6-worker fast_finish_chunk pool, a long pass's 3 in flight always leave 3 workers for short Finishes.
  • Memory per process: at most 11 chunk buffers (about 106 MB), plus one per pool worker for a request a stopped pass left running, plus one decoded pack per pass. This is independent of recording length. A cancelled chunk job waiting in the pool's queue now drops its buffer at once (34222fe P3), so queued cancelled jobs hold no audio. The per-chunk privacy check runs on the chunk pool itself, not on fast_finish_io. During a Firestore brownout a started chunk can sit in that check holding its buffer until the coordinator's own bound (deadline plus 2 s) releases the slot; the check then ends on the client's timeouts. In that window the bound is soft by at most the six pool workers' buffers.

Privacy at every send.

  • Privacy is asked before any audio is read, as before.
  • It is asked again inside every chunk job just before its provider request and before its retry, so a chunk that waited in the shared pool's queue is asked when it actually starts.
  • It is asked right before the language probe posts audio to the vendor (Modulate language ID) or the self-hosted classifier (before_probe / before_self_probe).
  • A refusal stops the pass. Cancellation stops queued work. A request already dispatched may finish, but its result is never written. The in-transaction fence on the write is unchanged.
  • One denial ends the pass (Owners, SCA-4434 03:36Z; review P3-a; race closed after the afb7e49 review P3-1). The pass's privacy authority is sticky, with the denial held in a threading.Event because chunk jobs on several pool threads set and read it. What the code guarantees: when any check refuses or errors, the denial is recorded before that check returns. From then on every later check answers False without asking, including the self-hosted (shadow) gate's, the vendor probe's, every chunk dispatch and every retry. A check whose read was already in flight answers False when it returns, whatever it read. Each chunk reads the denial again immediately before it is charged and sent, alongside stop. So no probe of either kind, chunk request or retry starts after a denial is recorded, and the pass ends privacy_blocked. The only send it cannot recall is a request that had already started before the denial was recorded; its result is never written.

Firestore per Finish.

  • Privacy is one check before the audio plus one per chunk dispatch, per retry and per language probe, instead of one per unit.
  • That is the same as today for a Finish of 5 minutes or less (2 checks), and 1 to 4 more for longer short Finishes.
  • A canary long Finish costs 6 to 11 checks plus its two refresh reads (one before the chunks, one before the write), the funding gate and one write. Admission's own extra read of the row is gone, so every Finish reads it once fewer than before.
  • Each check is one batch-privacy transaction on the owner's privacy document. At about 190 Finishes a day that is an estimated few hundred to about 1,000 extra reads a day, and about 16 extra writes a day (transcript plus cut wake for canary long Finishes). This is far below the 10M/day review line.

Provider audio-seconds per Finish.

  • Each Finish costs its own audio, plus 3 s per fixed cut (silence cuts add nothing), plus a resend of any chunk that fails once, plus at most 30 s for a language probe when the language is undeclared.
  • Up to 20 minutes this is under 1% above today.
  • The added spend is long Finishes, about 32 a day in the 12 h baseline:
    • At the 25% canary: about 8 a day, about 4 audio-hours a day at a 30-minute mean.
    • At 100%: about 11 to 16 audio-hours a day, the approved "about 11+".
    • Fleet bound: CONVERSATIONS_V3_FAST_FINISH_LONG_DAILY_SECONDS=7200 (kept; Owners confirmed 7,200 s) per UTC day across the fleet, in the shared Redis counter above, so it survives scaling and restarts.
      • Reserve: a long pass reserves the most it can send: every chunk twice (its one retry) plus one 30 s probe clip, about 3,666 s for a 30-minute Finish. It uses INCRBYFLOAT, and the reservation is taken back at once if that went over the cap. Retries therefore can never push the day past the cap (34222fe P3). While passes run, the counter reads high. Against the 7200 s default only one 30-minute pass's reservation fits at a time across the fleet (two would need 7,332 s), and after it settles to about 1,818 s the next one fits. At the 25% canary (about 8 long Finishes a day) a concurrent second long Finish is rare and falls back to batch as long_cap; raise the cap if the readback shows that happening.
      • Settle: the reservation is settled down to the audio actually sent (overlaps, retries and the vendor probe included; chunks never sent are refunded). The settle runs in the background on fast_finish_io, after the slot is released, and is best effort.
      • Under the deadline (34222fe P3): the reserve is one pipeline round trip on a client with 1 s connect and 1 s read timeouts. A pass reserves only with at least RESERVE_MIN_SECONDS (3 s) left, so the reserve ends before the deadline. With less left it refuses as deadline and reserves nothing.
      • Fails closed: when Redis errors or takes over 1 s, the long pass is refused as long_cap. Two passes racing for the last room may both be refused, but neither can push the day over.
      • The in-process counter is removed. The percentage is the operative limit; the cap is the hard backstop, and the 24 h report reads both the counter and audio_seconds_total.

Provider capacity.

  • Per backend-integration process, concurrent prerecorded requests from fast finish rise from at most 2 (one serial request per pass slot) to at most 6, the chunk pool. In prod that pool resolves to STT_PRERECORDED_MODEL=parakeet,modulate-velma-2.
  • Fleet worst case is 6 times the process count. I have no measured hosted Parakeet capacity figure to state, so the stop thresholds below watch its 429/5xx rate and latency.
  • With one retry per chunk, a pass fails only when a chunk fails twice. At a 2% request failure rate, a 9-chunk pass loses about 0.4% instead of about 17% with no retry.

Canary and stop rules.

  • Exposure. Long Finishes (over 20 minutes) go through the chunked path for CONVERSATIONS_V3_FAST_FINISH_LONG_PERCENT=25 of owners (salted uid bucket; outside it, long_canary), within the daily cap above (past it, long_cap). Finishes up to 20 minutes are not gated: their audio is unchanged.
  • Stop expansion or roll back (LONG_PERCENT=0) if any of these holds in the first 24 h:
    • long-path audio (audio_seconds_total{path="long"}, which includes the vendor probe clip, the same audio the cap charges) is over 6 h a day;
    • deadline plus provider_error is over 30% of long passes;
    • chunk queue p95 is over 5 s;
    • busy is over 5% of passes;
    • prerecorded provider 429/5xx on backend-integration is over twice its baseline.
  • Kill the whole chunked path (CHUNKED=off) if short-pass written share falls below its baseline, or short-pass provider_error or deadline is over 5%.
  • 24 h report after serving:
    • sum by (path) (increase(omi_conversations_v3_fast_finish_audio_seconds_total[24h])), converted to audio-hours and multiplied by the provider contract rate for the cost, checked against GET v3_fast_finish:long_audio_seconds:<day>;
    • outcomes by label;
    • wall p95;
    • chunk queue p95;
    • provider error rates.
  • Expand to 100% only after a clean report.

Production number that proves it (same 12 h prod window and query as the baseline, after serving):

  • Fast-card share of Finishes at least 95% (baseline 55/96).
  • Finish to first visible card, wall-clock p95 60 s or less.
  • Supporting readback: omi_conversations_v3_fast_finish_wall_seconds p95 (from record admission, not the tap; every written pass) under 45 s, plus {outcome}, chunks, chunk_seconds, chunk_queue_seconds and audio_seconds_total{path} (vendor probe included).

Rollback.

  • CONVERSATIONS_V3_FAST_FINISH_LONG_PERCENT=0 stops long passes only.
  • CONVERSATIONS_V3_FAST_FINISH_CHUNKED=off on backend-integration restores one serial request per unit, the 20-minute cap and today's slot behaviour.
  • Both are config changes. Provisional segments already written are replaced by the batch record projection as usual. To roll back the code, revert this PR.

Failure-Class: none

What changed and why

  • Split. chunk_plan produces chunks of 5 minutes or less. A cut goes in a retained-audio silence of at least 1 s near the even length. Otherwise it falls at the even length with a 3 s overlap. The remaining audio is shared evenly.

  • Stitching (re-review P3.1). At a fixed cut, the earlier chunk owns lines that start before the overlap's middle. Every later line that starts before the earlier chunk's last line ended is compared against it (join).

    • Words, which carry their own timing, go by time.
    • Utterances (Parakeet and Modulate return utterances lasting seconds, with no word timings) go by text (seam). Where the head of the later text repeats the end of the earlier text, the repeat is dropped. A clipped word is allowed on either side (the earlier chunk's last, the later chunk's first), and the clipped fragments are dropped too. Otherwise each such line loses the share of its tokens that falls before the earlier chunk's last end.
    • Parakeet's [0, 0] fallback spans its whole chunk instead of being dropped.
  • Long versus short by duration, not chunk count (re-review P2): pass_class and the audio_seconds_total path label both use more than 20 minutes of audio.

  • Screening before any slot (re-review P3.5): fast_finish.screen runs in live.py before slot acquisition and again inside the pass.

  • Language route once per pass. pre_recorded.prerecorded_bytes_route (kept in pre_recorded.py, where its local batch_language import already was) now takes before_probe / before_self_probe. prerecorded_from_bytes keeps its behaviour and takes an optional route.

  • Deadline module (cc33310 review P3.4): verification_stt_deadline, its ContextVar, budget_timeout and probe_timeout live in the new leaf module utils/stt/prerecorded_deadline.py. It imports no other utils.stt module, so pre_recorded, batch_language and language_gate import it at top level with no cycle, and pre_recorded.verification_stt_deadline is re-exported unchanged. fast_finish imports pre_recorded, prerecorded_deadline and batch_language.MAX_PROBE_SECONDS at top level and adds no function-local imports (only live.py imports fast_finish, lazily, as before).

  • Hard wall (9397a50 P3.4, cc33310 P2):

    • budget_timeout makes the request phases share one budget. This tightens the speaker-tag verifier's verification_stt_deadline the same way, since it was the same per-phase issue.
    • probe_timeout caps each part of the vendor probe's and the self-hosted gate's own timeouts to what is left. Under no caller deadline both keep their defaults.
    • Reads are bounded per reference, and every Firestore call is bounded by abandonment (see DESIGN), with the write fenced in its transaction.
    • The stopped-pass wait is bounded to the deadline plus 2 s. An early stop blocks further dispatches and retries and returns when the in-flight requests end (cc33310 P3.3).
  • No leaked reservation (cc33310 P3.2): row['started_at'] is read before LONG_BUDGET.reserve, so a row without it returns error with nothing reserved.

  • Small fixes from the 3a75ec5 review: the get_fast_finish_io_executor docstring now says the pool also runs the language resolution and the background budget settles (P3-c). A chunk job takes its buffer with holder.pop() inside try/except IndexError, so a holder the stopped pass emptied at that moment reads as abandoned (P3-d).

  • Daily cap by audio sent, fleet-wide (9397a50 P3.3; Owners and Release). It is a shared Redis counter per UTC day that fails closed; the in-process counter is gone. The flag registry, overlay comment, runbook and change note say it is a fleet bound. AUDIO_SECONDS{path} includes the vendor probe clip, so the readback and the cap count the same audio.

  • Unchanged from the previous revision: the deadline, slots, window, privacy at dispatch, one retry and the canary. New bounded outcomes are deadline, long_canary and long_cap. Metrics are unlabelled histograms for chunks per pass, chunk seconds, chunk queue seconds and wall seconds, plus an audio-seconds counter labelled path=short|long, all in the cloud_run_gmp_sync.yaml keep rule.

  • Flags.

    • CONVERSATIONS_V3_FAST_FINISH_CHUNKED: ops_kill, declared on prod backend and backend-integration.
    • CONVERSATIONS_V3_FAST_FINISH_LONG_PERCENT: rollout, with a dated ramp to 2026-12-10, declared 25 on prod backend-integration.
    • CONVERSATIONS_V3_FAST_FINISH_LONG_DAILY_SECONDS: config, declared 7200.
    • All are registered in config/feature-flags.yaml and deployment-setting-classification.json. runtime_env.yaml and the registry are regenerated.
  • Multi-unit Finishes (8 units or fewer) are written in one pass, and the cut is stored only after the whole transcript is written, so no partial window can lock.

  • Pipeline-lab stand-in. With CHUNKED on by default, main's admission stand-in handed the pass a unit with no retained references. The chunked plan was empty, so the pass ended empty before any STT call, and audio_single_recording_finish, finish_double_tap and finish_single_recording_fast failed (measured at c7c0042). Now the stand-in gives the unit one lab reference over the recording, which live.read_reference reads as silence. ops.install scripts the chunked path: _transcribe_words answers each chunk with the scripted lines in its window and counts transcribe_calls, and prerecorded_bytes_route is replaced, so no language probe runs. CHUNKED stays on in the lab, and the serial kill-switch stub is unchanged. Fast-finish segments carry uuid4 ids that summarisation prompts cite. The lab's fake LLM gateway seeds its answers from the prompt, so it now renames random UUIDs in first-seen order before seeding (the rule determinism.py already applies to run artifacts). Its answers then repeat, and the repeat comparison is unchanged. Harness only; no production code changed.

Known limit: diarization labels are per chunk, so the same provisional SPEAKER_00 in two chunks may be two different people. Provisional rows claim no speaker number, and the canonical transcript replaces them.

Overlap with open PRs (for Release ordering)

None of #26332, #26335 or #26336 had landed. Separately, main had moved 17 commits and conflicted with this branch in backend/deploy/cloud_run_gmp_sync.yaml (main edited the same keep regex), so origin/main at 220610c was merged in, and again at 3e42abf (the same keep-regex conflict, resolved the same way). It was refreshed onto repaired main at afab956 (after #26382) with no conflicts. The conflict was resolved by taking main's rule and keeping this PR's fast-finish chunk-metrics alternative; runtime_env.yaml and the registry re-render unchanged. git merge-tree of this head with each PR head:

  • SCA-4489: Measure deliberate v3 Finish to first Home summary #26332 (SCA-4489, Finish-to-Home SLI). It overlaps on four files:
    • Textual conflicts in config/feature-flags.yaml and backend/docs/feature-flag-registry.md only. It inserts CONVERSATIONS_V3_FINISH_HOME_SLI right above CONVERSATIONS_V3_FAST_FINISH, beside this PR's three new rows. Resolve by keeping both rows, then re-render the registry.
    • backend/utils/batch_pipeline/live.py merges cleanly. Its hunk is @@ -433,13 in _manual_finish_admitted: it imports finish_home_sli and calls observe_route(uid, conversation_id, 'batch') before single = .... This PR changes the same function: the deadline at entry, the bounded read, screen before slot acquisition, and row=None passed to run.
    • backend/utils/conversations/v3/fast_finish.py merges cleanly. Its hunk is @@ -353,6 in _run: observe_route(..., 'fast') after if written is False: return 'superseded' and before the cut. This PR rewrites _run (bounded calls, fenced write, _bounded(cut, after)); the merged call lands in the same place, after the write and before the cut.
    • Order: either PR can go first. If observe_route does any I/O, it sits outside this PR's Firestore bounds and should be cheap or bounded.
  • SCA-3684: Pin speaker evidence off for production readers #26335 (SCA-3684): prod.overlay.yaml, runtime_env.yaml, deployment-setting-classification.json and the registry merge cleanly. Its overlay hunk @@ -1919,6 is the closest to this PR's backend-integration env block. Re-run compose_runtime_env.py and render_feature_flag_registry.py after whichever lands second.
  • SCA-3499: Retire the shared-live GPU pull #26336 (SCA-3499): its conflicts are in the registry, the flag file and backend/charts/batch-pipeline-worker/templates/deployment.yaml, all against content already on main (its base predates the shared-live retirement and the SCA-3503 retirements), not against this PR's rows. Its overlay hunks (@@ -972/-1352/-1743/-2131) do not touch the fast-finish env lines. Same regeneration step.

Product invariants affected

  • INV-MEM-4: not affected. The only shared-code changes are:

    • two lazily built executor getters in backend/utils/executors.py (fast_finish_chunk, fast_finish_io);
    • a behaviour-preserving prerecorded_bytes_route helper inside utils/stt/pre_recorded.py;
    • the deadline context moved into utils/stt/prerecorded_deadline.py, with the deadline-shared request and language-probe timeouts.

    No memory intake, consolidation or promotion path changes.

How it was verified

All commands ran from backend/ in the lane worktree on lane/ff-long-multi, through omi-heavy run with bounded timeouts. Layer: hermetic unit tests. There was no live provider call and no deploy.

  • bash test.sh tests/unit/test_conversations_v3_fast_finish_chunked.py tests/unit/test_conversations_v3_fast_finish.py: 112 and 115 passed, 3 of 3 runs. New for the 3a75ec5 review:

    • afb7e49 review P3-1 and P3-2, deterministic with events and a barrier, no sleeps. The denying chunk is held where it raises _Refused until the others decide, so the coordinator cannot set stop first and hide a missing check:
      • three chunks dispatched at once. Chunk A's privacy read errors, while chunk B's read, already in flight, answers True only after the denial is recorded. B (and C) send nothing, and the pass ends privacy_blocked. This fails without the two new checks, 3 of 3 runs;
      • three chunks whose first requests all go out (barrier), then all fail. The first retry check errors, and the other chunks' retry reads answer True after the denial. Only the three first requests are ever sent. This replaces the single-chunk retry test and fails with the sticky wrapper removed, 3 of 3 runs (as does the first test);
      • the reviewer's scratch race test (30 runs), run here as a temporary uncommitted copy, passes 30 of 30 with the fix and fails 17 of 30 without the new checks.
    • the shadow gate's privacy check refuses, and separately errors, then every later check would allow. The route asks the shadow gate, the vendor probe, then the gate again. All three answer False, privacy is asked only twice (before the audio and by the shadow gate), and no probe is sent. No chunk is uploaded, no probe audio is charged to AUDIO_SECONDS or the fleet budget, and the pass ends privacy_blocked. Both cases fail without the fix;
    • a resolution abandoned at the deadline makes no privacy read when it later reaches the probe;
    • with under 3 s left the probes are skipped without a privacy read;
    • a chunk is not sent with under 5 s left (deadline);
    • tests that use a sub-second deadline on purpose set CHUNK_SEND_MIN_SECONDS to 0.

    New for the 34222fe review:

    • a vendor probe and a self-hosted gate that are slow in every phase. The reviewer's 8 s case is scaled to 0.8 s left: each phase runs to its capped timeout, about 2.4 s in total. The pass returns deadline before the deadline plus grace in both cases. Both fail without the outer bound;
    • with under 3 s left, both probes are skipped after the privacy check, the row's language is kept, the pass goes on and no probe audio is charged;
    • with the cap set to exactly one reservation (2 × 1,818 + 30 s), a pass that retries every chunk writes and stays within the cap, and a racing reservation during it is refused;
    • a long pass with under 3 s left returns deadline and reserves nothing;
    • a Redis settle that takes 1 s does not hold the pass (it returns in under 0.8 s), and the settle still lands;
    • the write guard raises after a fence whose reads outlast the bound;
    • when the pool is blocked, every cancelled queued chunk job's buffer holder is empty after the pass stops.

    New for the Owners and Release changes:

    • through _manual_finish_admitted with a 0.6 s deadline (at least 0.5 s for test_real_clock_budget_ratchet) and a Firestore row refresh that stalls 5 s: the pass counts deadline and both slots are free again within the deadline plus 2 s;
    • a transcript write whose commit stalls past its bound: the pass returns deadline within the deadline plus 2 s and calls no cut. When the stalled transaction body then runs, its guard raises and nothing is written. A write inside its bound runs fence, then write, then cut, in that order;
    • fleet budget on a shared fakeredis: reserve then settle up (retry and probe), full refund of a pass that sent nothing, over-cap reservations taken back at once, one key per UTC day with a TTL of at most 26 h;
    • two simulated processes (two budget objects on one Redis): after process A's long pass, process B is refused long_cap;
    • Redis down: screen, run and reserve refuse long passes as long_cap (also when only the reserve pipeline fails), and short passes still write;
    • a chunk whose privacy answer arrives after the pass stopped sends and charges nothing. This test fails without the new stop check;
    • with 40 s left the gate keeps 2 s connect and 6 s read; with 3 s left every part is at most 3 s; the vendor probe keeps (2, 8, 8, 8) with 40 s left;
    • test_conversations_v3_fast_finish.py: the pass is handed no row and reads its own (live.py's duplicate read removed); an undecodable row read by the pass is ineligible.

    New for the cc33310 review:

    • through _manual_finish_admitted with a 0.6 s deadline (at least 0.5 s for test_real_clock_budget_ratchet) and a storage read that stalls until its timeout: the read's timeout is capped to at most 0.6 s, the pass counts deadline, and both slots are free again within the deadline plus 2 s (without the read budget it is a 30 s read);
    • the serial kill-switch path still reads without a budget;
    • one 300 s chunk over ten packs, each read 0.15 s, with a 0.2 s deadline: at most two references are read;
    • a slow refresh, funding or privacy call ends the pass as deadline with no audio read;
    • a long row with no started_at returns error with nothing left reserved;
    • after an early provider_error the chunks still running take no retry and the pass returns in under 1 s (the deadline is 45 s); the same holds after a privacy refusal at one chunk's dispatch;
    • the self-hosted gate sends nothing once the deadline has passed and is unchanged without a deadline;
    • AUDIO_SECONDS{path="long"} includes the 30 s vendor probe clip.

    New for the 9397a50 review:

    • both review seam probes, which fail before this fix: "epsilon zeta" is no longer duplicated, and a clipped "o …" head keeps "store" while dropping "sto";
    • words joined by time;
    • a six-minute 6-unit Finish and a 19.9-minute single unit stay short (window 4, path=short) and run while a long pass holds the long slot;
    • a non-canary or over-cap long Finish is counted long_canary or long_cap with the long slot busy, never busy;
    • the language probe refused by privacy at send, with nothing charged;
    • an allowed probe charged at 30 s;
    • the cap charged with a retry (the sum of all requests sent);
    • a stopped pass returns in under 1 s while its request runs 1.5 s;
    • budget_timeout, verifier and probe timeouts summing within the deadline.
  • Related suites: 104 files (adding test_redis_db_client_factories.py), After the refresh onto afab956, 150 files passed: the 104 related files (the chat test included, repaired by test: restore backend main suite contracts #26382), the pipeline-lab tests (main's new finish_privacy_refused_fast_finish scenario included) and the ratchet. Earlier, on the tree merged at 3e42abf, 103 passed. test_chat_stream_error_fallback.py fails on the merged tree with ImportError: cannot import name 'speaker_evidence_erasure' from 'utils.observability'. That comes from main's Measure speaker evidence write fences and post-erasure sweep outcomes #26311 (utils/metrics.py imports the new module while the chat test harness stubs utils.observability). Every file in that import chain is identical to origin/main, so it is a main breakage, not this PR's; it passed before the merge. They cover pre-recorded STT, batch_language, the language gate and the serving language probe, speaker-tag verification, teaching placement, batch_pipeline_live, executors, runtime env compose/validator, projection pump deploy target, flag budget, background task ratchet and others. test_empty_capture_recovery.py was left out: it fails on this host only because the native Opus library is missing.

  • Pipeline lab at 98c2321, CI's command (scenario run --jobs 4 --repeat 2 --json --stt replay), all 13 scenarios with CHUNKED on: 12 passed, and finish_after_second_close is its committed strict xfail. 0 nondeterministic and 0 repeat differences. The five scenarios that reach summarisation on fast-finish words (audio_single_recording_finish, finish_after_reconnect_late_transcript, finish_double_tap, finish_next_opens_before_close, finish_single_recording_fast) each end with B written, with a gist and 1 action item. New test: the fake gateway gives one answer when only random ids in the prompt differ, and a different answer when the words differ. With the renaming disabled, fresh ids gave equal answers 0 of 20 times. The determinism, LLM-proxy and fake-upstream-oracle tests: 36 passed. Earlier, at 729f357: A guard run reached the real STT provider zero times and stopped any call to it. It counted each _transcribe_words chunk stub call and each serial _transcribe call:

    • audio_single_recording_finish: chunk stub 1, serial 0, real provider 0; fast_finish B written; vendor stt 2/2 (1 chunk plus 1 cassette play);
    • finish_after_reconnect_late_transcript and finish_after_long_reconnect_gap: chunk stub 1, serial 0, real provider 0; B written; stt 1/1;
    • finish_after_second_close: no fast-finish pass runs (the xfail's product gap: B never gets the Finish), so 0 calls of any kind, stt 0/0;
    • finish_double_tap and finish_single_recording_fast: B written, stt 1/1.
      The two fast-finish suites plus test_pipeline_lab_scenario.py and test_pipeline_lab_stage_reuse.py: 294 passed.
  • pyright on the changed modules (fast_finish, live, pre_recorded, prerecorded_deadline, batch_language, language_gate, executors): 0 errors. pre_recorded.py stays at its 1659-line base. render_feature_flag_registry.py --check-parsers passed, and compose_runtime_env.py regenerated the runtime env. scan_async_blockers.py, scan_import_time_side_effects.py and check_module_stub_pollution.py all reported 0 violations.

🤖 Generated with Claude Code

…SCA-4434)

Split every unit of a manually finished v3 recording into chunks of at
most five minutes (at retained-audio silences where possible, otherwise
at even offsets with a 3 s overlap), send them to the prerecorded
provider concurrently and stitch them in order, keeping each word once
by the chunk that owns its midpoint. The fast-pass bound rises from 20
minutes to two hours. Memory per pass stays explicit: at most four
chunk buffers in flight plus one decoded pack. Chunk requests run on a
new six-worker fast_finish_chunk pool; _FAST_FINISH_SLOTS still bounds
whole passes.

Privacy, funding, eligibility, the in-transaction fence, superseded and
already_started handling are unchanged; one failed chunk stops the pass
and the admitted batch job delivers. New unlabelled histograms count
chunks per pass, seconds per chunk request and wall seconds of a written
pass.

CONVERSATIONS_V3_FAST_FINISH_CHUNKED (ops kill, default on, declared on
for prod backend and backend-integration) restores one serial request
per unit and the 20-minute cap when off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T16:30:51.800066Z 729f357 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.

Git-on-my-level and others added 3 commits November 25, 2026 20:07
…(SCA-4434)

Owners DESIGN review and independent review of #26344 at 83ea3fe:

- One 45 s end-to-end deadline from record admission covers slot wait,
  reads, queue wait, provider requests and one retry; provider timeouts
  are capped to it. Past it the pass cancels queued chunks and yields to
  batch as `deadline`. Long passes keep three chunks in flight and stop at
  nine chunks (about 44.6 minutes, three rounds); longer recordings are
  refused before any spend.
- Long passes take their own slot; short Finishes wait up to 10 s for a
  slot instead of answering busy, and always find three pool workers.
- Privacy is asked again inside each chunk job just before its provider
  request; a chunk queued while consent changed is never sent.
- Utterance-shaped provider output is owned by start time and trimmed at
  the seam (text match, else the share heard twice), so fixed cuts no
  longer repeat text; Parakeet's [0, 0] fallback spans its chunk.
- The language route is resolved once per pass and reused by every chunk;
  each chunk is retried once if time allows.
- Long recordings are a canary: CONVERSATIONS_V3_FAST_FINISH_LONG_PERCENT
  (default 25) and CONVERSATIONS_V3_FAST_FINISH_LONG_DAILY_SECONDS (default
  7200 per process per UTC day). New audio-seconds and queue metrics.

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

prerecorded_bytes_route lives in utils/stt/prerecorded_route.py so
pre_recorded.py shrinks instead of growing past its line-count ratchet;
prerecorded_from_bytes keeps its behaviour and takes an optional route.

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: 9397a5060d

ℹ️ 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 thread backend/utils/stt/prerecorded_route.py Resolved
Git-on-my-level and others added 8 commits November 25, 2026 20:46
… before the probe (SCA-4434)

Independent re-review of #26344 at 9397a50:

- A pass is long only past 20 minutes of audio, never by chunk count; a
  short pass keeps the short slots and a window of four whatever its
  chunks, and its audio is counted as path=short.
- Length, canary and daily-cap refusals are screened from the units
  before any slot is taken, so they are counted as such, never busy.
- Every later-chunk line that starts before the earlier chunk's last end
  is compared: words by time, utterances by text with a clipped word
  allowed on either side, so overlap text is neither repeated nor traded.
- The language probe is privacy-checked right before it sends, charged
  to the pass, and its timeout capped to the deadline.
- The daily cap is charged with audio actually sent (overlaps, retries,
  probe), reserved up front and settled; stated per process throughout.
- Request phases share one timeout budget, and a stopped pass waits at
  most 2 s past its deadline before releasing its slot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eadline (SCA-4434)

Independent review of #26344 at cc33310:

- Each retained-audio reference read gets an ArtifactReadBudget bound to
  the pass deadline, and the deadline is checked before every reference
  inside a chunk; the serial kill-switch path keeps its own timeouts.
- The self-hosted language gate's timeout is capped to what is left, as
  the vendor probe's is; the deadline is re-checked after refresh,
  funding and privacy.
- started_at is read before the long-audio reservation, so a row without
  it leaks nothing.
- An early stop sets a stop flag: running chunks take no retry, nothing
  more is dispatched, and the slot is released when in-flight requests end.
- The deadline context lives in the leaf module prerecorded_deadline;
  prerecorded_bytes_route stays in pre_recorded; fast_finish adds no
  function-local imports.
- The daily cap is documented as per process lifetime, and AUDIO_SECONDS
  counts the vendor probe clip the cap charges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…CA-4434)

Owners and Release review on SCA-4434:

- Every Firestore call of a chunked pass (row refresh, funding, privacy,
  the language probe's privacy check, the post-chunk refresh, the write
  and the cut) runs on a small fast_finish_io pool and is abandoned at
  its bound (the deadline, or 1.5 s past it after the chunks), yielding
  deadline. The write's in-transaction guard refuses a body that runs
  past the bound, and no cut follows an abandoned write. Admission no
  longer reads the row before the pass; the pass reads it once.
- The long-pass daily cap is one Redis counter per UTC day shared by the
  fleet: reserve with INCRBYFLOAT (taken back when over), settle to the
  audio sent, 26 h TTL, bounded 1 s client; fails closed as long_cap.
- A chunk re-checks the stop flag after its privacy answer, just before
  it is charged and sent.
- Language probes keep each default timeout part, capped to what is left.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves the cloud_run_gmp_sync.yaml keep-regex conflict by taking main's
rule and keeping the fast-finish chunk metrics alternative.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ies (SCA-4434)

Independent review of #26344 at 34222fe:

- P2: language resolution (vendor probe and self-hosted gate) runs on the
  fast_finish_io pool and is abandoned at the deadline, so a probe slow in
  every phase cannot hold the slot past deadline + 2 s. After the privacy
  check, a probe with under 3 s left is skipped and the row's language kept.
- A long pass reserves every chunk twice plus a 30 s probe clip, so retries
  cannot push the day past the cap; it reserves only with 3 s or more left
  (else deadline), and settles in the background off the slot.
- The write guard re-checks the time after the fence's own reads.
- A cancelled chunk job drops its audio buffer while it waits in the queue.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Owners (SCA-4434 03:36Z) and the 3a75ec5 review:

- P3-a: the pass's privacy authority is sticky on denial. Once any check
  refuses or errors (the self-hosted shadow gate's included), every later
  check answers False without asking: no vendor or self-hosted probe, no
  chunk request and no retry leaves, and the pass ends privacy_blocked.
- P3-b: language resolution checks the time before its privacy read, so
  an abandoned resolution makes no reads.
- P3-c: the fast_finish_io docstring names the probes and settles it runs.
- P3-d: holder.pop() is guarded against IndexError.
- P3-e: a chunk's first request needs at least 5 s of the deadline left.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves the cloud_run_gmp_sync.yaml keep-regex conflict by taking main's
rule and keeping the fast-finish chunk metrics alternative.

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

afb7e49 review P3-1 and P3-2:

- _StickyPrivacy keeps its denial in a threading.Event and answers
  `allowed and not denied` after the read, so a read that began before
  another chunk's denial and returned True after it is refused.
- A chunk re-reads the sticky denial immediately before it is charged and
  sent, alongside stop, before the coordinator has stopped the pass.
- The docstring states exactly what is guaranteed.
- Deterministic multi-chunk tests (events and a barrier): an in-flight
  read after another chunk's denial, and other chunks' retries after a
  retry-check denial, send nothing. The single-chunk retry test is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
test_real_clock_budget_ratchet rejects real-clock budgets under 0.5 s. The
stalled audio read and stalled Firestore refresh tests now run a 0.6 s
PASS_DEADLINE_SECONDS; their stubs still stall 5 s, far past it, and the
assertions (released within deadline + grace, read timeout capped to the
deadline) are unchanged in shape. No production code changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level and others added 2 commits November 26, 2026 10:15
Refresh onto repaired main (#26382). No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With CONVERSATIONS_V3_FAST_FINISH_CHUNKED on by default, the lab's
admission stand-in handed fast_finish.run a unit with no retained
references, so the chunked pass planned zero chunks and ended "empty"
before any STT call; audio_single_recording_finish, finish_double_tap
and finish_single_recording_fast failed. The stand-in now gives the
unit one lab reference over the recording, read as silence, and the
lab scripts the chunked path that ships: _transcribe_words answers each
chunk with the scripted lines in its window and counts transcribe_calls,
and prerecorded_bytes_route is replaced so no language probe runs. The
serial kill-switch stub is unchanged. CHUNKED stays on in the lab.

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: 729f357072

ℹ️ 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 +145 to +146
from utils.batch_pipeline import live
from utils.stt import pre_recorded

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 new scenario dependencies to module scope

The newly added live and pre_recorded imports inside install() violate the explicit rule in backend/AGENTS.md: “All imports at module top level — never inside functions.” That guide also applies to the pipeline lab through its scoped guide. Move these new dependencies to module scope rather than extending the existing function-local import pattern.

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

Useful? React with 👍 / 👎.

Now that fast finish writes words in the lab, five scenarios reach
summarisation on fast-finish segments. Those carry uuid4 ids
(TranscriptSegment), and transcript_for_llm cites them in the prompt,
so the fake gateway, which seeds answers from the last user message,
gave a different gist, overview and action item on each repeat, and
CI's --repeat 2 marked the scenarios nondeterministic.

The fake now renames random UUIDs uuid4#1, uuid4#2, ... in first-seen
order before seeding: the rule determinism.py already applies to run
artifacts. The repeat comparison itself is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 4e5dfdb into main Nov 26, 2026
78 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/ff-long-multi branch November 26, 2026 19:22
Git-on-my-level added a commit that referenced this pull request Nov 26, 2026
Resolve the flag registry: keep main's chunked fast-finish flags
(#26344) and the CONVERSATIONS_V3_FINISH_HOME_SLI entry; re-render
backend/docs/feature-flag-registry.md from config/feature-flags.yaml.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 26, 2026
…nish (#26344)

After merging #26344: fast finish is chunked by default (5-minute chunks
with 3 s overlap, sent concurrently), and a B over 20 minutes runs only for
the long canary (LONG_PERCENT, 25 in production) under the fleet-wide
LONG_DAILY_SECONDS cap (7200 s/UTC day in production). The change note no
longer says there is no fast-finish daily cap. finish_after_second_close
re-measured on the merged base: 299 reads, 74 writes, 12 no-op, STT 1 via
fast_finish, LLM 6; caps unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 27, 2026
…4) (#26379)

## What changed and why

Follow-up to #26344, which is now merged; the base is `main`. SCA-4434:
about 1.5× as many long manual Finishes fit under the same daily
fast-STT cap, and the cap stays strict.

Before, a long pass (over 20 min) reserved `2 × planned + 30 s` at
admission, so its one retry per chunk was paid for up front. At the
7,200 s default (`CONVERSATIONS_V3_FAST_FINISH_LONG_DAILY_SECONDS`),
only one 30-minute pass (3,666 s) fit at a time, and about two fit in a
day.

Now:
- **Admission** reserves `planned + 30 s` (each chunk once, plus the
probe clip). Admission screening (`screen` / `room`) checks against the
same amount.
- **Each chunk retry** first reserves its own seconds on the pass's key,
`v3_fast_finish:long_audio_seconds:<day>`. It uses the same
`INCRBYFLOAT` with an immediate take-back over the cap, in one pipelined
round trip on the existing bounded (1 s) client, and only on the retry
path. The reserve runs only:
  - after the sticky privacy check and the stop check,
- after a second check of the recorded denial, just before the reserve,
  - with at least 3 s (`RESERVE_MIN_SECONDS`) of the deadline left.
- **When the reserve fails** (over the cap, Redis error or timeout), the
retry is not sent. The chunk fails as a failed retry does, and the pass
yields to batch through the existing path with outcome `retry_cap`. With
under 3 s left, the chunk fails with its first error, as before.
- **No audio is sent unreserved.** `_Sent` closes when the pass settles.
After that, nothing more is sent or reserved, and a retry reserve that
lands after the settle gives its seconds back. A settle can therefore
only refund, never undercharge.
- **Late reservation:** a retry whose reservation returns with under 1 s
(`RETRY_SEND_MIN_SECONDS`) of the deadline left is not sent (`_Expired`,
which counts as `deadline`). Its reserved seconds are refunded at
settle. A retry's reservation can take about 3–4 s in the worst case
(AUTH on a new connection, the health-check PING, the pipeline and the
give-back). The admission reservation can take about 5 s, so it ends
within `STOP_GRACE_SECONDS` past the deadline. The slot bound holds
because every wait on these calls is bounded.
- **Settle** works as before: it charges what was sent and refunds the
rest, including a reserved retry that was never sent.
- **Metric**:
`omi_conversations_v3_fast_finish_total{outcome="retry_cap"}` is
pre-initialised and kept by the existing GMP keep regex
(`conversations_v3_fast_finish_total`).

At 7,200 s, about three 30-minute passes fit a day, versus two, and two
fit at once. The bound is unchanged.

Ramp: move `CONVERSATIONS_V3_FAST_FINISH_LONG_PERCENT` 25 → 100 after
the first 24 h readback of long-pass latency (first card within 60 s)
and long audio seconds. Any cap raise is David's spend decision. Flag
notes, the runbook and the change note say the same.

This PR does not deploy, set any env or merge anything.

## Product invariants affected

- INV-MEM-4: not affected. The preflight matches
`backend/deploy/runtime_env.yaml`, which only #26344 changes, because it
compares against `main`. This PR changes no deploy, memory or projection
path, only `fast_finish.py`, its tests, docs and flag notes.

## How it was verified

The worktree is on head `cbc8142a113`, which includes `origin/main` at
`cb15ebd4fa5` (#26344 merged as `4e5dfdb1088`). All runs went through
`omi-heavy`:
- `test_conversations_v3_fast_finish_chunked.py` plus
`test_conversations_v3_fast_finish.py`: 243 passed. With
`test_real_clock_budget_ratchet.py` added: 254 passed.
- `python -m testing.pipeline_lab scenario run --jobs 4 --repeat 2
--json --stt replay`: overall outcome `passed`. 12 of 13 scenarios
passed and `finish_after_second_close` was xfail, as it is declared
`expected_failure` (#26288).
- Mutation checks, each run on both fast-finish files:
- `_run` reading `_Sent` instead of `close()` fails the abandoned-chunk
test.
- Dropping the post-reserve time check fails the late-reservation test.
- Replacing the 1 s minimum with a plain deadline check fails the 0.1
s-left case.
- Removing `retry_cap` from the pre-init list fails the fresh-process
test.
- `scripts/check_feature_flag_registry.py`: OK.

These are unit and lab results only. Nothing was deployed.

## Tests

In `test_conversations_v3_fast_finish_chunked.py`:
- Admission reserves `planned + 30`, and that is all the counter holds
while the pass runs.
- A retry reserves its own seconds before it sends. The counter equals
admission plus that chunk's seconds at the retry's send.
- With the cap set exactly to the admission amount, the retry is
skipped, the outcome is `retry_cap`, nothing is written, and nothing
beyond the reservation is sent.
- A Redis error at the retry reserve skips the retry.
- Two `_FleetBudget` instances (two processes) racing 40 takes on one
counter keep at most the cap. A second process taking the last room
makes the pass's retry `retry_cap`.
- Settle refunds a reserved retry that was not sent (the pass stopped
during the reserve). A retry reserve that lands after settle gives its
seconds back.
- A denial recorded by another check, a denial at the retry check, or a
stop during the first request: no reserve.
- A retry with under 3 s left reserves nothing.
- Two 30-minute passes fit under 7,200 s at once, and three in a day; a
fourth gets `long_cap`.
- **`_run`-level:** three abandoned long chunks are held just before
their send until `run()` has returned and settled. After that they make
no provider call and charge nothing. The language probe cannot reach
`add` after settle, because the pass waits on its resolution until the
deadline and the probe rechecks the deadline before charging.
- A retry whose reservation returns past the deadline, or with 0.1 s
left, is not sent and is refunded.
- Every outcome, `retry_cap` included, is pre-initialised at import.
This is checked in a fresh process, so test order cannot create the
label. All outcomes are also kept by the GMP regex.

UI-Evidence: none -- backend only

## Failure class (fixes)

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Nov 27, 2026
…s tail (#26419)

## Summary

When Finish resolves to a live v3 window and a capture sealed after that
window's last speech, Finish now also finishes that newer capture.
Before, it cut only the window's tail. The bug was reproduced by
pipeline-lab `finish_after_second_close` (#26389):

1. Recording A seals.
2. Recording B seals about two minutes later. B is a pendant or
server-batch capture still waiting on its transcript, so no window lists
it in `v3_recording_ids`.
3. The user taps Finish.

A's window was still live: idle 125 s, inside `live.MAX_IDLE` = 2 h. So
`finish_live_window` called `request_finish` on that window, which cut
`members[-1]` = A. B got neither the manual-end cut nor a fast finish,
and a short B stayed hidden under the Home word floor. The #26288
single-capture fallback and the #26361 named-window path both run only
when no window is live.

## DESIGN

**Reads and writes.** This changes only the live-window Finish
transaction, with `CONVERSATIONS_V3_FINISH_NEWER_CAPTURE` on.

- **Reads** (on top of main's window and tail-recording reads):
- the existing `_recent_finish_sources` query: at most 8 documents, 1
billed read when empty;
- when a newer capture qualifies, the account-deletion marker, then by
path:

    | Path | Extra reads after the marker |
    | --- | --- |
    | Live-lane capture moved to | none |
| Server-batch capture whose speech landed (`newer_recording_*`) | **B's
native ledger, 1 read** (`_finish_capture` → `_native_projection_state`,
since `newer_state` is None) |
| Marked capture, pending-retry (a later tap on a still-requested batch
B: `newer_already_requested` / `newer_consumed`) | **B's native ledger,
1 read** (same call) |
| Stored both (`newer_dual_*`) | **2 ledger reads**: B's, plus A's when
A is batch. A's is the read the tail cut always made, now ahead of both
writes |
| Selected, then declined | that path's ledger read; the tail's own
batch ledger read is unchanged |

Pinned by `test_server_batch_redirect_reads_the_capture_ledger_once`,
`test_marked_pending_retry_reads_the_capture_ledger_once`,
`test_stored_both_reads_each_ledger_once_before_any_write` (exact
ordered read paths).
- **Settlement:** none added. The Finish-to-visible sample is read from
the derived row `settle_processing` already reads.
- **Writes:**
- **up to 2 documents** in the stored-both case: A's window-tail cut and
B's recording-scoped request;
  - otherwise exactly 1, as before;
- the Finish stamp (`v3_finish_requested`) rides in the write the
transaction already makes, and the planner carries it in the derived-row
write it already makes: **no added write**.
- Off means the transaction is main's, plus the `tail` stamp in its
existing write.
- **Provider cost:** storing B's request makes B a fast-finish
candidate. That adds at most one fast-finish pass per stored-both
Finish, even when B turns out silent.
- **Chunked (the default since #26344, production `on`):** each unit is
split into chunks of at most 5 min with 3 s of overlap, sent
concurrently. A B of up to 20 min (`MAX_SECONDS`) is a few prerecorded
requests; the lab's 80 s B is one (STT 0 → 1).
- **Chunking off:** one request per unit, at most `MAX_UNITS` (8), up to
20 min.
  - **Bounds:**
- `CONVERSATIONS_V3_FAST_FINISH`: `cohort` by default, but production
runs `on` for the services that serve Finish and admission, so the
cohort does not limit it there.
- A B over 20 min runs only for the long canary:
`CONVERSATIONS_V3_FAST_FINISH_LONG_PERCENT` (25 in production) and
`CONVERSATIONS_V3_FAST_FINISH_LONG_DAILY_SECONDS` (7200 s of such audio
per UTC day across the fleet in production). That is the only
fast-finish daily cap; a long pass reserves its planned seconds before
any spend.
- The shared funding gate (`fast_finish.funded` →
`sync_admission(lane='batch')`): consent and the owner's funded STT plan
allowance.

**Production readback:**

1. `omi_conversations_v3_finish_no_pointer_total` by `outcome` for the
`newer_*` and `newer_dual_*` labels, against the tail path's `cut` /
`requested`. That shows how often Finish finds a newer capture and which
branch it takes.
2. **The share of Finishes whose response target becomes visible within
60 s:** `omi_conversations_v3_finish_to_visible_seconds{path}` (`tail` /
`newer` / `newer_dual`), `le="60"` bucket over `_count`, compared by
path. One sample per Finish, at the response target's first visible
manual-end settlement; kept by the sync scrape profile.
3. `omi_conversations_v3_finish_newer_declined_total{reason}`: how often
a selected newer capture declined and the tail answered.

## Change

- `database/conversations_v3_live.py`
- `request_finish(..., newer_capture=False)` gets a new parameter. When
it is true, the transaction runs the existing `_recent_finish_sources`
scan after its two document reads and before any write.
  - `_newer_capture()` selects the capture. A capture qualifies when it:
    - is a sealed Listen capture;
    - ended strictly after the window's `finished_at`;
    - is not one of the window's sources;
    - carries `has_content` (a projection that landed empty clears it);
- passes `_capture_ineligible(row, now)`: sealed within
`RECENT_FINISH_AGE`, unclaimed, not marked for another window, not
private, deleted, discarded, locked, merged, partial or upload-failed.

The newest qualifying capture wins, as in `_latest_capture`. The
account-deletion check (`_account_deleting`, shared with
`_live_window_or_deleting`) runs before any write.
- **B's speech has landed** (a live-lane capture with
`has_finish_content`, or a batch capture whose projection landed):
redirect only. B gets the recording-scoped cut or request through
`_finish_capture`, and the response names B. Outcomes are
`newer_recording_cut` / `newer_recording_requested`.
- **B is a server-batch capture whose projection has not landed**
(`_batch_speech_landed`). It may hold only silence: the session's last
capture often does, after the quiet timeout seals A and the device stop
seals B. The same transaction:
    - stores A's window-tail cut, exactly what main stores;
    - stores B's recording-scoped request.

Both ledger reads come first. `_finish_window_tail` and
`_finish_capture` take a pre-read `state=`, and StrictFirestore enforces
the order in tests. The response names **A's window**, because the cut
landed there. The outcome is `newer_dual_<tail outcome>`.
- Silent B: A is cut at once, as on main, and B's request clears at
whole-record completion.
- Speech B: A is cut and B's request becomes B's own manual end, so B
shows as its own card.
- **Why not `has_finish_content` for batch B?** In production it is true
for almost every batch capture right after creation.
`create_in_progress_conversation` → `mark_new` stamps
`v3_speech_landed_at` at creation
(`utils/conversations/v3/triggers.py:61-69`), and audio custody sets
`has_content` on any committed audio
(`database/server_batch_audio.py:60`). So a batch capture's speech has
landed only with its projection: `record_projection_revision` together
with `has_content`. The lab, which creates captures through the product
path, shows the same stamp. A test pins it: `created_stamp=True` fails
if the check goes back to `has_finish_content`.
  - **The window-tail cut alone** runs unchanged when:
    - no capture qualifies;
    - two captures tie exactly on `finished_at`;
    - the scan is full with its oldest row still newer than the window;
- `_finish_capture` declines or answers `already_empty`. It writes
nothing in those cases.
  - **Retries never cut A twice.**
- If A already carries this window's Finish (the stored-both case), the
tail path answers (`already_cut` / `already_requested`) and B is not
touched.
- A capture an earlier recording-scoped Finish marked answers through
`_finish_capture`, even if a window claimed it between taps.
- If the marked capture can no longer answer (private, locked, deleted,
discarded, merged, partial, upload-failed, or `_finish_capture`
declines, e.g. an unavailable ledger), the **window tail is cut**. The
app's `settleManualFinish` reads a 404 as "already closed", so a 404
would leave A uncut. `_finish_capture` writes nothing on those declines,
so the tail cut's reads still precede every write.
    - A mark that resolved empty no longer holds the Finish.
    - Unmarked captures older than an active mark don't qualify.
- `utils/conversations/v3/finish.py`: both live-window calls pass the
switch. They are the empty body and a named window that is still live.
`_acknowledge` counts the full label, then strips `newer_` / `dual_` to
answer like the path that stored it. A window answer is what the app
already settles on: `settleManualFinish` binds `_finishLiveId` to it
(`app/lib/providers/conversations_v3_provider.dart:145-173`).
- `config/conversations_v3.py`: `finish_newer_capture_enabled()` adds
the kill switch `CONVERSATIONS_V3_FINISH_NEWER_CAPTURE`. It defaults on;
off is exactly main.
- `utils/conversations/v3/metrics.py`: pre-initialised labels in
`omi_conversations_v3_finish_no_pointer_total`, apart from the tail
path's outcomes, every one reachable:
- `newer_recording_cut`, `newer_recording_requested`,
`newer_already_cut`, `newer_already_requested`, `newer_resolved_empty`,
`newer_consumed`, `newer_recording_ineligible` (account being deleted);
- `newer_dual_cut`, `newer_dual_requested`, `newer_dual_consumed`,
`newer_dual_already_cut`, `newer_dual_already_requested`,
`newer_dual_already_empty`, `newer_dual_resolved_empty`.
- `newer_already_empty`, `newer_batch_unavailable`,
`newer_batch_disabled` could never be returned and are removed. A
selected-then-declined capture counts in
**`omi_conversations_v3_finish_newer_declined_total{reason}`**
(`already_empty`, `batch_unavailable`, `batch_disabled`,
`recording_ineligible`), once after the commit; the window tail still
cuts and answers, counted as the tail's outcome.
- **`omi_conversations_v3_finish_to_visible_seconds{path}`**, histogram,
`path` ∈ `tail` / `newer` / `newer_dual`, buckets 5 s – 2 h.
- **Finish-to-visible sample (no correlation store).** `request_finish`
stamps `v3_finish_requested = {at, path}` in the first write it stores
on the response target's source: the tail for `tail` / `newer_dual`, B
for `newer`. In the stored-both case the tail's write is planned first
(`_window_tail_plan`, no read or write), so B's request is stamped only
when the answer names B; otherwise B rides along unstamped and B's own
card never samples. Consuming cuts and `already_*` answers write no
stamp, so a retried Finish keeps the first. The planner carries the
stamp to the derived row that shows the cut (first stamp wins).
`settle_processing` observes `now - at` once, at the row's first visible
manual-end settlement (the `v3_manual_end_home_counted` transition),
after the transaction commits; a stamp older than 2 h, a hidden row, or
a re-settlement records nothing. `first_speech_to_visible_seconds` is
not reused: it fires at row creation, and a live window's row exists
before its Finish. `deploy/cloud_run_gmp_sync.yaml` keeps the histogram.
- Pipeline lab (`scenario/ops.py`): at seal, the batch lane writes
`has_content` with `server_batch_audio_end`, as production's
`note_server_batch_audio` does in one transaction.
`finish_after_second_close` now expects the answer to name A's window
(`finish_response_names_a_window`) and B to be fast-finished
(`b_fast_finished`, the check main fails).
- Flag registry, contract paragraph in `listen_pusher_pipeline.mdx`,
change note, Firestore query driver for `request_finish`.

## Verification

All commands ran from `backend/` in the lane worktree, through
`omi-heavy`. Base is origin/main `afab9560db2`.

- **Scenario on main:** `finish_after_second_close` gave XFAIL. A was
cut, B got no fast finish, reads 236.
- **Scenario with the change:** PASSED. The answer names A's window; B
fast finish `written`; B on Home. Reads 304, writes 74, no-op writes 12,
STT 1, LLM 6. The budget is re-measured.
- **Scenario with `"env": {"CONVERSATIONS_V3_FINISH_NEWER_CAPTURE":
"off"}`:** same as main, at this head. Target A, `b_fast_finished`
fails, 236 reads, 62 writes, 0 STT.
- **All 13 committed scenarios:** passed.
- **Unit tests:** `tests/unit/test_episodes_finalize_paths.py`, 154
passed; with the Firestore guard set, 1079 passed.
- **End-to-end race test** (owners' request):
`test_one_finish_cuts_a_at_once_and_consumes_b_once_across_resolution_and_retry`,
parametrized by B landing with `speech` or `silence`. It runs entirely
on StrictFirestore:
1. B is created through the real `triggers.mark_new`, so it carries the
creation stamp.
2. Finish runs: one transaction cuts A and stores B's request; the
answer names A's window.
3. B's projection lands (`replace_record`), then the real whole-record
completion (`store.complete` → `_v3_finish_update`) runs twice. B's
request is consumed once: B ends with `v3_manual_end` for speech, or the
request is cleared for silence.
4. The same Finish runs again (same body and window id). It answers A's
window with `already_cut` and no writes; A is cut once and B is
requested once.

With the retry guard removed, `[speech]` fails (the retry answers
`capture-b`). `[silence]` still passes, because a mark that resolved
empty no longer holds the Finish, so the retry reaches A's tail either
way.
- **Each new test fails without its own fix.** Mutation runs:
  - R1, no stored-both path: 12 fail;
- R7, `has_finish_content` as the batch speech signal: 4 fail
(`created_stamp=True`);
- R2, ledger reads not hoisted: 4 fail (StrictFirestore read after
write);
  - R3, stored-both retry guard removed: 3 fail;
  - R4, a blocked mark answers instead of a tail cut: 5 fail;
  - R5, a retry decline is a 404: 1 fails;
  - R6, the older-than-mark condition removed: 1 fails.

The previous round's mutations (`has_content` gate, `already_empty`
decline, newest-wins, deletion marker) still hold.
- **Degraded-targeting telemetry counts once per Finish.** A tie or a
full scan records `omi_fallback_total` (`conversation_finalization`,
`newer_capture` → `window_tail`, `degraded`). `_newer_capture` only
marks a per-attempt flag, reset at the top of the transaction body;
`request_finish` records it once after the transaction commits.
`test_live_window_finish_records_degraded_targeting_once_across_transaction_retries[tie|full_scan]`
aborts the first attempt after the scan and before any write. With the
recording back inside the body, both cases fail: "Called 2 times".
- **Targeted set:** 43 files, 2597 tests passed: the changed tests, the
Firestore guard set, every `test_conversations_v3_*`,
`test_reliability_experiment_end_*`, `test_reason_label_enums`,
`test_pipeline_lab_*`, `test_batch_pipeline_projection` and
`test_server_batch_completion`.
- `scripts/check_feature_flag_registry.py` OK.

### Review fixes (panel `review-20261127t015349-a22e`, F1–F5)

- **F1** Finish-to-visible sample:
`test_live_window_finish_stamps_only_its_response_target[tail|newer|newer_dual]`,
`test_retried_live_window_finish_keeps_the_first_stamp[...]`,
`test_consuming_cut_keeps_the_stamp_of_the_finish_that_stored_the_request[tail|newer]`,
`test_finish_stamp_follows_the_cut_to_its_card_once` (planner, dual
card),
`test_finish_to_visible_is_observed_once_at_the_first_visible_settlement[...]`
(re-settlement does not repeat),
`test_finish_to_visible_drops_stale_hidden_and_unstamped_rows[stale|hidden|unknown_path|no_time|unstamped]`,
`test_finish_to_visible_dual_card_samples_only_the_response_target`,
`test_cloud_run_sync_scrapes_finish_to_visible`.
- **F3** decline:
`test_live_window_finish_counts_a_declined_newer_capture_and_still_cuts_the_tail[already_empty|batch_unavailable|batch_disabled|recording_ineligible]`
and, separately,
`test_live_window_finish_without_a_newer_candidate_counts_no_decline[none|older_than_window|silent]`;
`test_newer_capture_finish_labels_are_reachable_or_absent`.
- **F2/F4** read counts: the three exact read-sequence tests above.
- **F5**
`test_live_window_finish_cuts_the_tail_without_a_newer_finishable_capture`
asserts on the retained `b` that neither `v3_manual_end` nor
`v3_manual_end_requested` was written (and, for `none`, that B was not
recreated).
- Mutations: dropping the decline record fails 4; stamping B's request
in the stored-both case fails 1.
- Focused files (15), all passed at the earlier merged head (origin/main
merged after main moved): `test_episodes_finalize_paths` 178,
`test_conversations_v3_fast_finish` 115,
`test_conversations_v3_contract` 119, `test_firestore_query_shapes` 644,
`test_firestore_runtime_witnesses` 25,
`test_conversations_v3_live_passes` 53,
`test_conversations_v3_live_rederive` 129,
`test_conversations_v3_created_delivery` 59,
`test_conversations_v3_engine` 97,
`test_conversations_v3_finish_late_predecessor` 33,
`test_batch_pipeline_projection` 87, `test_pipeline_lab_scenario` 51,
`test_monitoring_telemetry_contract` 58, `test_fleet_deployment` 11,
`test_attach_cloud_run_gmp_sidecar` 117.
- `python -m testing.pipeline_lab affected` → 15 scenarios, all passed,
budgets unchanged (`finish_after_second_close` included).

The full backend unit suite is left to CI.

## Lab vs production

- **The final conversation shows `manual_end = no` in the lab.** The
lab's native-completion stand-in (`batch_projection`) skips the
projection transaction, so neither A's window-scoped request nor B's
recording-scoped request is ever promoted to `v3_manual_end`. Production
promotes them: at admission for a window-targeted single unit, at
whole-record ledger completion for a recording-scoped request
(`database/batch_pipeline_projection.py`, `whole_record_consumed`), as
for the existing #26288 fallback. In the lab, A and B end in one
conversation because no cut lands.
- **#26344 interaction.** #26344 is merged into this branch (merge
`4d2e913c`). Under its chunked fast finish and extended lab STT
stand-in, `finish_after_second_close` still meets every check
(`b_fast_finished: written`, STT 1 via `fast_finish`), now at 299 reads
(was 304).

## Rollback

Set `CONVERSATIONS_V3_FINISH_NEWER_CAPTURE=off` on the API service that
serves `POST /v1/conversations`. That restores exactly main's Finish
without a deploy; cuts and requests already stored stay. Or revert the
merge commit.

Product invariants affected: none
Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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