Skip to content

feat(v3): builder stages on their own queues behind stage_queues - #26824

Merged
Nizarius merged 9 commits into
mainfrom
feat/builder-stage-queues
Nov 30, 2026
Merged

Nizarius merged 9 commits into
mainfrom
feat/builder-stage-queues

Conversation

@Nizarius

@Nizarius Nizarius commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

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 (v3: one card per sit-down, and late speech joins its published card (SCA-4537) #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

Nizarius and others added 8 commits November 30, 2026 17:05
A builder task held its conversations-v3 slot through grouping, the outline
call and every owed summary with its derived effects, memory extraction
included. When the model vendor slowed down on 2026-11-30 every slot was held
longer, the queue saturated and a user's End waited behind automatic work.

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:

- grouping and title stay in service.reconcile on conversations-v3;
- service.summarise writes one conversation's summary; the grouping task
  enqueues it to conversations-v3-summary (a user-ended conversation's to
  conversations-v3-user) instead of writing it;
- utils/conversations/v3/memory.py extracts one conversation's memories from
  a marker the summary's settle arms (v3_memory_pending), on
  conversations-v3-memory, through its own route;
- a builder wake that carries a user's End travels on conversations-v3-user,
  where one task groups the owner and writes that conversation's summary.

The per-account rollout switch stage_queues is read only by the hand-off.
Off, nothing new is read, written or enqueued. Task handlers never read it,
so an account can be switched either way with work in flight. An enqueue that
fails runs the stage in the task that tried and is counted. The three queues
are declared with enabled: false, so nothing creates them yet.

Failure-Class: none

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The loopback Cloud Tasks queue had no limit, tasks took no time and a failed
task was never delivered again, so a backlog or a retry could not be
scripted. An optional queue model adds slots, retries with the queue's
backoff, filler tasks that stand in for other owners' work and queues that do
not exist. The driver runs a split builder stage's task through the product's
own route handler and charges each task's slot for its model calls.

Scenario format: queues, switches (env changed mid-run), llm.fail (scripted
gateway failures), faults.memory_extraction, a queue check and the
conversation fields summary_owed, memory_runs and memory_final. The repeat
comparison renames the id hashes inside stage task names like random UUIDs.
scenario compare gains metric stages. Without a queues block a scenario runs
exactly as before.

Failure-Class: none

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Whole-chain scenarios for the builder queue split, each with the rollout
switch on: automatic end, user End, user End during a backlog, late text
after the summary, the switch flipped with work in flight, missing queues,
and failures. fixtures/arms/stage_queues.json runs any scenario with the
switch on against off. reach.json is re-measured for all 26 scenarios.

Failure-Class: none

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The per-owner memory extraction lock moves from database/redis_db.py to
database/conversations_v3_processing.py, next to the marker it protects, and
releases through the Redis client in use (a script object registered at
import ran on another client under the pipeline lab). The memory step in
process_conversation.py is two lines shorter than before the split. The
settle's optional memory argument is typed, which the strict type check
requires.

Failure-Class: none

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…d counts

The sweep now re-creates a staged owner's summary task instead of waking the
builder, which saves one builder pass in this scenario: 694 reads, 181 writes
and 20 no-op lease renewals, down from 708, 185 and 21.

Failure-Class: none

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…te label

The retryable-response counter keeps a list of route labels; an unlisted
route is recorded as other. The memory stage's task route is added to it.

Failure-Class: none

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…, input check

Review of the stage-queue change:

- backend-sync runs the stage tasks and its metrics sidecar keeps named
  metrics only. The two new counters were not on its list, so they would have
  read as no series there. They are added, with a test on both sidecar lists.
- The runbook says what a code rollback to a revision without the memory
  route does to memory tasks and gives the order that loses nothing.
- The sweep counts an owner whose summary task it re-created.
- The pipeline lab records digests of what each memory extraction was given
  (transcript lines with speaker attribution, the other fields,
  structured.participants) and compare metric stages reports them, so an
  extraction run as its own task can be shown to read what the inline one
  read.

Failure-Class: none

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@Nizarius
Nizarius marked this pull request as ready for review November 30, 2026 23:15
With stage_queues on, a summary hand-off chose between two queues: the user
queue for a conversation a user ended, the summary queue for everything
else. The rewrite of an automatic conversation's summary (late speech joined
a conversation that already shows one; v3_rewrites on the row) now goes to
conversations-v3-memory, the queue of the work nobody waits for, so rewrites
never delay first summaries. Rewrites were 2 to 3% of summary writes until
late speech started joining its published card and 20 to 26% in the hours
after.

The choice is handoff.summary_queue, used by the grouping task's hand-off and
by the sweep. A user-ended conversation's rewrite still goes to the user
queue. The task is still a summary task on the reconcile route. Switch off,
nothing changes.

Failure-Class: none

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@Nizarius
Nizarius merged commit 28876df into main Nov 30, 2026
75 checks passed
@Nizarius
Nizarius deleted the feat/builder-stage-queues branch November 30, 2026 23:52
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