Skip to content

fix(batch): drain each owner's projection chain continuously and cut per-row cost - #22830

Merged
Git-on-my-level merged 3 commits into
mainfrom
lane/owner-drain-p1
Oct 20, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
lane/owner-drain-p1

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

What this fixes

Batch projection persists each owner's result log in strict chain order. After #22745, runs 14 and 16 drained a catch-up owner at about 1.7–1.8 s/row (about 35 rows/min), so a 1.2k-row owner needs about 35 min of projection. Two things make that worse or keep it there:

  • Scheduling (I4). One 30 s walk budget per sweep is shared by every owner on the instance, with about 20 s between sweeps. With tens of heavy owners each one's duty cycle collapses, and its 35 min becomes 1–2 h.
  • Per-row cost (I1–I3). Every row pays two read-only pre-check transactions, serial GCS reads (result payload, audio manifest), a serial candidate query, and an inline Typesense step. That step re-deletes every historic sync_merged_from donor, so index_ms grows with donors (run 14: 59.7% of summed assignment time).

This is Phase 1 of the owner-parallel design (data/run-2026-10-13-two-lane-nemotron/owner-parallel-design.md, §3(c), in the workspace repository). No ordering relaxation: the assignment transaction's predecessor fence (projection_watermark == previous_segment_id through erased rows), privacy, binding, ledger and receipt fences decide every row exactly as before. R1–R4 and A1–A3 are unchanged. Phase 2 (batched assignment) is separate.

Changes

  1. Per-owner drain. Kill switch BATCH_PIPELINE_OWNER_DRAIN_ENABLED, default on. false restores the fix(batch): continue owner chains inside the projection sweep and page only pending rows #22745 sweep walk exactly.
    • The sweep only discovers owners. When it persists an owner's pending head, it hands the owner to this process's OwnerDrains (utils/batch_pipeline/projection_drain.py) instead of a budgeted walk. It leaves that owner's later rows on the same page to the drain, and skips owners already draining here. An owner still waiting for a drain slot keeps its one-row-per-pass page progress.
    • Fair scheduling: a FIFO of owners, at most 8 draining per process. Each turn walks in blocking steps of ≤ 15 s on sync_executor until the chain ends, blocks, or 120 s pass. An owner with rows left re-queues behind every waiting owner. Every turn takes at least one step.
    • Each step holds the advisory Redis owner claim for the step (lease 300 s) instead of per row. So one owner has one walker across processes, and a busy claim ends the step before any read.
    • Pre-checks dropped (c3). Rows a step reaches as the watermark's successor skip the predecessor and per-part check transactions when the step's fresh result-row read shows no receipt. A row or part that already has a receipt still replays through the check. A receipt that races in is replayed by the assignment transaction, including the silence path, exactly as the check would have done.
    • A recovery wake that stops at its 64-row / 30 s bound hands the owner to the drain. Drained async rows are owed follow-ups through the existing owed queue.
  2. Read-ahead (c2). BATCH_PIPELINE_PROJECTION_PREFETCH, default 4; 0 is the kill switch; malformed or > 8 keeps 4.
    • ChainPrefetch loads the next N rows' successor links, job bindings, result payloads and audio manifests on storage_executor. All of these are immutable once committed. Receipt state always comes from the walk's fresh read. A miss or failed load falls back to the walk's own read; a load still running when the step budget is spent ends the step (more) and stays queued, so a slow read is never redone inline on the sync slot. The step deadline is also checked between multipart parts. A drain turn keeps one read-ahead across its steps.
    • The candidate hint query (get_closest_conversation_to_timestamps) starts beside context and build, after the predecessor committed, for the span the words predict. It is used only when it returns a conversation for exactly the built span, waiting no longer than the step has left; no match, a different span, an error or the cap redoes it inline. So the hint each assignment sees is the one the serial path would have seen.
  3. Index off the chain, coalesced (c1). Kill switch BATCH_PIPELINE_PROJECTION_INDEX_DEFERRED_ENABLED, default on.
    • With defer_index, assign_sync_conversation records the canonical and its donor lineage instead of running the index step. The lineage is the cumulative sync_merged_from plus this commit's new donors from assign_in_transaction(absorbed=...).
    • ProjectionIndex converges each touched conversation once per flush, from durable state, through conversations.index_sync_assignment. That runs after each drain step and on each serving tick, with a single flusher. So a heavy owner pays the lineage deletes once per conversation per flush, not once per row.
    • Re-deleting the lineage on each flush keeps today's repair of a fail-open donor delete that timed out or was lost (Grok review).
    • Fail-open as before: pending work is in memory until the conversation's next deferral. false restores the inline step. Legacy sync callers are unchanged.
  4. pipeline_sim projection-drain. It runs the real Projector walk, sweep and OwnerDrains on virtual time, with run-14 p50 latencies charged per call. Read-ahead lanes overlap.

Measured (model, virtual time; python -m testing.pipeline_sim projection-drain)

Workload today (sweep_walk) drain, no cuts Phase 1
1 owner × 1,200 rows 36.7 rows/min (≈ 33 min) 44.4 118.2 rows/min (10.2 min)
12 owners × 300 rows, one instance 3.0 rows/min each 27–33 61.5–99.4 each
  • Today's 36.7 matches the 35 rows/min that runs 14/16 measured, which calibrates the model.
  • Pre-check transactions for 1.2k rows drop from 2,400 to 2. Result loads are 1,215 (about one wasted read-ahead per turn).
  • Every mode makes identical assignment calls, including candidate hints and new donors, and ends with the identical index.
  • The model has no Firestore hot-document contention, so live rates will be lower. The design estimates 60–120 rows/min.

Rollout

Three independent switches, all on by default:

  • BATCH_PIPELINE_OWNER_DRAIN_ENABLED=false is today's sweep walk.
  • BATCH_PIPELINE_PROJECTION_PREFETCH=0 reads every input on the chain.
  • BATCH_PIPELINE_PROJECTION_INDEX_DEFERRED_ENABLED=false restores the inline index.

They are registered in config/feature-flags.yaml and config/policy/kill_switches.py.

Live checks after deploy (aggregates only):

  • same-owner persist gap p50 ≤ 0.6 s;
  • sync_assignment_timing index_ms=0 on the drain path;
  • batch_projection_index lag_ms p95 ≤ 60 s;
  • no rise in sync_assignment contention retries;
  • owner_drain outcome=turn lines.

Not merged or deployed by this PR.

Verification

Unit layer, on m5, nice -n 19, worktree lane/owner-drain-p1 rebased on 3d2de47f5dfd:

  • Targeted backend/test.sh over 50 files: owner-chain, sweep, projection, follow-up, discovery, serving, quarantine, worker, sync assignment callers (cross-job, size rollover, live overlap, smart-merge flatten, lineage), people-stats, pipeline_sim and characterization goldens, background-task and real-clock ratchets. All tests pass.
    • The only guard hit is the CPU-time warning on test_batch_stage_policy::test_old_stage_repair_leaves_admission_unset: 0.33–0.37 s against the 0.30 s local budget, with host load average about 91. That test does not touch these modules, and CI's ceiling is 1.0 s.
  • New test_batch_pipeline_owner_drain.py (34 tests, incl. the review regressions):
    • fairness: one slot, one step per turn, and a light owner finishes in its second turn behind two 12-row owners;
    • the concurrency bound and one walker per owner;
    • sweep → drain discovery through Serving.reconcile_async;
    • same-pass hand-off, and that queued owners keep page progress;
    • the kill switch restores the sweep walk;
    • the claim is held per step, zero pre-checks, a busy claim, and the predecessor fence still stopping a stale successor link;
    • a raced receipt replays with and without the pre-check;
    • equivalence: a drained catch-up (erased row mid-chain, two owners) has the same final results, watermarks and order as today's sweep walk; the sim's assignment calls and final index are equal;
    • read-ahead reads once, follows links ahead, and falls back on errors;
    • index: only new donors, and deferred convergence equals the inline index with fewer calls;
    • single flusher, defer_index wiring, and the serving tick flush.
  • New test_pipeline_sim_projection_drain.py: a fast 100-row case in the PR lane. The 1.2k-row and 12-owner cases are marked slow and were run here (3 passed).
  • scripts/typecheck.sh: 0 errors. scan_async_blockers: 0. scan_import_time_side_effects: 0. check_feature_flag_registry: OK.

Line count

Line-Count-Exception: backend/database/conversations.py | 4448 -> 4475 | the deferred index hook must sit beside the existing in-place transaction and index step in assign_sync_conversation, and index_sync_assignment shares that file's private Typesense helpers

Failure class

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page

The same sweep-scheduling family as #22745: an ordered per-owner drain was scheduled as a shrinking share of a bounded sweep pass.

Product invariants affected

none

🤖 Generated with Claude Code

…per-row cost

Phase 1 of the owner-parallel design. The sweep-shared 30 s walk budget
collapsed each heavy owner's duty cycle as owners multiplied, and every
row paid two read-only pre-check transactions, serial GCS reads and an
index step that re-deleted every historic donor. No ordering rule
changes: the assignment transaction's predecessor, privacy, binding and
receipt fences decide every row as before (R1-R4, A1-A3 kept).

- Owner drain (BATCH_PIPELINE_OWNER_DRAIN_ENABLED, kill switch, default
  on). The sweep only discovers owners. OwnerDrains runs up to 8 owners
  per process, FIFO, in 15 s blocking steps on sync_executor and 120 s
  turns; an owner with rows left re-queues behind every waiting owner.
  Each step holds the advisory owner claim, and rows reached as the
  watermark's successor skip the predecessor and per-part pre-checks
  when the step's fresh read shows no receipt. A raced receipt replays
  in the transaction exactly as the check would have. A wake that stops
  at its bound hands the owner to the drain. Off restores the sweep walk.
- Read-ahead (BATCH_PIPELINE_PROJECTION_PREFETCH, default 4, 0 = off).
  Successor links, job bindings, result payloads and audio manifests of
  the next rows load on storage_executor; receipt state is always read
  fresh, and any miss falls back inline. The candidate hint lookup runs
  beside context and build after the predecessor commits, used only for
  the exact built span.
- Deferred index (BATCH_PIPELINE_PROJECTION_INDEX_DEFERRED_ENABLED, kill
  switch, default on). assign_in_transaction reports only the donors a
  commit newly absorbs. Walks defer people-stats and Typesense work, and
  ProjectionIndex converges each touched conversation once from durable
  state after each drain step and serving tick. Off restores the inline
  step with the cumulative sync_merged_from deletes.
- pipeline_sim projection-drain: the real walk, sweep and drain on
  virtual time with run-14 latencies. 1.2k-row owner: 36.7 rows/min
  today, 120 with Phase 1; 12 heavy owners: 3.0 vs 65-114 each. Every
  mode makes identical assignment calls and ends with the same index.

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

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T11:22:17.721988Z 417c185 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Grok review of the owner drain (FIX-FIRST):
- Deferred index keeps donor repair: defer_index now receives the
  canonical's lineage (cumulative sync_merged_from plus this commit's new
  donors), so a fail-open donor delete that timed out or was lost on exit
  is retried by the next flush, as the inline step did. Coalescing still
  pays those deletes once per conversation per flush, not per row.
- Hand-offs are thread-safe: sweeps and wakes run on sync-pool threads
  while overlapping reconcile passes and drains swap on the event loop.
  drain_requests and chain_followups now change only under one lock.
- A drain step no longer holds its pool slot past its budget waiting on
  read-ahead: the wait is capped by the step's remaining time, a row
  still loading ends the step (more=True) and stays queued for the next
  step, and after 30 s of total waiting the walk reads it inline.
- Page rows left to the drain count as waiting in the sweep summary.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: be61a556f3

ℹ️ 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".

if future is None:
return None
try:
return future.result(timeout=PREFETCH_WAIT_SECONDS)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Await prefetch work outside the sync executor

When an owner drain is active, drain_step is already running in sync_executor, so this .result(timeout=30) turns a sync worker into a coordinator waiting on storage_executor. With the default eight concurrent drains, slow GCS reads can pin half of the 16-worker sync pool for 30 seconds at a time, delaying sync ingestion and other work assigned to that pool; await the prefetch from the async OwnerDrains coordinator instead of blocking across pools.

AGENTS.md reference: backend/AGENTS.md:L277-L281

Useful? React with 👍 / 👎.

if pending is None or pending[0] != span:
return False, None
try:
return True, pending[1].result(timeout=CANDIDATE_WAIT_SECONDS)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Move candidate-query waiting into async orchestration

On the owner-drain path this method also executes inside a sync_executor worker, so waiting up to 10 seconds on a db_executor future creates another cross-pool coordinator. Under Firestore congestion, eight drains can occupy eight sync workers while doing no sync work, increasing latency for the ingestion pipeline; coordinate the candidate future from async code rather than calling .result() in the worker.

AGENTS.md reference: backend/AGENTS.md:L277-L281

Useful? React with 👍 / 👎.

for active in reversed(patches):
active.stop()
finally:
logging.disable(logging.NOTSET)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore the caller's logging threshold

When run() is invoked in-process by the unit suite or another simulator harness after logging has already been disabled at a nonzero threshold, this unconditional reset enables every log globally instead of restoring the caller's state. Subsequent tests or simulations can therefore emit logs they intentionally suppressed and become order-dependent; save logging.root.manager.disable before setting CRITICAL and restore that saved value in this finally block.

Useful? React with 👍 / 👎.

Comment thread backend/database/conversations.py Outdated
if defer_index is not None:
# Only this commit's new redirects; earlier donors were deleted when absorbed.
clock.donors = len(absorbed)
defer_index(uid, conversation['id'], list(absorbed))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve retries for historical donor deletions

When a newly absorbed donor's fail-open Typesense deletion encounters a transient failure, later assignments to the same canonical no longer retry it because absorbed is empty after the original merge. The previous inline path passed the cumulative sync_merged_from list on every append, so a later write could remove the stale donor document; with this deferred call the donor can remain searchable indefinitely. Keep unresolved donor deletions durable or include historical donors in a later convergence pass.

Useful? React with 👍 / 👎.

…y candidates

Grok re-review (round 2) findings:
- A read-ahead load still running is never redone inline on the sync
  slot: take() returns NOT_READY however long it has waited (each wait
  capped at the step's remaining time), and only a failed load is read
  inline. Storage calls keep their own timeouts; a turn starts a fresh
  read-ahead.
- The step deadline travels in WalkHint: assign_parts checks it between
  the parts of a multipart row (StepDeadline ends the step with more=True;
  the next step resumes at the first unpersisted part), and the parallel
  candidate wait is capped by what is left of the step.
- A parallel candidate lookup that found nothing is redone inline, so a
  conversation committed after the lookup started is still seen, as on
  the serial path.
- The drain switch note no longer claims it alone restores the pre-drain
  walk: read-ahead and the deferred index keep their own switches.

Model: 1.2k-row owner 118.2 rows/min (was 120 with the trusted empty
hint); 12 heavy owners 61.5-99.4 each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 44430ae into main Oct 20, 2026
63 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/owner-drain-p1 branch October 20, 2026 12:07
Git-on-my-level added a commit that referenced this pull request Oct 20, 2026
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	backend/docs/feature-flag-registry.md
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