Repository navigation
fix(batch): drain each owner's projection chain continuously and cut per-row cost - #22830
Conversation
…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]>
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. |
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]>
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 👍 / 👎.
| 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)) |
There was a problem hiding this comment.
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> # Conflicts: # backend/docs/feature-flag-registry.md
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:
sync_merged_fromdonor, soindex_msgrows 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_idthrough 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
BATCH_PIPELINE_OWNER_DRAIN_ENABLED, default on.falserestores the fix(batch): continue owner chains inside the projection sweep and page only pending rows #22745 sweep walk exactly.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.sync_executoruntil 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.predecessorand per-partchecktransactions 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.BATCH_PIPELINE_PROJECTION_PREFETCH, default4;0is the kill switch; malformed or > 8 keeps 4.ChainPrefetchloads the next N rows' successor links, job bindings, result payloads and audio manifests onstorage_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.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.BATCH_PIPELINE_PROJECTION_INDEX_DEFERRED_ENABLED, default on.defer_index,assign_sync_conversationrecords the canonical and its donor lineage instead of running the index step. The lineage is the cumulativesync_merged_fromplus this commit's new donors fromassign_in_transaction(absorbed=...).ProjectionIndexconverges each touched conversation once per flush, from durable state, throughconversations.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.falserestores the inline step. Legacy sync callers are unchanged.pipeline_sim projection-drain. It runs the realProjectorwalk, sweep andOwnerDrainson 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)sweep_walk)Rollout
Three independent switches, all on by default:
BATCH_PIPELINE_OWNER_DRAIN_ENABLED=falseis today's sweep walk.BATCH_PIPELINE_PROJECTION_PREFETCH=0reads every input on the chain.BATCH_PIPELINE_PROJECTION_INDEX_DEFERRED_ENABLED=falserestores the inline index.They are registered in
config/feature-flags.yamlandconfig/policy/kill_switches.py.Live checks after deploy (aggregates only):
sync_assignment_timingindex_ms=0on the drain path;batch_projection_indexlag_msp95 ≤ 60 s;sync_assignmentcontention retries;owner_drain outcome=turnlines.Not merged or deployed by this PR.
Verification
Unit layer, on m5,
nice -n 19, worktreelane/owner-drain-p1rebased on3d2de47f5dfd:backend/test.shover 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.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.test_batch_pipeline_owner_drain.py(34 tests, incl. the review regressions):Serving.reconcile_async;defer_indexwiring, and the serving tick flush.test_pipeline_sim_projection_drain.py: a fast 100-row case in the PR lane. The 1.2k-row and 12-owner cases are markedslowand 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