Skip to content

v3: one card per sit-down, and late speech joins its published card (SCA-4537) - #26769

Merged
Git-on-my-level merged 13 commits into
mainfrom
lane/frag-latency-lab
Nov 30, 2026
Merged

Git-on-my-level merged 13 commits into
mainfrom
lane/frag-latency-lab

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What

Two fragmentation fixes in Conversations v3. Both are on by default behind kill switches.

  1. Sit-down cutting at the default silence gap (CONVERSATIONS_V3_SITDOWN_AT_DEFAULT)
    • Gap marks, SITDOWN_RULE and planner._join_sitdown used to apply only when the silence gap was over 300 s.
    • Production runs the 300 s default, so they never applied there. Topic turns inside one continuous stretch became separate Home cards.
    • On the owner account, 52 of 70 close pairs of visible cards (3 minutes apart or less, 3.3 days) were cuts inside one recording.
  2. Late speech joins its published card (CONVERSATIONS_V3_ABSORB_LATE_SPEECH)
    • When a device sync lands after the card it continues was published, the outline plans both into one conversation. Until now, preserve_finished_windows still made the late speech a second card.
    • Now an unowned line takes the next published owner in the same planned window, and the card's bounds, claims and segment offsets grow to include it. It then gets the one late notes rewrite (planner.late_rewrite).
    • It works backward only: speech after the card's last published line is the live continuation and stays open.
    • A deleted or discarded card is a barrier, so that speech stays its own card and is not lost.
    • Only the live builder absorbs. Re-derive and backfill do not.
  • Absorption skips a card that is still open, and any re-plan after the transcript size check cut the plan.
  • A card takes late speech only while its one late rewrite is still available (unused, within a day), so absorbed speech reaches its notes.
  • A rebuilt card keeps its own source, language and cloud-sync setting.

Also included:

  • the lab's ideal.runs frag scorer (counts only);
  • a new scenario, late_sync_joins_published_card, which reproduces the owner-account split.

Evidence

Owner-day replays (pipeline lab, simulated clock, dev gateway, under $0.30 spent in total).

Base is 5cce841 with the production env overlay; head is this branch. frag counts (Home cards, Home pairs at most 180 s apart) and ideal.runs score against owner-reviewed ideals:

Day Home cards Home pairs Ideal F1 Splits Merges Ideal recall
11-27 27 → 21 17 → 12 (no ideal)
11-18 28 → 16 19 → 6 0.24 → 0.29 55 → 51 19 → 17 8/9 → 9/9
11-17 19 → 19 8 → 5 0.29 → 0.29 48 → 54 10 → 9 2/2 → 2/2
  • Merges went down on both days that have an ideal, so the join does not over-merge.
  • 11-17 is neutral on F1.
  • LLM calls per replayed day ranged from −40% to +37%.
  • Day replays cannot produce the late-sync case (everything is present when the replay plans). The new scenario covers it:
    • absorption off splits the late speech into a second card (323 reads, 85 writes, 13 LLM calls);
    • absorption on joins it (309 reads, 79 writes, 12 LLM calls).

Also measured and not shipped: a longer close timing (900 s gap, 3600 s lock). It halves splits but raises merges (11-18: 17 → 22, 11-17: 9 → 15) and scores lower F1 than this PR on both days that have an ideal (0.28 and 0.25).

Considered and dropped: making End wait only for its own recording. Production never holds a manual-end cut (omi_conversations_v3_finish_held_total was 0 over 24 h, across about 615 manual-end cards), so it buys no live latency. In the lab it cost a second notes pass.

Line-Count-Exception: backend/utils/conversations/v3/service.py | 2259 -> 2264 | the live builder passes the absorption switch and clock into both preserve_finished_windows calls through one typed partial

Tests

  • tests/unit/test_conversations_v3_*.py: 1623 passed.
  • New tests:
    • test_conversations_v3_late_speech_absorb.py: backward only, live tail stays open, deleted and discarded barrier, switch off.
    • test_late_overlapping_recording_joins_the_finished_conversation: service level, four passes; bounded claims, bounds grow, no duplicate segments.
    • test_sitdown_cutting_applies_at_the_default_gap_by_default.
  • Tests that contrast hard topic boundaries at the default gap now pin the switch's off path.

Rollout

On by default, with kill switches:

  • CONVERSATIONS_V3_SITDOWN_AT_DEFAULT=off restores hard topic boundaries at the default gap.
  • CONVERSATIONS_V3_ABSORB_LATE_SPEECH=off restores separate late cards.

The registry rows for both switches follow in a separate PR. Under R-20261130-01, a PR that touches config/feature-flags.yaml is held to every overdue row (SCA-5831).

Readback after serving: owner Home pairs per day from a fresh snapshot (baseline: 70 pairs in 3.3 days), and summary_writes_total{kind=rewrite}.

Pipeline lab

Pipeline lab scenarios: passed (17 scenario(s) x2, jobs 4, stt replay, 88.4 s, ref dd0899b0fcce dirty)

scenario outcome checks seconds transcripts reads writes no-op writes stt llm
audio_single_recording_finish passed 9/9 11.795 synthetic 188 53 5 2 7
finish_after_long_reconnect_gap passed 8/8 12.206 scripted 238 65 7 1 7
finish_after_reconnect_late_transcript passed 8/8 11.908 scripted 267 75 8 1 8
finish_after_second_close passed 10/10 12.049 scripted 297 75 12 1 7
finish_cloud_audio_off passed 9/9 10.963 scripted 182 54 5 0 7
finish_double_tap passed 11/11 10.887 scripted 197 56 5 1 8
finish_next_opens_before_close passed 10/10 10.532 scripted 235 69 7 1 8
finish_no_closed_recording passed 9/9 10.45 scripted 166 48 4 0 7
finish_on_visible_conversation passed 10/10 10.041 scripted 170 48 4 0 7
finish_privacy_refused_fast_finish passed 8/8 7.987 scripted 37 8 1 0 0
finish_single_recording_fast passed 9/9 8.26 scripted 200 56 5 1 8
finish_transcript_never_lands passed 7/7 7.621 scripted 237 66 7 0 7
home_paging_past_hidden_runs passed 8/8 8.06 scripted 1027 48 4 0 7
late_sync_joins_published_card passed 9/9 7.784 scripted 309 79 7 0 12
speaker_owner_absent passed 8/8 7.298 local 174 59 4 1 7
speaker_owner_and_person_finish passed 8/8 6.317 local 173 59 4 1 7
speaker_partial_final_pass_keeps_voices passed 8/8 7.615 local 159 56 4 1 6

Coverage: all 17 committed scenario(s) ran x2 and evaluated their checks.

🤖 Generated with Claude Code

Git-on-my-level and others added 12 commits November 29, 2026 18:14
…h own-hold; frag scorer; late-transcript End scenario

Failure-Class: none (lab arms, default off)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eted-card joins, live tail stays open)

Failure-Class: none (lab arm, default off)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Late speech that the outline planned with a published card now joins it (backward only, never into
a deleted or discarded card, never the live tail), and a manual-end cut waits only for the finishing
recording's own transcript. Both are default-on kill switches:
CONVERSATIONS_V3_ABSORB_LATE_SPEECH and CONVERSATIONS_V3_FINISH_OWN_HOLD_ONLY.

Failure-Class: fragmentation-late-speech

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Production never holds a manual-end cut (omi_conversations_v3_finish_held_total was 0 over 24 h
across ~600 End presses), so waiting only for the finishing recording buys no live latency. In the
lab it paid a second notes pass whenever the earlier transcript landed within seconds of End.

Failure-Class: fragmentation-late-speech

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

Failure-Class: fragmentation-late-speech

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sit-down cutting (gap marks, SITDOWN_RULE, planner._join_sitdown) only applied above the five-minute
gap, and production runs the default, so topic turns inside one continuous stretch became separate
cards. It now applies at the default gap too, behind the default-on kill switch
CONVERSATIONS_V3_SITDOWN_AT_DEFAULT. Owner-day replays: 11-27 home 27 -> 21 cards; 11-18 home 28 -> 16,
ideal F1 0.24 -> 0.29, merges 19 -> 17; 11-17 neutral (F1 0.29 both, merges 10 -> 9).

Failure-Class: fragmentation-topic-cut

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Failure-Class: fragmentation-late-speech

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts with the transcript size cap (#26705): absorption runs only on a plan the size check has not
cut (no fallback budgets) and never joins a card that is still open, so the size check keeps owning
an open card's extent. The open-card size-cut test pins sit-down off (main's topic cuts).

Failure-Class: fragmentation-late-speech

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Under R-20261130-01 a PR that touches config/feature-flags.yaml is held to every overdue registry
row, so the two rows (CONVERSATIONS_V3_SITDOWN_AT_DEFAULT, CONVERSATIONS_V3_ABSORB_LATE_SPEECH) land
in a follow-up once the registry debt clears (SCA-5831). Both switches are documented in the PR.

Failure-Class: fragmentation-late-speech

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Failure-Class: fragmentation-late-speech

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Panel review-20261130t060308-b501:
- F1: absorbed speech reaches the card's notes only through its one late rewrite, so a card whose rewrite
  is spent (v3_rewrites) or more than a day past its end takes no late speech; the speech keeps its own
  card, as with absorption off.
- F2: a rebuilt card keeps its own source, language and private_cloud_sync_enabled instead of
  re-deriving them from a first line that absorption moved onto a late recording.

Failure-Class: fragmentation-late-speech

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Backend unit shard 7 fails on tests/unit/test_app_client_schema_inventory.py::test_inventory_openapi_route_response_decode_migration_complete. That failure is not from this PR: main's latest Backend Unit Tests run fails on the same test, and this PR changes no app/ files. The v3 and lab tests this PR touches all pass.

…ard)

Measured with scenario run --trace-calls over all 18 committed scenarios, then scenario reach.

Failure-Class: fragmentation-late-speech

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit b894910 into main Nov 30, 2026
68 of 70 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/frag-latency-lab branch November 30, 2026 06:54
Nizarius added a commit that referenced this pull request Nov 30, 2026
)

## What changed and why

A builder task held its `conversations-v3` slot through everything it
did for an owner: grouping, the outline call, then every owed summary
with its derived effects, memory extraction included. On 2026-11-30 the
model vendor slowed down, every slot was held longer, the queue
saturated for hours and a user's End waited 12 to 36 minutes for its
title and summary behind automatic work. User Ends are under 1% of
summaries.

The work is now three stages, each one function, and one hand-off
(`utils/conversations/v3/handoff.py`) decides after a stage whether the
next one runs in the same task or as a task of its own:

| Trigger | Grouping and title | Summary | Memory extraction |
|---|---|---|---|
| Automatic (text lands, silence closes the conversation) |
`conversations-v3` (existing) | `conversations-v3-summary` |
`conversations-v3-memory` |
| User End or Finish | `conversations-v3-user`: one task does both, for
that conversation | same task | `conversations-v3-memory` |
| Late speech joins an automatic conversation that already has a summary
| `conversations-v3` | rewrite on `conversations-v3-memory`, the lowest
priority | `conversations-v3-memory` |

- **Grouping and title**: `service.reconcile`, unchanged up to its
commit. Afterwards it hands each owed summary off instead of writing it.
A background pass that finds a user-ended conversation owed sends its
summary task to the user queue.
- **Rewrites yield to first summaries**: the rewrite of an automatic
conversation's summary (`v3_rewrites` on the row, not user-ended) is
handed to `conversations-v3-memory`, the queue of the work nobody waits
for, instead of the summary queue; it is still a summary task on the
reconcile route. A user-ended conversation's rewrite goes to the user
queue. The choice is `handoff.summary_queue`, used by the grouping task
and the sweep. Rewrites were 2 to 3% of summary writes until late speech
started joining its published card (#26769) and 20 to 26% in the hours
after.
- **Summary**: `service.summarise`, the loop body the grouping task ran
before, for one conversation. Summary tasks reuse `POST
/v1/conversations-v3/reconcile` with extra payload fields (`stage`,
`cid`): a revision that predates this ignores them and runs a whole
pass, which writes the same summary.
- **Memory**: `utils/conversations/v3/memory.py`. The summary pass
leaves the step out and its settle arms `v3_memory_pending` with the
hash of the content it read, in the transaction that marks the summary
done. The memory task has its own route (`POST
/v1/conversations-v3/memory`), so a revision without it answers 404 and
the queue retries. It skips a conversation whose summary is owed again,
and a summary that settles while it runs re-arms the marker, so the last
extraction reads the text of the last settled summary. It does not hold
the summary lease, so a rewrite never waits for an extraction. One
extraction per owner at a time is a Redis lock (fail open; concurrent
extractions for one owner lose each other's compare-and-set and repeat
their model calls). A memory failure no longer fails the conversation's
summary: the extraction is tried at most five times, then dropped and
counted.
- **User lane**: `triggers.enqueue` sends a wake that carries a user's
End to `conversations-v3-user`; that task groups the owner in the
foreground and writes that conversation's summary itself. A busy owner
answers 503 and the queue retries after 2 s.
- **Sweep**: for an owner on the new path it re-creates a lost summary
task instead of waking the builder, so a summary backlog does not turn
into idle builder passes.

**The switch.** `stage_queues` is a per-account Omi flag store rule,
default off, read only by the hand-off. Off, every stage runs in the
grouping task as before. Task handlers never read it and serve whatever
a conversation owes, so an account can be switched either way with work
in flight. It exists for the rollout: the end state is every account on,
then the switch and the inline path are deleted.

**Nothing is created by this PR.** The three queues are declared with
`enabled: false` in `deploy/ops/prod.yaml` and `staging.yaml`. Until
they exist every hand-off to them fails, the stage runs in the task that
tried, and
`omi_fallback_total{component="conversations_v3",from_mode="stage_queue"}`
counts it, so an admitted account behaves as with the switch off.

new: capacity. Three Cloud Tasks queues, declared and not created:
summary 64 concurrent, memory 24, user 32 (starting sizes, to be set by
the owner of the rollout). Two metrics:
`omi_conversations_v3_stage_handoffs_total{stage,mode}` and
`omi_conversations_v3_memory_extractions_total{outcome}`, added to the
backend-sync sidecar's allow-list (`deploy/cloud_run_gmp_sync.yaml`), at
most 11 series per instance.

**Rollback.** Deactivating the rule strands nothing. Rolling the code
back to a revision without the memory route is different: memory tasks
answer 404 there until the queue drops them. The runbook gives the order
(deactivate the rule, let the memory queue drain, then roll back).

**Cost.** Measured in the pipeline lab on one automatic conversation,
switch on against off: 2 more Firestore writes (the memory claim and its
finish) and 6 more reads per summarised conversation, the same model
calls. Over the 19 scenarios that existed before: 2.4% more reads and
4.0% more writes with the switch on. With the switch off: no difference
from `main` in any measured count (below).

Not changed: folder assignment, apps, action items, goals and the
webhook stay in the summary task; the 64-slot cap of `conversations-v3`;
the app. A failed model call inside memory extraction is still absorbed
by the extraction (it returns without memories), as before.

Change note:
`backend/docs/listen_pusher_pipeline/changes/2026-11-30-v3-builder-stage-queues.md`.
Runbook: `backend/docs/runbooks/conversations-v3.md` (Stage queues:
order of a rollout, what to watch, rollback and its known limit).

## Product invariants affected

- INV-MEM-4: not changed. Memory extraction still runs through
`extract_memories`, the same admission boundary and canonical writer;
this PR changes only which task calls it and when. It is called for the
stored conversation after its summary settled, instead of inside the
summary pass.
- INV-TASK-2: not changed. Action items are written by the same step of
the summary pass as before; `process_conversation.py` is touched only at
the memory step (an observer that reports a deferred memory extraction).

## How it was verified

Pipeline lab (`backend/testing/pipeline_lab/`), the real v3 code on a
Firestore emulator and Redis with looped-back named tasks on a virtual
clock and a scripted fake model gateway:

- Seven new scenarios, switch on, each run twice with identical results
(`scenario run --repeat 2`): automatic end (each stage on its own
queue), user End (title and summary from the user queue), user End
during a backlog, late text after the summary (the rewrite waits on the
low-priority queue, nothing goes to the summary queue, memory is
extracted once, from the final text), the switch flipped off and on with
work in flight (nothing stranded), missing queues (every hand-off
refused, same end state), failures (a summary model failure and a memory
failure are each retried by their own queue; the memory retry does not
redo the summary).
- User End during a backlog, the 30 Nov shape: the shared and the
summary queue each held by other owners' work for 55 minutes. Switch on:
the End's conversation has its title and summary at the instant its
transcript lands, while the background conversation's summary waits for
the backlog. Switch off, same story: the End's conversation does not
exist until the backlog drains, 847 s later.
- Every scenario that existed before, switch on against off (`scenario
compare --arms .../fixtures/arms/stage_queues.json`): all 19 pass in
both arms, same conversations, and metric `stages` shows the same title
and summary digest and the same memory runs in every scenario. The only
differences are reads (+2.4%), writes (+4.0%) and the stage task counts.
- Switch off against `main` (`scenario compare origin/main --worktree`,
the 19 scenarios): 0 of 223 metric keys differ (reads, writes, deletes,
no-op writes, model calls, speakers, title and summary digests).
- What memory extraction is given, switch on against off (the lab now
records digests of each extraction's input): the transcript lines with
their speaker attribution and the conversation's other fields are the
same in all 19 scenarios. The one field that differs is
`structured.participants` (the stored row's list against the one the
summary pass holds in memory), which the extraction does not read.
- All 26 committed scenarios pass twice (`scenario run --jobs 4 --repeat
2`).

Not verified: nothing ran against real Cloud Tasks, a deployed service
or a real model. No load test was run. The queue sizes are estimates.

## Tests

- `backend/tests/unit/test_conversations_v3_stage_queues.py`: both
counters pass the two sidecar allow-lists; the hand-off table in each
mode; a refused enqueue runs the stage in place and is counted; wake
routing for user Ends with and without the user queue; stage task names
change only with the work; the grouping task enqueues, the user lane
writes user-ended summaries itself; the queue of a summary task by who
waits for it (first summary, automatic rewrite, user-ended); the sweep;
a summary task serves the conversation whatever the switch says; the
settle arms the memory marker only when the pass deferred memory; claim,
finish and attempt cap of the marker; the memory task skips during a
rewrite, leaves a marker a newer summary armed, never takes the summary
lease; payloads from before the split on the new handler; route dispatch
by `stage` and `lane`; busy and provider faults answered as retries.
- Mutation pass on the unit tests: ten single decisions reverted one at
a time (the grouping task always reading the memory marker, claiming
during an owed rewrite, no fallback for the user wake, the user lane
writing every summary, arming memory whenever deferred, a finish that
ignores a newer marker, a refused enqueue that does not run the stage,
deferring memory with the switch off, a summary task swallowing a pass
that cannot begin, an extraction without the owner lock); each made a
test fail.
- `backend/tests/unit/test_pipeline_lab_stage_queues.py`: the lab's
queue model (slots, retries with backoff, filler, missing queues), the
driver's handling of split-stage tasks, the scenario format additions,
the repeat comparison's renaming of hashed random ids, the fake
gateway's scripted failures and the `stages` compare metric.
- Pipeline lab: `stage_queues_*.json` (seven scenarios);
`scenario/reach.json` re-measured.

Line-Count-Exception: backend/utils/conversations/v3/service.py | 2279
-> 2395 | the summary stage is carved out where it already lived:
summarise is the loop body of drain_processing, and its task entry and
the sweep hand-off share this module's lease, load and process helpers,
which the existing tests patch on this module; splitting the file is a
refactor of its own

## UI evidence

UI-Evidence: none -- backend 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 Dec 1, 2026
…s on landing too (#26771)

## What changed and why

Device sync uploads an older talk file by file, often after newer speech
has landed. Only the newest stretch may stay
open, so `outline.stretches` finished every older stretch at once,
however recently its speech landed. The first
file's card was published on arrival. The next file of the same talk,
landing a minute later, could not move that
published boundary (`planner.preserve_finished_windows`), so it became a
second card. Settling on landing exists so
that "an offline batch whose speech is already old must not lock the
moment it arrives", but it protected only the
newest stretch.

Production audit, metadata only, 24 h to 2026-11-30 04:22 UTC: 110
adjacent v3 card pairs with no gap, disjoint
recordings, no manual cut and 50+ words each side. 53 of them involve a
recording that arrived through device sync.
In 21 of those, the first card was built already finished while newer
speech from the same device existed, and its
neighbour landed within 5 minutes; 19 of the 21 had no recording placed
before. That is the case this PR fixes. The
other pairs are batch-lane reconnects (#26749), concurrent double
captures, or uploads more than 5 minutes apart (see
"Not changed here").

**Containment: dark by default.** Everything this PR adds runs only for
owners listed in
`CONVERSATIONS_V3_SETTLE_OLDER_OWNERS` (owner tags `sha256(uid)[:12]`,
or `*`; read per pass), and only with
`CONVERSATIONS_V3_SETTLE_ON_LANDING` on. The default is empty, and then
every pass is main's: no hold, no off-page
sibling lookup, no settlement wake, and `has_pending` and the projection
commit run main's code (the commit's
past-deadline rotation now also applies only to sources the outline held
for settlement). The existing
`CONVERSATIONS_V3_SETTLE_ON_LANDING` stays as it is: it defaults on and
gates main's own landing settlement of the
newest stretch, so turning it off would change main. The new flag is
registered as a rollout
(`config/feature-flags.yaml`): merge dark, then a test allowlist,
internal owners, and `*`. Proof: `scenario compare`
with the allowlist emptied on both arms shows every committed scenario
identical to main (below), and unit tests
pin the flag-off loader, `has_pending`, commit and plan to main's.

**The mechanism.** Live builder passes (`service.reconcile`, never
derive or on-open) pass `settle_older` to
`outline.stretches`. Under `CONVERSATIONS_V3_SETTLE_ON_LANDING` (default
on), `_settle_older` leaves out an older
stretch when all of these hold:

- every recording in it is a device-sync landing
(`outline.device_sync_landing`: sync intake stamped its
`sync_content_revision`, a positive integer; no other sync stamp, such
as `sync_recorded_end_at`, counts; and it is
not a live capture that sync extended, `sync_live_target`), all from one
known `client_device_id`;
- a newer stretch holds speech from that same device, or the stretch
already stores a deadline;
- its speech is older than the lock delay, but it landed less than the
lock delay ago;
- no transcribed audio covers the silence gap after its last line
(`_audio_covers`: completed and transcribed
recordings only, on capture-time ends, never an arrival-stamped
`finished_at`);
- no conversation has placed any of its recordings (no claims), and none
of them has lines in another stretch;
- it is not bounded by a manual end or the window cap.

Its recordings stay pending until the lock delay after the stretch's
last landing (`outline.SETTLE_UNTIL`, kept
pending by `preview_wakes`). A file that lands in that window joins the
stretch. Once the wait ends, the stretch is
planned as one finished card. No second open card is ever committed.
Every other capture keeps main's publication
schedule: live, batch and rotation captures whose transcript lands late,
separate-origin Finish predecessors, and
synced speech behind only another device's speech.

**The stored deadline.** The projection commit writes the deadline to
each held recording as `v3_settle_until` and
clears it once the stretch is planned. Without it, the wait would end as
soon as the newer conversation locks and
leaves the loaded page. The older stretch would then be published as an
open card, finished by the next newer
speech, and the next file would split again.
`sync_files_after_newer_speech` covers that sequence.

**The new wake.** `_after_projection` enqueues a Cloud Task at every
distinct deadline it holds
(`triggers.enqueue(settlement=True)`) with payload `trigger:
"settlement_deadline"` and its own per-second task name,
so a same-minute arrival wake cannot swallow it, and each held row keeps
its wake whichever page later loads it.
`routers/conversations_v3_tasks.py` answers 503 for this trigger while
the builder lease is busy, so the
queue retries it; untriggered and `native_manual_ready` requests behave
as on main. A deadline already past (a sibling
still missing) re-checks once a minute through the same settlement task,
never an ordinary minute wake. Each wake is
retried briefly (three attempts); one that still cannot be created makes
the pass report more work.

**The pass chain.** `service.has_pending` keeps main's read first. Only
when every other pending source it finds is
held until a future settlement deadline does it read in
`v3_pending_since` order for owed work ahead of them. Held
sources on other pages therefore no longer keep the chain reconciling
and waking the owner every minute; their
settlement task plans them. When it finds only such holds, it also
re-creates the settlement task of the earliest one
off the page (idempotent by name) and reports more work until that
succeeds, so a hold whose wake failed after the
commit is recovered from its stored deadline even if its source never
returns to a page: no hold ends up with
neither a wake nor a continuation.

**The new query.** The pending page is ordered by `v3_pending_since`,
not capture time. When it is full, a held
file's sibling can sit off the page, and the stretch would settle
without it. Then, and only with settling on landing
on (the same switch the builder reads), `load()` looks for the off-page
pending siblings of held device-sync files
(`_hold_for_pending_siblings`, on the existing
`conversations_v3_pending_capture_continuation` index):

- seeds are unplaced device-sync files with a known device whose old
speech landed within the lock delay, or that
  store a deadline; ordinary recordings never qualify;
- both sides use capture time (`capture_span_without_transcript`, never
an arrival-stamped `finished_at`): it reads
captures that start within 20 minutes of a seed cluster's capture span.
A sibling is evidence only with the same
known, non-empty device and a gap strictly below the silence gap, as
grouping joins speech;
- it reads capture metadata only. It never decodes a sibling or adds it
to the pass, so an optional sibling can
trigger no transcript (lake) read and no neighbour reads. Only one of
the device's captures found within the
silence gap of the cluster's span marks the stretch, which waits until
both share a page, up to
  `policy.TRANSCRIPT_WAIT` (15 min) past its deadline;
- one pass reads at most 32 documents and spends at most 10 s
(`SIBLING_SECONDS`, far inside the 240 s builder lease)
for every held cluster across all its load attempts (`SiblingReads`,
created per reconcile pass beside
`UnlockedPage` and shared by the bounded-load ladder and its batch-cap
retry), 16 documents at a time, each query
within 3 s. Each RunQuery's whole limit is taken from the allowance
before it is sent, and it is never resumed
(`FIRESTORE_NO_RETRY`: the SDK's resume after a mid-stream error asks
for the same limit again), so no call can
return more than was charged; a finished call gives back what it did not
return;
- a lookup that cannot finish (the allowance is spent) or fails marks
nothing: the stretch keeps main's plan. A
failure (a read, or a capture field it cannot parse) ends the lookup for
the rest of the pass, every later load
attempt included (`SiblingReads.failed`), is logged and counted as a
degraded fallback, and the pass goes on. Main's
  load path is unchanged with the switch off.

**Stored data and clock arithmetic are best effort.** Every stored field
this path reads goes through
`outline.instant`, a guarded capture clock and bounded audio durations:
a value that is not a valid instant in
2000–2100 or a valid duration counts as absent. Every clock sum on the
path (skew, lock delay, transcript wait,
deadlines, coverage, lookup windows) goes through one helper,
`outline.shifted`, which gives no result when the sum
overflows or leaves that range; the caller then keeps main's plan. Only
an eligible stretch's clocks are read.
`_audio_covers` skips a row it cannot read (no coverage), an unreadable
stored deadline is no hold, capture spans
treat an unreadable field as absent, and in `has_pending` an unreadable
stamp is owed work, as on main. A failed
pending-order read in `has_pending` (3 s timeout, never resumed) keeps
main's answer, and `has_pending` answers owed
work the moment it reads it, so a later failure of the same read cannot
lose it. None of them fails the pass.

The queries are registered with the Firestore query-shape drivers.

**Observability.** `omi_conversations_v3_settle_older_total` counts
passes that hold an older stretch, and
`backend-sync`'s managed Prometheus keep-list scrapes it
(`deploy/cloud_run_gmp_sync.yaml`).

**Relation to #26769.** Late-speech absorption joins an earlier file
into a later published card, backward only, and
costs a notes rewrite. It cannot join the upload order, which is the
shape reproduced on production below. This PR
joins both orders without publishing the partial card first. Absorption
still applies wherever this PR keeps main's
plan.

## Not changed here (follow-ups)

Review rounds had added the changes below on shared paths. None is
needed to keep the older talk on one card, so this
branch restores main's code for each (`f4d380410d`). Main already lives
with future `v3_pending_since` stamps from
held Finishes and previews: such a recording stays pending and is
planned by the deadline wake or any pass that loads
it. Each item is a separate follow-up:

1. **Pull a future `v3_pending_since` back to now when speech lands or a
recording is re-armed.** This covers the live
transcript writer (`database/conversations.py`
`update_conversation_segments`), `mark_pending` and
`promote_manual_end`. It would make a held recording with fresh speech
head the pending page on its first pass,
   instead of at its deadline.
2. **Clamp a future `v3_pending_since` on Finish and native re-arm**
(`_window_tail_plan`, `_finish_capture`,
`permits_native_source`). A deferred older stretch is never the newest
capture a Finish targets.
3. **Split unreadable recordings into terminal and retryable failures.**
Terminal ones would be a missing blob, a
shredded key, a missing file or corrupt segments; retryable ones decode,
type or fetch errors. Retryable ones would
stay pending on a rotating retry, and an older stretch would wait while
a sibling is temporarily unreadable. Main
already treats corrupt segments as unreadable
(`TranscriptSegmentsDecodeError` is a `ValueError`).
4. **Treat a lake-fetch outage (`TranscriptPointerFetchError`) as a
retryable race (`recording_decode_retryable`)**
instead of failing the pass, on the main load path. (The new sibling
read already isolates its own failures.)
5. **Keep a transient lake fetch on an unlocked preview's source out of
the owner's deterministic backoff.**
6. **Count only due pending work in the pass chain for every kind of
hold.** `has_pending` now skips settlement holds
only (see "The pass chain"); main's other future holds keep their
behaviour.

Also not changed: device-sync uploads that land more than 5 minutes
apart (28 pairs; the builder has no sign that
more audio is coming, so this needs a client signal such as the phone's
pending WAL count), and concurrent double
captures (29 pairs, a duplicate-capture problem, not a reconnect).

## Expected latency cost

- **A device's synced old speech landing behind that device's newer
speech, with no transcribed audio after it:** its
card appears up to the lock delay (5 min) after its last file lands,
instead of at once. That is the wait the
newest stretch already has. Production, same 24 h, metadata only: 25,408
of about 116,000 completed v3 cards were
built from speech over 5 minutes old and finished within 4 minutes. In a
random 1,500-card sample, 442 had no
transcribed audio covering the next 5 minutes (the `_audio_covers`
rule); 213 of those were device-sync files from
one device, and 186 had newer speech from that device before the card
was built. So about 3,150 cards a day
(about 2.7%, two thirds of them hidden from Home) wait up to 5 more
minutes. Before this round the gate let up to
  about 7,500 a day wait.
- **A pending sibling off the page:** only on a full pending page; that
stretch waits until both share a page, up to
  15 minutes past its deadline, re-checked once a minute.
- **Everything else is unchanged:** live, batch and rotation captures,
synced speech behind only another device's
speech, the newest stretch, older stretches followed by transcribed
audio, placed stretches, backfill, re-derive
  and on-open.
- **Reads and writes:** the sibling lookup runs only on a full pending
page with the switch on, for held device-sync
files: at most 32 metadata documents per pass, and no transcript read.
`has_pending` reads a second page only when every other pending source
it
found is held until a future deadline. A held stretch writes its
deadline once (again when a new landing moves it)
  and gets no outline call until it is planned. Lab, all 27
scenarios against main (flag on): 33 fewer reads, 21 fewer writes, 7
fewer LLM calls and 3 more no-op writes, all in the new
  scenario; flag off, none.
- **Default:** none of the above. With
`CONVERSATIONS_V3_SETTLE_OLDER_OWNERS` empty (the default) nothing
changes;
the numbers above are for `*`, and a test allowlist costs only its
owners' share.
- **Rollback:** empty `CONVERSATIONS_V3_SETTLE_OLDER_OWNERS`, or
`CONVERSATIONS_V3_SETTLE_ON_LANDING=off` on the
  builder runners. That also turns off landing settlement
for the newest stretch: at the default timing every stretch then counts
from its last speech, and the sibling read
  does not run.

## Product invariants affected

none

## How it was verified

- **Review round 1 replays.** The reviewer's replays are tests now
(synthetic rows). On `f3c75432bb` 18 cases fail,
  each one below; here they pass:
- **Ordinary captures:** a live batch capture landing late behind
another device's speech, with and without a
rotation stamp, gets its card on the first pass and stores no deadline
(it was held 280 s). Main's separate-origin
Finish test (`test_conversations_v3_finish_late_predecessor.py`) is
restored unchanged and passes. Live captures,
sync-extended live captures, another device's newer speech and an
unknown device each keep main's plan.
- **Read cost:** with the switch off, a full page of 32 seeds, each with
65 pending captures behind it, reads one
capture-order document, as main does (it read 2,081). Ordinary
recordings never seed the read with the switch
on. 32 held sync clusters share one budget of at most 32 documents and
wait (bounded) for what it did not finish.
- **Capture time and isolation:** an arrival-stamped `finished_at` no
longer stretches a seed onto another device's
recording an hour later. Another device's adjacent capture, or one of
its own device's an hour away, does not
hold a sync file; its own device's off-page sibling does, without being
read, and a lake fault on that sibling
    cannot fail the pass.
- **Continuation:** two held rows across a one-source page no longer
keep the pass chain going, owed work still
does, and an overdue settlement wake keeps its own task name next to an
ordinary wake of the same minute.
- **Review round 2 replays.** On `776621f5eb` 9 cases fail; here they
pass:
- **Budget:** sibling streams that fail after 15 documents read at most
32 in all (they read 480), and the
bounded-load ladder's 32-, 8- and 1-seed attempts share one 32-read
budget (they read 96).
- **Best effort:** an off-page sibling next to another device's
historical card, whose lake read fails, neither
fails the load nor blocks an ordinary card in the same reconcile (both
aborted). The lookup never decodes a
sibling; a held file waits for its device's off-page sibling without
reading it, and the two form one stretch
    once they share a page.
- **Wakes:** two holds with distinct deadlines each get a settlement
task, so the second keeps its wake after the
    first deadline's one-source pass loads only the first.
- **Review round 3 replays.** On `8d3432b10e` 7 cases fail; here they
pass:
- **Budget:** the installed SDK's RunQuery stream on a fake transport
that breaks every 15 results makes one RPC
and stops (it resumed with the original limit and read 51 documents
against 32).
- **Best effort:** a seed whose stored audio duration overflows a
timedelta neither fails the load nor blocks an
    ordinary card in the same reconcile (both aborted).
- **Wakes:** one transient failure creating the later deadline's task is
retried and the pass commits (it raised,
and the later hold had neither a task nor a continuation); a settlement
wake that cannot be created is reported
as more work; and an off-page hold whose wake cannot be created keeps
the chain going until a pass creates it.
- **Review round 5 replays (the allowlist on).** On `8c48da5abd` 22
cases fail; here they pass:
- **Time:** a year-9999 landing on an ordinary older card, a year-9999
stored deadline, and a year-9999 coverage end
no longer overflow before the commit; the ordinary Home card is
published, as on main. Clock sums that leave
    2000–2100 give no result.
- **Optional I/O:** a stalled optional query takes its 3 s timeout, not
RunQuery's 300 s past the 240 s lease: the
    pass commits and publishes (it returned `raced` with no Home card).
- **Evidence:** a candidate with no device ID, or exactly a silence gap
away, no longer holds the seed across three
    passes; it is published on the first, as on main.
- **Provenance:** a malformed `sync_recorded_end_at` is no provenance (a
normal recording behind newer same-device
speech was withheld); only a positive integer `sync_content_revision`
counts.
- **`has_pending`:** an owed row read before the stream fails is kept:
true, as main answers.
- **Containment:** with the owner off the allowlist, two synced files
are planned on arrival as on main (two cards,
no stored deadline), the loader runs no sibling query, `has_pending` is
main's ids-only read, and the commit
    writes no settlement field.
- **Review round 4 replays, and the audit of the new path.** On
`46c4b82471` 19 cases fail; here they pass:
- **Parsing:** a legacy row whose optional `recorded_start` is not an
instant no longer aborts the reconcile, and
its ordinary card is published, as on main. Unreadable coverage fields
count as absent (the next readable field
still proves coverage), an unreadable stored deadline is no hold,
capture spans read unreadable stamps, absurd
audio durations and odd types as absent, and `has_pending` counts
unreadable stamps as owed work.
- **Lookup results:** one interrupted sibling query and a real claim
closure that overflows the 32- and 8-seed
loads: the failure is carried through the ladder, the one-seed pass
makes no further sibling read, and the card
is published at its deadline, as on main (it was held 60 s past it). An
allowance spent before a cluster is
reached, or a lookup that cannot finish, keeps main's plan; a failed
pending-order read keeps main's answer.
- **Pipeline lab on the merged tree (`7d57d903e0`, main `e26598ae7f`
merged in), against main at `197be6283a`, all 27
  committed scenarios.** The new scenario turns the allowlist
on in its own `env` (`CONVERSATIONS_V3_SETTLE_OLDER_OWNERS: "*"`); every
other scenario runs the default (off).
- **Flag off** (`scenario compare --arm main@origin/main --arm head`,
the allowlist emptied on both arms by arm
env): no difference. 27 of 27 scenarios are the same, and 0 of 376
metric keys (operations, outcomes, speakers,
stages, STT routing) differ from main. `sync_files_after_newer_speech`
fails identically on both arms there,
    since its expectations need the feature.
- **Flag on** (`scenario compare origin/main --worktree`): 26 are
identical on both arms (same outcomes,
conversations and operation counts), among them
`late_sync_joins_published_card` (#26769),
`sync_safety_copy_repeats_live` (#26699) and main's seven `stage_queues`
scenarios (#26824).
`sync_files_after_newer_speech` fails on main (the older talk as two
conversations, F1 and F2) and passes here
(one conversation, F1+F2, on Home with notes), with 33 fewer reads, 21
fewer writes, 7 fewer LLM calls and 3 more
no-op writes. Its 15 checks follow F1 through the newer conversation
(the same device's) locking and leaving the
page, an unrelated empty sync wake, another device's capture, and F2
moving the deadline. They check that no
partial card exists at any of those points and that the joined card
appears at the deadline.
- All 27 scenarios with `--jobs 4 --repeat 2 --stt replay` passed in
both repeats (summary below), and
    `scenario/reach.json` is re-measured on the merged tree.
- **Replay tests.** Multi-pass replays drive the real
`service.reconcile` and projection commit on the strict
Firestore fixture, with the older files as device-sync landings of the
owner's device:
- two files of one older talk landing a minute apart while the owner is
talking make one card, in upload order and
    in reverse order, with no partial card in between;
- a second file appended to the first file's recording joins its card.
That is the production shape below; main
    gives two cards;
  - the hold survives the newer card leaving the page;
- with settle-on-landing off, after a placed first file, and behind only
another device's speech, the plan is
    main's.

Loader tests cover the held-sibling lookup across a page boundary (the
held file waits, then joins its sibling once
both share a page), its metadata-only reads, and a lookup the budget
cannot finish (main's plan). Pure `stretches`
  cases cover every condition above.
- **Production repro of the bug, test account, current main.** A 90 s
socket capture landed first, and its card was
open. Then two abutting 120 s WAL files of a talk two hours older went
through `/v2/sync-local-files`, the second
after the first had a card. The first file's card was `processing` 32 s
after its file landed. Sync appended the
second file to the same recording, and it became a second card. Final
state: two cards from one recording, split
exactly at the file seam. Not deployed, so there is no production
after-run; the replay above is that shape.
- **Live-STT lane (not a bug).** On the test account with private cloud
sync off for the run, a 240 s + 460 s call
  with a 1.5 s reconnect gave one card holding both recordings.
- **Unit suites, after merging main.** All `test_conversations_v3*`
files and every file importing the
v3 modules, `transcript_multipart` or `sync_repeats` (78 files) in one
xdist session: 3,797 passed; the 13 failures
are all `test_conversation_events_bounds.py`, which passes alone (21
passed): cross-file `sys.modules`
contamination in a shared session, as `backend/AGENTS.md` warns. The
Firestore query-shape, contract and
index-oracle guards (the held-sibling lookup, its capture-window query
and both `has_pending` paths registered;
`commit_projection`'s digest re-pinned for its allowlist gate), the
pipeline lab tests, main's
`test_sync_live_repeat_lines.py`, `test_home_index_cutoff.py` and
`test_mcp_conversation_detail_paging.py`: 1,742
passed. The feature-flag registry renders and checks clean (its tests:
122 passed). `pipeline_lab affected` selects
every scenario. Pyright: 0 errors. The async-blocker scan finds nothing
in the changed ranges.
- **Preflight:** `scripts/pr-preflight --pr-body-file` with this body
passed every check, including the line-count
  exceptions, the failure class and the product invariants.

## Tests

`backend/tests/unit/test_conversations_v3_settle_older.py` (new, 107
cases; the allowlist is `*` there unless a case
clears it):

- **Pure `stretches`:**
  - the wait and its deadline, and a file landing in the wait moving it;
- main's plan for placed, shared, manually ended, settled,
live-younger-than-the-lock-delay,
followed-by-transcribed-audio, live-capture, sync-extended-live,
other-device and unknown-device stretches, and
    for manual-end and window-cap bounds;
  - the newest stretch is never left out;
- only resolved transcription proves recorded silence, and a skewed
`finished_at` cannot veto the wait.
- **Wake:** at the deadline, a one-minute settlement retry once past it,
and none on derive.
- **Stored deadline:**
  - cleared when a held source turns out unreadable;
  - an unreadable sibling does not block the readable one;
  - the hold survives the newer card leaving the page;
  - the metric is in the sync keep-list.
- **Replays:** the multi-pass shapes above.
- **Loader:** an off-page held sibling keeps the held file waiting until
both share a page, the lookup never decodes a
  sibling, and a lookup the budget cannot finish keeps main's plan.
- **Review rounds 1 to 5:** the replays and audit cases listed under
"How it was verified".
- **Containment:** the flag-off plan, loader, `has_pending` and commit
are main's.

`backend/tests/unit/test_conversations_v3_contract.py`: the
`settlement_deadline` wake answers 503 while the lease is
busy and runs once free. Its task name never collides with a same-minute
arrival wake.

`backend/tests/unit/test_conversations_v3_finish_late_predecessor.py`:
restored to main's version.

`backend/tests/unit/test_conversations_v3_review.py`:
`MemoryQuery.stream` accepts the SDK's retry and timeout options
(the sibling lookup streams with `retry=FIRESTORE_NO_RETRY`).

`backend/tests/support/firestore_conversations_v3_drivers.py`: the
held-sibling lookup (a held sync seed, and its
capture-window query) and both `has_pending` reads are registered query
shapes.

## Pipeline lab

**Pipeline lab scenarios: passed** (27 scenario(s) x2, jobs 4, stt
replay, 272.9 s, ref `7d57d903e090`)

| scenario | outcome | checks | seconds | transcripts | reads | writes |
no-op writes | stt | llm |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| audio_single_recording_finish | passed | 9/9 | 22.706 | synthetic |
186 | 52 | 5 | 2 | 6 |
| finish_after_long_reconnect_gap | passed | 8/8 | 19.743 | scripted |
236 | 64 | 7 | 1 | 6 |
| finish_after_reconnect_late_transcript | passed | 8/8 | 20.508 |
scripted | 267 | 74 | 8 | 1 | 7 |
| finish_after_second_close | passed | 10/10 | 26.509 | scripted | 296 |
74 | 12 | 1 | 6 |
| finish_cloud_audio_off | passed | 9/9 | 25.538 | scripted | 181 | 53 |
5 | 0 | 6 |
| finish_double_tap | passed | 11/11 | 24.488 | scripted | 195 | 55 | 5
| 1 | 7 |
| finish_next_opens_before_close | passed | 10/10 | 18.926 | scripted |
236 | 68 | 7 | 1 | 7 |
| finish_no_closed_recording | passed | 9/9 | 16.804 | scripted | 166 |
47 | 4 | 0 | 6 |
| finish_on_visible_conversation | passed | 10/10 | 16.254 | scripted |
170 | 47 | 4 | 0 | 6 |
| finish_privacy_refused_fast_finish | passed | 8/8 | 12.832 | scripted
| 37 | 8 | 1 | 0 | 0 |
| finish_single_recording_fast | passed | 9/9 | 15.157 | scripted | 198
| 55 | 5 | 1 | 7 |
| finish_transcript_never_lands | passed | 7/7 | 15.157 | scripted | 237
| 65 | 7 | 0 | 6 |
| home_paging_past_hidden_runs | passed | 8/8 | 19.793 | scripted | 1027
| 47 | 4 | 0 | 6 |
| late_sync_joins_published_card | passed | 9/9 | 17.909 | scripted |
308 | 78 | 7 | 0 | 10 |
| reconnect_successor_lands_late | passed | 9/9 | 17.895 | scripted |
367 | 85 | 18 | 0 | 7 |
| speaker_owner_absent | passed | 8/8 | 17.452 | local | 172 | 58 | 4 |
1 | 6 |
| speaker_owner_and_person_finish | passed | 8/8 | 12.886 | local | 171
| 58 | 4 | 1 | 6 |
| speaker_partial_final_pass_keeps_voices | passed | 8/8 | 12.46 | local
| 157 | 55 | 4 | 1 | 5 |
| stage_queues_automatic_end | passed | 11/11 | 11.036 | scripted | 175
| 52 | 4 | 0 | 7 |
| stage_queues_late_text_rewrite | passed | 14/14 | 18.625 | scripted |
307 | 79 | 7 | 0 | 9 |
| stage_queues_missing_queues | passed | 15/15 | 17.407 | scripted | 359
| 100 | 9 | 1 | 12 |
| stage_queues_model_failures | passed | 14/14 | 15.771 | scripted | 204
| 54 | 4 | 0 | 7 |
| stage_queues_switch_flipped_in_flight | passed | 19/19 | 19.905 |
scripted | 694 | 181 | 20 | 0 | 22 |
| stage_queues_user_end | passed | 12/12 | 20.043 | scripted | 207 | 59
| 5 | 1 | 7 |
| stage_queues_user_end_during_backlog | passed | 14/14 | 20.379 |
scripted | 337 | 94 | 7 | 1 | 12 |
| sync_files_after_newer_speech | passed | 15/15 | 23.598 | scripted |
672 | 152 | 21 | 0 | 18 |
| sync_safety_copy_repeats_live | passed | 3/3 | 20.525 | scripted | 225
| 59 | 8 | 0 | 6 |

Coverage: all 27 committed scenario(s) ran x2 and evaluated their
checks.

The run used `7d57d903e0`, the merge of main. `4835648f91` after it
commits only the re-measured `reach.json`,
so the code under test is the head's.

## UI evidence

UI-Evidence: none -- backend-only change

## Failure class (fixes)

Failure-Class: FC-live-settlement-uses-capture-clock

Line-Count-Exception: backend/utils/conversations/v3/service.py | 2395
-> 2511 | the settlement wakes sit beside the held-Finish wake in
`_after_projection` with a bounded-retry helper whose failure keeps the
pass chain going, `has_pending` skips settlement holds with one more
read in pending order and re-creates an off-page hold's wake, the pass's
sibling-read allowance is threaded through the load ladder, plus the
`settle_older` argument at the live `stretches` call
Line-Count-Exception: backend/database/conversations_v3.py | 2832 ->
3052 | the held-sibling lookup (gated, metadata-only, one pass budget)
reads the same pending-page state `load()` already holds, and the
projection commit stores the settlement deadline in the recording update
it already writes

🤖 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