Repository navigation
feat(batch-pipeline): fresh uploads reach a conversation within 2 min beside catch-up - #22842
Conversation
…up (Fix C) Catch-up uploads arrive newest-first, so the capture-ordered merge held every newer result behind the owner's oldest unready head. Once any ready result has waited BATCH_PIPELINE_MERGE_HEAD_WAIT_SECONDS (default 60; off/<=0 restores strict order) behind an unready head, the merge releases the owner's ready rows in capture order; the head later appends as late_capture. The commit body, log chain, watermark, owner revision fence and projection order are unchanged. complete() and every recovery re-entry stamp ready_at; rows without it never start a bypass. Two owner-scoped job indexes back the queries; a missing index logs head_wait_unavailable and keeps strict order. Bypass commits carry head_wait_bypass and log closed labels only. David ruled 2026-10-20. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… refuse fenced successors The strict commit transaction no longer issues head-wait queries. A blocked owner is probed non-transactionally for its longest waiter; only an expired wait opens a second transaction that re-reads the waiter, selects the earliest-captured ready row and runs the unchanged commit body. The emulator takes a collection-wide lock per transactional query, so the in-transaction probe stalled heartbeats and lost leases in the two-worker gauntlet. An owner-wide privacy fence that refuses the released successor now returns None like strict order instead of raising out of maintenance (Grok review). The missing-index fallback records the shared firestore_read fallback. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A transient read error from the non-transactional head-wait probe now returns None, the strict-order result, instead of escaping commit_next and cutting a serving maintenance tick short (Grok r2 nit). The fallback helper is imported at module level so the missing-index handler cannot raise. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… beside catch-up David's bar (2026-10-20): fresh uploads (capture lag <= 10 min) reach "conversation exists" at p95 <= 2 min and are never held by the owner's catch-up backlog. Ramp runs 14-16 measured fresh p95 546 s: GPU queue and compute were seconds; the time went to the capture-ordered merge head (mostly leaked-lease retries, fixed by #22805), the owner-serial projection chain behind the backlog, and quarantine recovery pickup. - Fresh-first merge (BATCH_PIPELINE_MERGE_CATCH_UP_DEPTH, default 32, off restores the plain merge): admission stamps fresh_capture from capture end. Catch-up commits wait while the owner already has 32 committed rows awaiting projection; when a catch-up row heads the owner, a non-transactional probe finds the earliest pending fresh row and, if ready, a second re-verifying transaction commits it ahead of the backlog. Commit body, log chain, late marking and log-ordered projection are unchanged. Owners held this way are re-offered by owner on every pump maintenance tick and after each serving projection sweep, so one held backlog filling the 100-row result_ready page cannot hide another. New merge_fresh job index; without it the merge logs fresh_first_unavailable and keeps the plain order. - GPU priority (BATCH_PIPELINE_FRESH_GPU_PRIORITY_ENABLED, default on): fresh lane uploads older than 10 min lease at RECENT, after fresh uploads, instead of sharing the owner's FRESH FIFO. - Recovery dispatch: the candidate scan restarts after a short page (it used to skip every earlier candidate for a whole pass), and serving dispatches on its own 5 s loop on the maintenance leader (BATCH_PIPELINE_RECOVERY_DISPATCH_INTERVAL_SECONDS, off = pass only). pipeline_sim (testing/fresh_latency_scenario.py, a live owner-chain walk model): with a 300-row newest-first catch-up owner, that owner's own fresh uploads go from p95 829 s (today) to under 2 min. Stacked on #22820. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…watermark, stuck fresh head) Grok review of the fresh-first merge: - GPU spend admission picked fresh-lane fair-use checks by priority 0, so fresh-lane catch-up admitted at RECENT skipped the hard restriction and daily audio ceiling and drew on the backfill budget. Admission now reads the upload's recorded sync lane (priority only when no lane is recorded); the sim admission model matches. - Privacy erase dropped log_sequence from the erased result, so an erased projection watermark turned the catch-up hold off. The erased row keeps its log position (an ordering field, like previous_segment_id). - With catch-up held and the earliest fresh row stuck (retry), a later ready fresh row lost the bounded head wait. The fresh probe now reads up to 8 pending fresh rows and, once a ready one has waited the head-wait bound, commits the earliest ready fresh row (head_wait_bypass too). - Record-lane units are classified like uploads; docs and flag notes say so. - The fresh-latency sim walker honours the 30 s owner-chain walk budget. With it, depth 32 left too little margin at production's per-row cost; the default is now 16 (fresh p95 42 s beside a 300-row catch-up owner, same catch-up drain as 32). Fix C's replay pins the hold off to keep isolating the head wait. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…esh-latency The fresh probe gets the same treatment: a transient read error keeps the strict result and logs fresh_first_probe_retry; held-owner bookkeeping now happens right after the strict transaction so early returns cannot skip it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b16efff9b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| watermark and (item.capture_at, item.segment_id) <= (watermark['capture_at'], watermark['segment_id']) | ||
| ), | ||
| # Merge class only: fresh rows commit ahead of the owner's catch-up backlog. | ||
| 'fresh_capture': now - item.capture_at - item.duration_seconds <= FRESH_CAPTURE_LAG_SECONDS, |
There was a problem hiding this comment.
Exclude non-sync work from fresh-first classification
When a native retained recording spans more than ten minutes, admit_recording submits all of its units through this scheduler, so earlier units are stamped fresh_capture=False while the tail is stamped True; if the tail finishes first, _catch_up consequently treats the earlier record unit as catch-up and commits the tail ahead of it, despite the merge contract explicitly intending record-lane rows to retain plain order. The same unconditional timestamp check also marks future-dated uploads that lane classification rejected as untrusted backfill as fresh. Carry the trusted sync admission class into this field, or leave it unset for record/untrusted lanes, rather than deriving it for every WorkItem solely from capture time.
Useful? React with 👍 / 👎.
| and recording_age_seconds > FRESH_CAPTURE_LAG_SECONDS | ||
| and fresh_gpu_priority_enabled() | ||
| ): | ||
| return Priority.RECENT |
There was a problem hiding this comment.
Preserve the fresh lane when selecting the usage meter
For every fresh-lane upload older than ten minutes, this changes the persisted priority to RECENT, but BatchProjectionStore.prepare_accounting() still chooses sync_fresh only when a sibling has priority 0 and otherwise records sync_backfill. Compute authorization now correctly uses the intake lane and therefore skips the backfill reservation while applying the live cap; after projection, however, this audio increments only the separate backfill meter, so the realtime + sync_fresh total checked by later fresh admissions never advances and these uploads can repeatedly evade the daily live-audio ceiling. Persist/use the intake lane for projection accounting rather than overloading scheduling priority.
AGENTS.md reference: backend/AGENTS.md:L145-L145
Useful? React with 👍 / 👎.
…ough, durable holds)
Grok round 2:
- A privacy fence on the probed fresh row returned early, so Fix C's head
wait never ran for the owner's other ready rows. It now falls through.
- Held owners lived only in memory; after a restart a held backlog could fill
the global result_ready page and hide another owner's ready rows. A hold now
sets a durable merge_holds/{owner_key} marker (no user ID; owner purge
deletes it) that leader maintenance in the pump and serving re-offers and
clears once a drain no longer holds.
- The fresh probe reads up to 32 pending fresh rows (the query cap), not 8.
- A head-wait pick among fresh rows re-verifies inside the transaction that
the skipped earlier fresh row is still unready.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts were Fix C's own lines (identical on both sides) plus main's flag registry and deployment classification, which take main's version with this branch's three flag rows re-added; the rendered registry and index manifest are regenerated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e1174c5be2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| current = tx.get('jobs', fresh['segment_id']) | ||
| if not ( | ||
| candidate | ||
| and _catch_up(candidate) | ||
| and current.get('merge_pending') | ||
| and current.get('state') == 'result_ready' | ||
| and current.get('fresh_capture') is True |
There was a problem hiding this comment.
Revalidate the earliest fresh row after the probe
When an earlier-captured fresh unit is admitted after the nontransactional fresh_pending() probe but before this transaction, first_pending() can still return the older catch-up head, while these checks validate only the stale selected unit and any previously observed skipped row. The later fresh unit can therefore commit even though the newly admitted earlier fresh unit is already pending, violating fresh-row capture ordering and forcing that earlier audio to append as late_capture; recheck the earliest fresh row or fence the probe with the owner's revision before committing.
Useful? React with 👍 / 👎.
| None means nothing is pending, so the marker is stale. | ||
| """ | ||
| marks = ( | ||
| client.collection(f'{namespace}_merge_holds').where('held', '==', True).limit(max(1, min(limit, 100))).stream() |
There was a problem hiding this comment.
Paginate the durable hold-marker scan
After a process restart with more than 50 owners carrying hold markers, both maintenance callers repeatedly invoke this query with limit=50, but the query has neither a cursor nor any rotation. If one returned page contains owners whose projection remains blocked, their markers stay true and Firestore can return that same page on every pass, so later held owners are never re-offered even after their projection depth has fallen; this recreates the permanently hidden backlog that the durable markers are intended to prevent.
Useful? React with 👍 / 👎.
| for key, owner_id in self.store.held_merge_owners(limit): | ||
| if owner_id: | ||
| drain(owner_id) | ||
| if not owner_id or owner_id not in self.held_owners: | ||
| self.release_hold(key) |
There was a problem hiding this comment.
Fence hold-marker clearing against concurrent holds
With multiple serving or pump replicas, this process can finish drain() without adding the owner to its local held_owners while another replica concurrently reaches the depth cap. If the other replica observes the existing held: true marker, it performs no marker write, after which this branch clears that same marker; a crash of the other replica then loses the only durable indication that its owner remains held. Clear only the marker version observed before the drain, or refresh the marker on every hold so a concurrent hold conflicts with the clear.
Useful? React with 👍 / 👎.
…rker paging, fenced head) Grok round 3: - The hold marker and in-memory set were cleared whenever the strict attempt found an unready head, although the owner was still over the depth cap. Held now means "at the cap with rows pending, whatever the head's state"; a marker clears only once the owner is below the cap or has nothing pending. - Marker recovery read the same first 50 markers every tick. Leader maintenance now pages with a rotating cursor (ordered by owner key). - A privacy fence on the strict commit of a catch-up head escaped before the fresh probe. The owner's ready fresh row now still commits; the fence is re-raised only when nothing else commits. - A head-wait pick among fresh rows re-verifies every skipped earlier fresh row, not just the first. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9c7f44104a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| and recording_age_seconds > FRESH_CAPTURE_LAG_SECONDS | ||
| and fresh_gpu_priority_enabled() | ||
| ): | ||
| return Priority.RECENT |
There was a problem hiding this comment.
Assign GPU priority per decoded capture unit
For a trusted fresh-lane upload whose oldest filename is more than ten minutes old but whose tail was captured recently, recording_age_seconds is the age of the oldest file, so this returns RECENT; accept_batch_upload() calls priority_for() only for the seed and preserves that priority while replacing the seed for every decoded unit. Consequently, even units whose capture ended within the fresh window enter the RECENT GPU queue behind catch-up work, despite later being marked fresh_capture=True for merging, so a mixed upload can still miss the fresh-latency objective. Derive scheduling priority from each decoded unit's capture end rather than from the batch-wide maximum age.
Useful? React with 👍 / 👎.
| ('lease_leak_fixed', 'head_wait'), | ||
| ('lease_leak_fixed', 'head_wait', 'recovery_dispatch_loop'), | ||
| ('lease_leak_fixed', 'head_wait', 'recovery_dispatch_loop', 'fresh_gpu_priority'), | ||
| ('lease_leak_fixed', 'head_wait', 'recovery_dispatch_loop', 'fresh_first'), |
There was a problem hiding this comment.
Keep the fresh-latency ladder cumulative
When ladder() generates the experiment report, this step adds fresh_first but drops fresh_gpu_priority from the preceding step; replay() therefore sets the GPU-priority flag to its off value. The reported transition simultaneously enables one lever and disables another, so it cannot attribute the latency change to fresh-first and contradicts the function's stated cumulative ship-order comparison. Include fresh_gpu_priority in this tuple.
Useful? React with 👍 / 👎.
| if over_cap and waiter is None and fresh is None: | ||
| # At the depth cap with rows pending, whatever the head's state: | ||
| # maintenance re-offers this owner, and the durable marker | ||
| # (owner key only) survives a restart. | ||
| held['over_cap'] = True | ||
| if not tx.get('merge_holds', key).get('held'): | ||
| tx.put('merge_holds', key, {'held': True, 'held_at': now}) |
There was a problem hiding this comment.
Persist a hold when a commit reaches the depth cap
When a catch-up commit raises the outstanding projection count from depth - 1 to exactly depth, over_cap is still false because it was computed before the commit, so this transaction does not create the durable hold marker. Normally the next drain_owner() iteration creates it, but a process exit after the successful commit and before that iteration leaves pending catch-up rows with neither a marker nor an in-memory hold; after restart, an older saturated result_ready page can hide this owner indefinitely. Persist a marker as part of the cap-reaching commit (a stale marker can be cleared by the existing reoffer path).
Useful? React with 👍 / 👎.
…ound-4 review) Grok round 4: - A fenced result_ready head (BatchPrivacyBlocked re-raised by commit_next) aborted leader maintenance before the durable-marker re-offer, and a failure inside the marker page skipped the rest of that page while the cursor moved past it. The global ready-page drain, each marker owner and each in-memory held owner now run in their own try (pump and serving), logging event=batch_merge action=held_reoffer|ready_drain outcome=retry. - A fence re-raised for a non-catch-up head skipped hold bookkeeping, leaving a fenced owner first in the pump's in-memory set. Bookkeeping now runs before any re-raise. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3856599731
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| Fresh uploads (capture ended at most ``FRESH_CAPTURE_LAG_SECONDS`` before | ||
| admission) commit ahead of the owner's pending catch-up rows, and catch-up | ||
| commits wait while the owner already has this many committed rows awaiting | ||
| projection, so a fresh row never queues behind the owner's whole backlog. |
There was a problem hiding this comment.
Document the fresh-first conversation lifecycle
This changes how batch audio is ordered into conversations, including bypassing catch-up rows and holding catch-up commits at a projection-depth cap, but backend/docs/listen_pusher_pipeline.mdx remains unchanged. Update that owning lifecycle document with the fresh-first ordering and kill-switch behavior so operators and future changes do not rely on a stale pipeline contract.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
|
|
||
| def dispatch_recovery(self): | ||
| """Dispatch-loop tick: quarantine recovery only, on the maintenance leader.""" | ||
| if self.recovery is None or not self._leads(True): |
There was a problem hiding this comment.
Separate recovery dispatch from the maintenance lease
When this replica's supervise() path hangs in reconciliation or recording drain while its event loop and another sync-executor worker remain alive, the new five-second loop continues calling _leads(True) on the same SERVING_MAINTENANCE lease. This continually extends the 60-second TTL, so no healthy replica can take over leader-only _maintain() work such as cleanup, scheduler recovery, and result-ready/hold-marker draining, defeating the lease's intended long-drain failover and potentially stalling those queues indefinitely. Give recovery dispatch a separate lease or let only the supervisor renew the maintenance lease.
Useful? React with 👍 / 👎.
Co-Authored-By: Claude Opus 5.5 <[email protected]> # Conflicts: # backend/docs/feature-flag-registry.md
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6640653674
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| held['over_cap'] = True | ||
| if not tx.get('merge_holds', key).get('held'): | ||
| tx.put('merge_holds', key, {'held': True, 'held_at': now}) |
There was a problem hiding this comment.
Persist holds after privacy-fenced commit attempts
When an owner is already at the depth cap and its result-ready catch-up head fails the privacy check during flush(), this marker write is part of the same transaction and is rolled back with the attempted result commit. The exception path nevertheless records only the process-local held_owners entry and does not retry the marker separately, so a restart can lose the durable hold and leave this owner hidden behind a saturated result_ready page. Persist the hold in a separate fenced transaction when the commit raises BatchPrivacyBlocked.
Useful? React with 👍 / 👎.
| try: | ||
| pending = self.store.fresh_pending(key, FRESH_PROBE_ROWS) |
There was a problem hiding this comment.
Scan past the first 32 pending fresh rows
When an owner has more than 32 pending fresh units, the first 32 are all unready, and a later unit is ready behind a catch-up head held at the depth cap, every retry reads the same first page and _fresh_pick() returns nothing. Because the strict head is ready and blocked only by the cap, the later global head-wait path is not entered, so that ready fresh unit can miss the two-minute objective until one of the first 32 finishes or expires. Paginate this probe or query the earliest ready fresh row separately while revalidating earlier rows.
Useful? React with 👍 / 👎.
…2842 Main #22842 (fresh uploads within 2 min) added fresh_capture to final jobs and moves admission priority 0 -> 1, and regenerated main's goldens. Integration's provider_stt_{byok,ja,unsupported} goldens (lane 8, #22536) predate it. The diff is only those two fields (21 priority 0->1, 7 fresh_capture), the same pattern as main's own regeneration. Co-Authored-By: Claude Opus 5.5 <[email protected]>
What changed and why
David's bar (2026-10-20). Batch-lane fresh uploads (capture lag ≤ 10 min) reach "conversation exists" at p95 ≤ 2 min, and are never held by the same owner's catch-up backlog.
What prod showed. Runs 14–16 had fresh p95 546 s (944 hash-cohort fresh rows, ro-prod aggregates). GPU queue and compute were seconds. The time went to three places:
Breakdown:
data/run-2026-10-13-two-lane-nemotron/fresh-latency.mdin the workspace repo.Builds on #22820 (Fix C), now merged to main. All four behaviour changes ship on with a kill switch:
BATCH_PIPELINE_MERGE_CATCH_UP_DEPTH, default 16;offrestores the plain merge).fresh_capturefrom capture end.merge_fresh(owner_key, merge_pending, fresh_capture, capture_at, segment_id). Without it the merge logsfresh_first_unavailableand keeps the plain order.BATCH_PIPELINE_FRESH_GPU_PRIORITY_ENABLED, default true).BATCH_PIPELINE_RECOVERY_DISPATCH_INTERVAL_SECONDS, default 5). Serving dispatches on its own loop on the maintenance leader, with a per-instance lock so the pass and the loop never scan at once.log_sequenceon the erased result. It is an ordering field, likeprevious_segment_id, and keeps an erased projection watermark usable for the depth.Ordering ruling. Fresh rows commit ahead of pending catch-up rows. This is the transient out-of-order publication David approved with Fix C; the final state is commit-order independent per the Fix C proof.
Prerequisites before deploy (lead):
merge_freshindex is READY (the Firestore readiness gate blocks the deploy otherwise);Product invariants affected
none
How it was verified
pipeline_sim. Ranpython -m testing.fresh_latency_scenario, the new scenario on Fix C's chain helpers:Depth K. 16 → 42 s, 32 → 74 s, 64 → 141 s, with the same catch-up drain. At 0.5 s per row (after owner-drain) it is about 30 s.
Unit tests.
backend/test.shwithBACKEND_UNIT_TEST_FILE_LIST, 62 batch, sim, Firestore-guard and flag files,nice -n 19: green. The exceptions are two CPU-guard trips on this host.test_batch_stage_policy::test_old_stage_repair_leaves_admission_unset(0.34 s) is equally slow on the base commit (0.40 s call).test_batch_pipeline_long_speech_handoff[vi-vi](0.30–0.32 s) is unrelated to this change.Grok read-only review: round 1 FIX-FIRST (4 findings, fixed in
fresh-first review fixes); round 2 FIX-FIRST (4 findings, fixed infresh-first round-2 review fixes); round 3 FIX-FIRST (4 findings, fixed infresh-first round-3 review fixes); round 4 FIX-FIRST (2 findings, fixed inisolate held-owner re-offer); round 5 SHIP (no findings) on 3856599.Not verified here. The emulator suites and the sync Cloud Tasks gauntlet are left to CI, and so is live behaviour. The 5% live check should show:
fresh_first/head_wait_bypasslog counts;recovery.prepared_atp95 ≤ 15 s;Tests
test_batch_pipeline_merge_fresh_first.py.test_batch_pipeline_admission.py. Fresh-lane catch-up at RECENT keeps the hard restriction and daily ceiling, and does not reserve backfill. The backfill lane reserves whatever its priority.test_batch_pipeline_scheduler.py. The fresh_capture stamp, the RECENT priority for fresh-lane catch-up, and a fresh upload leasing ahead of its owner's catch-up FIFO.test_batch_pipeline_quarantine_recovery.pyandtest_batch_pipeline_serving.py. The cursor wraps after a short page (the regression test for the bug), overlapping sweeps are refused, the dispatch tick is leader-only, the runtime runs both loops, and the interval parses correctly.test_fresh_latency_sim.py. The shipped levers meet the bar with and without the catch-up owner; main today, and the stack without fresh-first, do not.test_pipeline_sim_scenarios.py. The exhaustion baseline pins the serving-pass cadence, which is the cadence fix(batch): dispatch bounded quarantine recovery batches and keep recovery polls pending #22321 was measured on, and a new variant shows the loop shortens the quarantine tail with the same paid calls.fresh_capturefield;<30sinstead of<1m, and their relative log order follows dispatch order.UI evidence
UI-Evidence: none -- backend batch pipeline only
Failure class (fixes)
Failure-Class: none
🤖 Generated with Claude Code