Skip to content

fix(listen): end batch-only conversations on speech quiet, not audio quiet - #25633

Merged
kodjima33 merged 6 commits into
mainfrom
fix/batch-speech-quiet
Nov 17, 2026
Merged

kodjima33 merged 6 commits into
mainfrom
fix/batch-speech-quiet

Conversation

@kodjima33

@kodjima33 kodjima33 commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

On batch-only sockets (all mobile pendant capture since Nov 2), a conversation never ended while the pendant kept streaming. These sockets run no live STT, so lifecycle_loop measured its 120 s quiet timeout from the last received audio frame, and a pendant sends frames even in silence. Separate conversations merged into one in-progress recording until the device disconnected.

Prod evidence (2026-11-17):

  • One account: two conversations (1:09–1:30 PM and 1:33–2:43 PM NY) sat inside one recording that stayed in_progress from 1:06 PM for 1h43m and never appeared on Home. The device's own synced copies show the real boundaries: 2.5 min speech gaps at 1:30 and 1:33.
  • Fleet: 476 batch recordings had fresh audio. 142 of them (30%) had been open more than 1 h, and 16 more than 4 h.

The audio-clock rule came in with ef2e2ed (2026-10-27, "route eligible platform capture to durable batch without live STT").

Change

  • utils/stt/speech_clock.py: per-socket SpeechClock. It runs the local Silero model that the VAD gate and sync segmentation already use (threshold 0.5, at least 3 consecutive 32 ms windows) over decoded audio, and records the wall time of the last sustained speech. Any model failure marks the clock failed and records a vad fallback.
  • receiver.py: batch-only sockets feed every decoded frame to the clock. Sockets with live STT are unchanged.
  • conversations.py lifecycle_loop: for batch-owned rows, quiet counts from quiet_since(...):
    • Last speech heard in this row. The 120 s timeout now ends the conversation at real silence.
    • No speech yet in a row this socket created. The row stays open. Silence never closes an empty recording every 2 minutes.
    • Row resumed from an earlier socket. The resume counts as speech, so a reconnect cannot pin an ended conversation open.
    • No clock or a failed clock. The previous audio-clock rule applies.

Cost

  • Real Silero on a 16 kHz sample fed in 20 ms frames costs about 6.4 ms CPU per audio second, roughly 0.6% of a core per stream.
  • This is inline on the receive loop, the same pattern as VADStreamingGate._run_vad. Prod listen runs that gate with VAD_GATE_MODE=active.
  • At about 476 concurrent batch sockets fleet-wide, the total is about 3 cores.
  • Windows and inference seconds go to the existing record_vad_windows metric, so the load is visible.

Speech threshold

The threshold and model are the ones the sync segmentation uses (local_vad.segments_from_16khz_samples, Silero at 0.5 on raw PCM). On 2026-11-17 that segmentation split this same pendant audio at the right places: 2.5 min gaps at 1:30 and 1:33 PM. Within the 70-minute conversation it found no 120 s gap.

Validation

  • tests/unit/test_listen_batch_speech_quiet.py, 13 cases:
    • sustained speech vs a blip; partial windows and odd bytes; 8 kHz resampling; failure fallback; real Silero on silence;
    • the quiet_since rules;
    • lifecycle_loop: streamed silence after speech closes the row; recent speech, an all-silent row, a missing clock, a failed clock and a calendar meeting window keep it open, including a row created before its meeting started (the window counts from the last speech, since a live batch row's stored recorded_end is its creation).
  • Real model on recorded speech: first speech mark at 0.14 s, last at 19.98 s (speech ends at 20 s), nothing in the following 10 s of silence.
  • All listen, receiver, batch, VAD, quiet and local-preview unit files: 2127 passed, 1 skipped.
  • Prod baseline before the fix, on the same path the pendant uses (ios, source=omi, pcm16, one socket: 30 s speech, then 150 s of streamed silence frames, then 30 s speech): one conversation (074fe865), still in_progress afterwards, never cut. The same e2e runs again after the listen roll; it should give two.

Deploy

Listen only. Rides the next listen roll after the 22:00Z freeze, together with #25599 (re-gated drop hold, merged 13:51Z). The two are independent: #25599 makes a socket drop end the conversation; this makes streamed silence end it.

Not in this PR

  • The time from cut to summary and the Processing row are handled separately.

Line-Count-Exception: backend/routers/listen/receiver.py | 3064 -> 3072 | batch-only sockets feed decoded audio to the new speech clock; the logic lives in utils/stt/speech_clock.py

Product invariants affected

none

Failure class (fixes)

Failure-Class: new

🤖 Generated with Claude Code

…quiet

A pendant streams frames through silence, so the batch-only lifecycle (which
used the last audio frame as activity) never reached its quiet timeout and
separate conversations merged until the device disconnected. Batch-only
sockets now run the local Silero model on decoded audio and count the quiet
timeout from the last sustained speech. An all-silent row stays open, a
resumed row counts its resume as speech, and a VAD failure falls back to the
audio clock.
@kodjima33
kodjima33 merged commit b2fdcbc into main Nov 17, 2026
65 checks passed
@kodjima33
kodjima33 deleted the fix/batch-speech-quiet branch November 17, 2026 21:09
@kodjima33

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level merged as b2fdcbc. It's listen-only and needs the next prod listen roll after the 22:00Z freeze. Main already has #25599, so one roll at or after b2fdcbc ships both. Prod evidence is in the body: 30% of live batch recordings were open for more than 1 h. Unless your v3 lane is rolling listen then, I'll do a build-only run plus the listen Helm dispatch for b2fdcbc at 22:00Z and run the speech/silence/speech e2e on prod right after.

kodjima33 added a commit that referenced this pull request Nov 18, 2026
…allowlist canary) (#25673)

## What changed and why

**Problem.** A pendant recording should show its transcript and summary
on Home within 60 s of the seal. In prod it takes minutes. The largest
p50 stage after the seal is not the GPU. It is the ordered merge: 80% of
recordings wait the full 60 s `BATCH_PIPELINE_MERGE_HEAD_WAIT_SECONDS`
behind a starved head. That head is a days-old `retry` job, and the
existing bypass then commits the same row 60 s late.

**Change.** Owners listed in the new
`BATCH_PIPELINE_MERGE_STALE_HEAD_UID_ALLOWLIST` (default empty) skip the
head wait when it is waiting only on starved rows. A starved row was
admitted at least 1,800 s ago and has waited that long for a lease:
`ready`/`retry` with `available_at` at least 1,800 s in the past, or
`leased` with `lease_until` at least 1,800 s in the past. Every
lease-ending path (`_defer`, admission hold, missing-input repair, held
requeue, redrive, quarantine) resets `lease_until` to 0 and stamps
`available_at`, so a row that failed seconds ago, or is due again in
seconds, is not starved. The skip commits exactly the row the expired
wait would commit (the owner's earliest ready pending row) through the
same transaction body. Inside that transaction it also requires:
- the row is a native record unit whose earlier binding units are
settled;
- every pending row captured before it is starved. A new bounded
`pending_page` read (129 rows, `first_pending`'s filters, order and
index, on every store backend) checks this; a longer backlog refuses.

A refused skip returns before the catch-up hold and the backlog-release
fallback. Without the early return, a provider-route record candidate
could set `held['backlog']` and the tx-fresh fallback would run before
60 s; with it, that fallback is unreachable from a skip. A skip logs
`event=batch_merge outcome=stale_head_skip` (head state + wait bucket)
and does not write `head_wait_bypass`, so the bypass field and log stay
real expiries only. Unchanged:
- unlisted owners
- head wait off
- non-record rows
- any unready row ahead that is in flight, recently leased, younger than
30 min, or in another state (`record_pending`, `held`)

### Stage budget, seal to Home summary (prod, read-only)

Sample: 600 random `batch_live_v1` rows with `record_sealed_at`, sealed
45 min to 8 h before 2026-11-18 07:50Z, out of 6,730 eligible. 432 had
every unit committed. Per recording, the critical path is the last unit
to commit. Units per recording: p50 1, p75 2, p90 5.

| Stage | p50 s | p75 s | p90 s | Note |
|---|---:|---:|---:|---|
| seal -> intake claimed | 8 | 396 | 732 | bimodal: 56% < 15 s, 36% wait
5-15+ min |
| claimed -> staged/admitted | 6 | 9 | 19 | |
| admitted -> GPU result (queue + compute) | 9 | 21 | 62 | GPU is not
the bottleneck |
| **GPU result -> committed (ordered merge)** | **62** | 137 | 372 |
346/432 via head-wait bypass: p50 67 s single-unit, 98 s multi-unit.
Without bypass: 0.1 s |
| committed -> persisted (projection discovery) | 21 | 33 | 43 | |
| persisted -> ledger `transcribed` (follow-up/completion) | 37 | 62 |
99 | 33 s single-unit (eager wake), 46 s multi-unit |
| `transcribed` -> `summary_completed_at` (notes) | 38 | 58 | 93 | Luna
`conv_structure` |
| seal -> `summary_completed_at`, end to end (n=235) | 452 | 708 | 1,496
| |

Sum of p50 stages on the fast-claim path: about 181 s.

**Root cause of the merge stage.** For 20 of 20 sampled bypassed owners,
the earliest pending fresh-class row is a native record job in `retry`,
captured 36-215 h ago and due long ago (`available_at` in the past).
`fresh_capture` is fixed at admission. The tx-fresh gate and
`_fresh_pick` therefore treat these rows as fresh heads, and every new
recording waits out the full 60 s. The canary account (`viUv7G...`) has
this shape: a 78.6 h-old catch-up `retry` head, with fresh-class `retry`
stock from 84 h ago behind it.

### Ranked cuts (expected p50 seconds saved for the seal -> summary
path)

1. **Stale-head skip (this PR).** Saves 45-55 s on ~80% of recordings.
All 75 of the canary owner's rows ahead are starved under this rule:
`retry`, due 10.3-90.3 h, unleased (53 at attempt 1, 22 at attempt 0, so
an `attempt == 0` rule would exclude most of them). They fit inside the
129-row page. Sampled owners had 8-134. Low risk: same rows and outcome
as today's bypass, 60 s sooner, allowlist-scoped. After a CPU roll the
commit lands on the next serving tick (10 s on prod
backend-integration). After a GPU worker roll it lands at publication,
saving about 60 s.
2. **Persisted -> `transcribed` completion.** Saves 20-35 s. Low-medium
risk, small to medium effort. `RECORD_FOLLOWUP_WAKE_ENABLED` covers only
single-unit records (`projection.py:1627`), and even single-unit takes
33 s. Extending the eager wake to multipart, and finding the single-unit
delay, comes next.
3. **Post-commit projection wake (committed -> persisted).** Saves 15-20
s. Medium effort. The GPU pump commits directly with no `on_committed`
hook, so this needs a GPU image roll.
4. **Intake-claim tail.** p50 unchanged, p75 about -380 s. Medium risk
and effort. 36% of seals wait 5-15+ min for the `record_pending` claim.
Needs diagnosis: record-drain capacity (10 rows per pass) vs ~1,200
seals/h, or barrier refusals.
5. **Starved fresh-class `retry` heads themselves.** Same seconds as cut
1, for every owner. Medium effort. This is a scheduler question: why due
FRESH `retry` rows go unleased for days. Fixing it removes the need for
cut 1's allowlist.
6. **Notes model time.** At most 5-15 s, with quality risk. Luna
one-shot; the fleet notes histogram is ~25 s model time. Needs a quality
eval before any model or prompt change. Not recommended now.
7. **Staged cuts, no gain now.**
- `RECORD_FRESH_MERGE_ENABLED` (cut 4): its blocker is unresolved. The
prod GPU worker image tag is `ef42ee8` (2026-11-14), which predates the
sibling guard `a0a8816`. It would also not help here, because the stale
heads are already fresh-class.
- `RECORD_NOTES_EAGER_ENABLED` (cut 2): superseded by #25635, which
already moves the notes obligation to due-now at completion. The
lease-off producer revision blocker is still open.
8. **Pre-seal admission of completed units.** Saves at most ~25 s
(admission + GPU = 15 + 9 s p50). Very high custody risk: the seal
barrier is the admission contract (`require_record_audio_barrier`). Not
recommended.

**What remains to reach 60 s p50.** After cut 1 (with a GPU roll), the
fast path is about 8 + 6 + 9 + ~1 + 21 + 37 + 38 ≈ 120 s. Cuts 2 and 3
bring it to about 65-75 s. The rest has to come from notes (cut 6) or
claim/staging. The intake-claim tail (cut 4) dominates p75 and must be
fixed for a p75 target.

**Related.** #25633 (120 s speech-quiet seal) and #25635 (first summary
when the sealed transcript lands) are live. #25601 and #25623 (David)
work on stuck projection chains/heads; they touch no file here. The
staged cuts and the 60 s head wait are documented in
`2026-11-14-record-post-seal-latency.md`.

## How to canary and roll back

- **Canary for one account.** Set on prod Cloud Run
`backend-integration` (the serving loop host,
`BATCH_PIPELINE_SERVING_ENABLED=true`):
`BATCH_PIPELINE_MERGE_STALE_HEAD_UID_ALLOWLIST=viUv7GtdoHXbK1UBCDlPuTDuPgJ2`.
This PR deliberately adds no runtime-env overlay entry: put it in the
`backend-integration` section of
`backend/deploy/runtime_env/prod.overlay.yaml` as part of the canary
change, so the next deploy keeps it. The backend image must contain this
PR. `config/deployment-setting-classification.json` classifies the
variable as `config`. The GPU worker needs nothing; adding the same env
there after its next image roll moves the commit to publication time.
- **Readback.** A skip leaves no durable marker, so readback relies on
the `event=batch_merge outcome=stale_head_skip` log line. On the canary
account's next recordings, `committed_at - ready_at` of the last unit
should drop from ~60-100 s to ≤ ~10 s, with no `late_capture` within a
recording.
- **Rollback.** Remove the uid or unset the env. No migration; committed
rows keep their order.

## Product invariants affected

none

## How it was verified

- Prod measurement used read-only Firestore (collection-group
`conversations` query on `record_lane_owner`/`status`/`finished_at`,
joined to `batch_pipeline_prod_jobs` and `_results` and to
`pipeline_ledger`) and read-only `kubectl`/`gcloud` describes. No prod
writes, env or flag changes.
- `pytest tests/unit/test_batch_pipeline_merge_stale_head.py`: 32
passed. Jobstore SQL safety plus protocol parity: 210 passed.
- 94 directly affected test files pass locally: merge, jobstore, parity,
scheduler, transaction-attempt, pipeline sims, all Firestore query/index
guards, `test_flag_budget.py` and `test_record_seal_latency.py`. CI runs
the full 1,260-file selection.
- Existing merge suites unchanged and passing:
  - `test_batch_pipeline_merge_head_wait.py` (177)
  - `test_batch_pipeline_merge_fresh_first.py` (59)
  - `test_batch_pipeline_merge_tx_fresh_gate.py` (24)
  - `test_record_seal_latency.py` (58)
  - `test_batch_provider_merge_membership.py` (46)
  - `test_batch_terminal_poll_skip.py` (42)
  - `test_batch_backlog_release.py` (57)
  - the recovered-release suites and the head-wait sims
- All 24 changed-file-selected unit test files pass, including
`test_flag_budget.py`, `test_pipeline_sim*`,
`test_lifecycle_invariants.py` and
`test_cross_service_deploy_contract.py`.
- `backend/scripts/typecheck.sh`: 0 errors. `make preflight`: 43 checks
passed. `scripts/check_feature_flag_registry.py`: OK.
- Not verified: a live canary. That requires the backend roll and env
change, which belong to the parent.

## Tests

`backend/tests/unit/test_batch_pipeline_merge_stale_head.py` (32 cases)
covers:
- a listed owner commits at once behind a starved head, with its own log
and no `head_wait_bypass`; an expired wait keeps the bypass marker
- **realistic heads that are not starved keep the wait:** in flight; the
reviewer's lease-expired retry due again in 10 s (`lease_until=0`,
`attempt=1`); a retry that failed 10 min ago; a row redriven a minute
ago; `record_pending`; `held`
- a prod-shaped retry due for 10 h without a lease is starved and skips
- a head deferred between the probe and the transaction keeps the wait
- **a young, leased recording captured earlier blocks the skip**; both
then commit in capture order
- **a refused skip of a backlog-held (provider) unit commits nothing,
adds no held owner and runs no early fallback transaction** before 60 s
- the 129-row page bound: 128 starved rows ahead skip, 129 refuse
- unset, empty or other-uid allowlists keep the 60 s wait
- head wait off keeps strict order
- an unready earlier unit of the same recording waits
- non-record rows keep the wait
- the prod shape (catch-up head plus fresh-class stock), with the tx
fresh gate on and off
- exact allowlist parsing

Mutation check: restoring the old `lease_until`-only rule fails 4 of
these tests, and removing the early return fails the backlog test.

`test_jobstore_sql_safety.py` adds `pending_page_in` binding and
limit-cap coverage. `test_jobstore_protocol_parity.py` checks that every
backend serves `pending_page`, and the Firestore query-shape registry
drives the new query.

## UI evidence

UI-Evidence: none -- backend merge scheduling only

## Failure class (fixes)

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)
kodjima33 added a commit that referenced this pull request Nov 18, 2026
…fault off, cohort canary) (#25726)

## Problem

Conversations v3 is on for TestFlight. A pendant capture is a batch-only
*recording*. It has no transcript until it seals, and it seals only
after 120 s of speech quiet (#25633) or at socket close. In a cafe the
speech never pauses for 120 s. Nik's recording `4170f9cf` ran 19:01:54
to 19:35:31Z (33.6 min). His chat ended 19:09:50Z, and its derived rows
appeared at 19:40:52 and 19:43:08Z. Home showed nothing for 31 minutes.

## Change (ships OFF)

- **Rotation** (`routers/listen/conversations.py` `_v3_rotation_due`,
`_rotate_v3_recording`, `_seal_rotated`, `_seal_rotated_recording`;
`utils/stt/speech_clock.py` `rotation_due`). A batch-owned row with
`recording: true` (the v3 marker) seals at the first 1.5 s speech pause
once it is `CONVERSATIONS_V3_ROTATION_MIN_SECONDS` old (default 180), or
at `CONVERSATIONS_V3_ROTATION_MAX_SECONDS` (default 300) without a
pause. A row never rotates if it is a legacy row, an onboarding capture,
has no speech of its own, has a pending client stop
(`finalization_reason`), is under an episode `hold`, or is inside the 60
s backoff after a failed rotation. A tick that is already a quiet seal
or a producer `boundary_at` takes the existing path. A failed or absent
SpeechClock uses only the cap.
- **Cut order** (fixes the custody blocker). This is the order
`rollover_after_transcript_decode_failure` already uses:
1. Create the successor first. The old row stays `in_progress` and keeps
receiving audio until `current_conversation_id` switches.
2. `LiveAudioArchive.retarget(old, successor)`
(`utils/other/live_audio_archive.py`), under the archive lock. From then
on, any frame still addressed to the old id is appended to the
successor. This covers a frame the receiver bound before the switch and
appended after it.
3. `finish_recording(old)` flushes and commits the old row's packs. Its
custody is then final.
4. Stamp `v3_rotation_cap_seconds`, then run
`process_conversation(old)`. The old row is no longer current, so
`close_batch_archive` skips the global close, exactly as in the
decode-failure rollover.

A custody timeout leaves the old row queued and retries it on the next
tick (at most 8 queued). After socket close, the old row's armed quiet
check and stale recovery own it. A successful seal drops the old
producer token, so the 64-token cap is not reached on long sockets.
- **Supersede mode**
(`create_new_in_progress_conversation(rollover=True,
supersede=previous_id)`, `database/listen_continuations.py`
`supersede_live_continuation`).
- Phone sockets send `client_conversation_id`. Without this mode, the
create first resolved the origin's `live_continuation` pointer, which
named the still-open current row, and resumed that same row. So a long
recording rotated at most once.
  - In supersede mode the create skips both continuation resumes.
- The pointer moves only after the successor is claimed, armed and is
`current_conversation_id`, in one transaction. A failed create therefore
never leaves the pointer on a dead empty row.
- It moves only when the pointer names the retired row, one of this
socket's own recordings, or nothing. Otherwise `other_owner` is counted
and logged, and another generation's pointer is never taken.
  - A reconnect resumes the successor.
- **Successor failure.** If the create raises, or returns without
switching, the current recording is kept. `recording_session_id`,
`batch_record_capture`, `recording_session_ids_by_conversation` and the
Redis in-progress id are restored, and rotation backs off 60 s
(`ROTATION_RETRY_SECONDS`). A `WebSocketException` (ownership changed,
or the 64-token cap) is re-raised after the restore, so the socket
closes as it would on any other create.
- **No rotation on reconnect-protocol rows.** A row carrying
`listen_batch_producer` never rotates. Its producer token would fence
both the seal retries and stale recovery of an orphan. The flag is unset
in prod, so this is inert today.
- **Seal retries.** A retired recording stays in `_unsealed_rotations`
until `process_conversation` returns True.
  - Refused seals retry after 15, 30, 60 and 120 s.
- Teardown (`routers/listen/runtime.py`, before the current row is
handled) runs `drain_rotations` for one last attempt.
- On hand-off, the socket drops the producer token, so the cap stays
reachable only by live rows.
- The row is then left `in_progress` for
`LiveConversationController.recover_stale_in_progress`
(`routers/listen/conversations.py`). That runs in `process_pending` on
the owner's next listen connection, for rows quiet for an hour, and
seals through `process_conversation`.
- Correction to the previous round: the quiet check armed at creation
does not recover a v3 recording. `recovery_admission_refusal` returns
`terminal_no_derived`, because `triggers.mark_new` stamps
`terminal_no_derived_effects` on every v3 recording. This holds for any
crashed v3 socket today, not only for rotation.
- Counter:
`omi_listen_v3_rotation_total{outcome=rotated|same_row|create_failed|seal_failed|seal_retry|handed_off|other_owner}`
through the reason-enum core (`RecordingRotationOutcome`, family
`recording_rotation`).
- **Builder** (`database/conversations_v3.py`
`_mark_successor_pending`). It applies only when the latest spoken
recording carries `v3_rotation_cap_seconds`, which only rotation writes.
In that case it keeps the stretch open while a later recording is in
progress under that cap + 15 s, or processing for under 15 min. With
rotation off, no row has the stamp, and the builder behaves exactly as
on main. The successor query is `.select()` over 8 metadata fields,
limit 8, single-field `started_at` index. It is registered in the
query-shape drivers.
- **Switches.**
- `CONVERSATIONS_V3_RECORDING_ROTATION`: `off` (default), `cohort`
(members of the `v3-recording-rotation` rollout cohort) or `on`.
- The cohort lives in the `rollout_cohorts` collection. No uid goes in
deploy source.
- All three envs are in `deploy/runtime_env/_base.yaml` (composed
`runtime_env.yaml`) and both listen chart values files, as
`off`/`180`/`300`. They are also in `config/feature-flags.yaml`, the
rendered registry and `deployment-setting-classification.json`.
- Changing any env value rolls backend-listen. Membership changes do not
roll (60 s cache).

## Canary for one owner

1. In `backend/deploy/runtime_env/_base.yaml` (gke backend-listen env)
and `backend/charts/backend-listen/prod_omi_backend_listen_values.yaml`,
set `CONVERSATIONS_V3_RECORDING_ROTATION` to `cohort`. Recompose with
`python3 backend/deploy/compose_runtime_env.py`, merge, then roll listen
with `gcp_backend_listen_helm.yml` (environment=prod, branch=main,
expected_sha, mode=deploy, image_tag). With an empty cohort this is
still off for everyone.
2. Write the uid to a private file (0600), then run:
`GCP_AGENT_TIER=prod-operator backend/.venv/bin/python
backend/scripts/rollout_cohort.py --uid-file <file> --cohort
v3-recording-rotation --project based-hardware --environment prod --add
--apply`
It takes effect within 60 s. To undo, use `--remove`, or set the env
back to `off`.

The image must contain this PR first: `gcp_backend.yml` mode=build-only,
then the listen helm deploy. The builder change is inert until rotation
stamps a row, so its deploy order does not matter.

## Checks

1. **Custody at the cut.** The first version of this PR was wrong. It
sealed the old row while the socket kept binding frames to it, and
`server_batch_audio_closed` is not set while the socket is active
(`batch_close.py:46`). With the reconnect flag off, late frames extended
a `processing` row's window. With it on, `note_server_batch_audio`
refused them and poisoned `uncommitted`. The new order makes it
impossible for a frame to join the old row once its seal starts.
- Proof: `tests/unit/test_listen_v3_rotation_custody.py`, parametrized
with `LISTEN_BATCH_RECONNECT_ENABLED` off and on.
- It uses the real `LiveAudioArchive` (durable outbox on the hermetic
`remote` bucket), the real `note_server_batch_audio` / `_received` on
`StrictFirestore`, and the real `_rotate_v3_recording` →
`finish_recording` → `process_conversation` → `close_batch_archive`.
- 120 frames are produced concurrently. Each is bound before a yield,
like the receiver. One extra frame is bound to the old id and appended
after the seal.
- Assertions: every frame is committed exactly once; each frame lies
inside its own row's window; the sealed window is identical before and
after; old frames all precede successor frames; `uncommitted` is empty;
the archive did not fail; the old producer token is dropped.
- Mutation check: with the retarget line removed, the reconnect-off case
fails with the sealed window growing from (1000.00, 1000.46) to
(1000.00, 1001.21), and the reconnect-on case never seals.
- The receiver's ownership bookkeeping is not retargeted. Its sample
ranges (`_note_accepted_frame`) only place live-STT transcripts, which
batch-only sockets do not run. The custody ACK checkpoints per-channel
frame sequence numbers, not conversation ids.
- The test proves the ACK publishes once over retargeted frames, with
nothing left pending. It also bounds the skew: the successor's
`started_at` equals its `server_batch_audio_start`, which is the frame
right after the sealed window, within one 10 ms frame of it.
- Not real in this test: `create_new_in_progress_conversation` is a
binding-equivalent stub. The real create path is covered by the
continuation test below. It creates the server-batch row with yields
that stand in for Firestore round trips, then switches
`current_conversation_id`. `schedule_finalization` is stubbed to record
the window and set `processing`. The full create path needs the
recording-session, Redis and calendar stack and was not exercised.
- Words: a word that straddles the cut lands whole in one recording's
audio, but each recording is transcribed separately, so a word cut by
the 300 s cap can be split across two transcripts. Cuts at a 1.5 s pause
avoid that.
1b. **Rotation on a phone socket, through the real create path**
(`tests/unit/test_listen_v3_rotation_continuation.py`). This uses the
repo's `CaptureHarness`: the real `create_new_in_progress_conversation`,
real `resolve_live_continuation` on `StrictFirestore`, and
`client_conversation_id='original'`.
- The old call (no supersede) returns the same row, which reproduces the
bug.
- Four consecutive rotations give 5 distinct recording ids. The pointer
names each new successor in turn, every retired recording is sealed and
stamped, nothing is deleted, and nothing is left unsealed.
   - A reconnect afterwards resumes the last successor.
- Mutation check: with `supersede` removed, the test fails with `sealed
== []`.
- `supersede_live_continuation` refuses a pointer owned by another
generation and returns `absent` for a missing origin.
1c. **What the phone does.** The app parses `conversation_session` as
`UnknownEvent` and ignores it
(`app/lib/backend/schema/message_event.dart`).
- A rotation seal sends `memory_processing_started` for the retired
recording. That is the same event and the same `process_conversation` →
`schedule_finalization` path a quiet seal uses today, so the quiet seal
is the precedent.
- On that event the client keeps streaming on the same socket.
`CaptureController.onMessageEventReceived`
(`app/lib/services/capture/capture_controller.dart:4089`) stamps the
session's WALs with the recording id (`_finalizeAndStampSession`) and
starts a new session.
- v3 Home re-reads the list and the live conversation on a capture
event, at most every 10 s, instead of adding the recording as a row
(`app/lib/pages/conversations/conversations_page.dart:411`).
- Difference from a quiet seal: frequency. A batch recording's
`memory_created` arrives only after GPU transcription, which takes more
than 30 s. So the 30 s fallback runs `_confirmSessionWalsRetained(...,
failClosedReason: 'missing_conversation_event')` and auto-syncs the
retained WAL for every rotated recording, as it already does after each
quiet seal.
- Consequence: about one WAL upload per 3-5 min instead of one per
quiet-ended recording. These sync pieces then hit the containment issue
in check 4.
   - I read the code. I did not run the 1.0.593 client.
2. **Stitching.** `outline.stretches` splits only on a 5 min gap or a
manual cut, so recording boundaries do not split a conversation.
`planner.windows/build` copy lines in order across recordings. The
finish rule is what could false-split: the commit clears `v3_pending` on
an untranscribed live successor. `_mark_successor_pending` handles that
for rotation-sealed rows. Tests:
`test_untranscribed_successor_keeps_the_stretch_open` (7 cases),
`test_a_recording_rotation_did_not_seal_keeps_the_five_minute_rule` and
`test_rotated_recordings_stitch_into_one_stretch_in_order`.
3. **Load, for a 1 h continuous capture.** Before: 1 recording and 1
batch unit. After: 12 recordings (300 s cap) to about 20 (180 s +
pause). Audio seconds are unchanged. Per recording, there is one more of
each: successor create (recording-session open, producer claim,
quiet-check arm), finalization request and pusher close, intake claim,
admission authorize, batch job and lease docs, merge head, projection,
cap stamp. v3 reconcile stays a named task per owner-minute. Unfinished
stretches make no LLM call. The builder adds one ≤8-doc metadata query
per pass. Default off means no load change until a canary.
4. **Sync bridges.** The reviewer is right. `batch_target_contains`
(`utils/sync/live_overlap.py:105-131`) refuses a piece that starts
before a target, or ends after a sealed one. Prod sample, Nik,
2026-11-18, metadata only:
   - 15 of 17 listed live recordings had overlapping WAL pieces.
- Of the 18 pieces, 13 sat inside one recording (10 merged, 3 pending).
- 5 already span a recording boundary today and stay standalone
legacy-layer rows. Examples: `e87bfed2` 18:57→19:33 starts before
`4170f9cf`, and `09be1e39` covers three recordings.
- With 3-5 min recordings, pieces over a few minutes would stop merging.
That is 3 of today's 10 merged pieces (5.5, 5.0 and 30.3 min, including
`80484b85` against `4170f9cf`).
- What the user would see: a legacy-layer sync card for the same speech
next to the v3 derived conversation, once its settling hold ends. The v3
"same text ±2 s" dedupe does not catch two independent transcriptions.
- Not fixed here, and a blocker before `on`. The cohort canary should
watch for these duplicates. Fleet-wide frequency was not measured: no
collection-group index exists to query bridges across owners.
5. **Legacy untouched.** `recording is True` plus `server_batch_owned`
is required. Tests: `test_legacy_row_never_rotates` and
`test_off_is_the_old_lifecycle` (unset, `off` and empty-`cohort` all
keep the main lifecycle, including the quiet seal). The builder gate is
the row stamp.
6. **Calendar.** A meeting does not block v3 rotation
(`test_a_calendar_meeting_does_not_block_v3_rotation`). v3 conversations
come from transcript windows, and `create_new_in_progress_conversation`
re-attaches the active meeting to the successor.
7. **Speaker labels.** Batch diarization labels are per unit, so
`SPEAKER_0` in recording N is not `SPEAKER_0` in N+1. The owner
(`is_user`) and named people (`person_id`) are resolved per recording
from embeddings (`utils/conversations/speaker_resolution.py`), so they
stay consistent. `recording_carry` copies manual speaker assignments
into the successor. What breaks: unnamed voices get different S-numbers
every 3-5 min inside one derived conversation, both in the copied
transcript and in the outline input. The outline prompt already treats
S-numbers as unreliable. Shorter recordings also give speaker resolution
less audio per voice. That may lower wearer recognition, which v3 needs
before it hides background talk. Not measured.

## Latency, from "conversation ends" to "derived row visible"

- **Before** (continuous background speech): unbounded, until 120 s of
quiet or socket close, plus batch transcription. Nik's case was 31 min,
with about 5 min of transcription for a 33.6 min recording.
- **After, for a canary owner:** the first derived in-progress row
appears 3-5 min after speech starts, plus transcription of a 3-5 min
recording. When the conversation ends, the open recording seals within
at most 180 s (usually at the next pause). Notes follow at last speech +
5 min, by the unchanged planner rule. If cafe noise is itself
transcribed as lines, the stretch stays open. It is visible live, but
auto-notes wait. A Home row within about 1 minute is not delivered here.

## Related

David's lane: #25714 and #25659 touch the v3 store and service, not this
`load()` tail or `lifecycle_loop`. #25633 introduced SpeechClock.
`routers/conversations.py` `get_live_conversation` is not touched.

## Verification

- Unit: 4118 passed, 2 skipped. Locally,
`test_cloud_run_metrics_egress_workflow` fails on macOS bash 3.2 (empty
array under `set -u`), and `test_rollout_cohorts` flakes under xdist but
passes alone. Neither touches these files. Earlier round: 3113 passed
and 1 skipped across every `conversations_v3*`, `listen_*`, archive,
outbox, desktop-batch, cohort, runtime-env, flag and query-shape file,
including the new custody and lifecycle cases.
- Lifecycle cases cover: process returns False, successor create fails,
successor resumes the same row, user_stop, quiet tick, episode hold,
producer `boundary_at`, exact threshold boundaries, env tunables, cohort
membership, and off equal to main.
- `backend/scripts/typecheck.sh`: 0 errors. `scripts/pr-preflight
--pr-body-file`: green.
- New tests:
  - seal retry backoff and hand-off;
- a raising seal that is retried, and an admitted seal that drops its
token;
  - teardown drain;
  - failed-create residue restore;
  - retarget chains A→B→C and the 64-entry eviction;
- an orphan left by a crash between create and seal: the real
`quiet.arm` / `quiet.run` refuse it
(`test_a_rotation_orphan_is_left_for_listen_stale_recovery_not_the_quiet_check`),
and `recover_stale_in_progress` seals it on a later connection
(`test_a_rotation_orphan_is_sealed_by_stale_recovery_on_a_later_connection`);
  - runtime teardown awaits `drain_rotations`;
- the reviewer's probe as a test: a failed
`_persist_policy_and_arm_quiet_check` leaves the pointer on the old row,
and the retry moves it;
  - `own_ids` acceptance;
  - a `WebSocketException` closes the socket;
  - the Redis restore;
  - token pop at hand-off;
  - no rotation on reconnect-protocol rows.
- Not verified: no device capture and no dev or prod run. The custody
test stubs the create, while the continuation test runs the real create
without a real archive.

Line-Count-Exception: backend/routers/listen/runtime.py | 1576 -> 1578 |
teardown drains retired v3 recordings before it handles the current row

## Product invariants affected

- INV-MEM-4

Cited because `backend/deploy/runtime_env.yaml` changed. The change only
adds three backend-listen env entries; memory intake and promotion are
unchanged.

## Failure class (fixes)

Failure-Class: FC-transport-liveness-read-as-speech-activity

🤖 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