Skip to content

fix(batch): continue owner chains inside the projection sweep and page only pending rows - #22745

Merged
Git-on-my-level merged 11 commits into
mainfrom
lane/proj-chain
Oct 20, 2026
Merged

Git-on-my-level merged 11 commits into
mainfrom
lane/proj-chain

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

5% record-lane ramp run 10 failed obligation_over_15m. All 16 late rows came from one owner whose ordered projection chain ran at 3.2 rows/min. Two scheduling causes:

  • The chain sat idle about 60% of the time, waiting for a sweep page to reach its head again.
  • persisted/ready replays filled most of each 100-row assignment page: 1,640 ProjectionReplay in 22 minutes.

A third factor, a 6.7 s per-row assignment cost for that one owner, can't be explained from the code.

Diagnosis: data/run-2026-10-13-two-lane-nemotron/ramp5-run10-diagnosis.md (Q2 and Q4) in the workspace repository.

Changes

  1. The sweep continues the owner's chain. Kill switch BATCH_PIPELINE_SWEEP_OWNER_CHAIN_ENABLED, default on.
    • When the sweep persists a row that was pending, it walks that owner's chain from projection_watermark. It uses the same walk as the recovery wake.
    • Bounds: one walk per owner per sweep, 64 rows / 30 s per walk, and 30 s per sweep across all owners.
    • Page rows the walk persisted are skipped without a read. Every other page row is attempted in page order as before, including rows past a walk that hit its bound or ran out of budget.
    • Every row still goes through the Redis owner claim and the transactional predecessor, privacy and receipt fences one at a time. There is no new per-owner concurrency.
    • Walked rows reach follow-ups through normal discovery, not the wake's priority queue, so they can't starve other owners' follow-ups.
  2. Pending-only assignment page. Kill switch BATCH_PIPELINE_PROJECTION_PENDING_PAGE_ENABLED, default on.
    • Assignment discovery queries ['pending'] with its own cursor.
    • A separate ['persisted','ready'] page with its own cursor finishes synchronous-policy receipts exactly as the mixed page did. Seeing any async receipt keeps follow-ups scheduled.
    • Async follow-up discovery keeps its own mixed page and cursor unchanged.
    • Same in filter and the same declared results composite index. The query driver gains a states domain.
  3. Assignment sub-phase timing. This is observability, so it has no switch.
    • Projection times load_result, manifest, context, build and candidate (get_closest_conversation_to_timestamps) as batch_projection_phase phases. These are gated by the existing BATCH_PIPELINE_PROJECTION_TIMING_ENABLED, which is on in prod.
    • assign_sync_conversation(timing=True) logs one event=sync_assignment_timing line per call with these fields: attempts, live_overlap_ms, fence_ms, plan_ms, encode_ms, persist_ms, body_ms, commit_ms, retry_ms, index_ms, donors, total_ms and exception_type. Durations, counts and static tokens only, no IDs.
    • Only projection passes timing. Legacy sync callers are unchanged.

Not fixed in this PR: the 6.7 s/row cost. The code has several candidates that the new fields separate:

  • the GCS result load;
  • the unbounded candidate query;
  • lock waits on the per-user sync_assignment day/recent docs, which every intake reads and writes, and on the target conversation while the previous row's follow-ups write it;
  • SDK commit retries;
  • post-commit Typesense deletes for every historical sync_merged_from donor on each row.

None is clearly dominant from the code alone, so this ships the timing. The next burst names the sub-phase.

Optional item 4 skipped: gating complete_content accounting on all siblings being ready. It touches the completion fence, so it isn't small.

Expected effect: the idle gaps go away, so one owner's chain should go from about 3.2 to about 8.5 rows/min at the current 6.7 s/row. Owners at the normal 1.3 s/row reach about 23 rows per 30 s walk. The pending-only page also stops the replays from taking up page slots.

Rollout

Both switches are default-on kill switches. Setting false restores the previous sweep. With both off, the sweep makes the same store calls as before (tested). Each switch is independent.

Verification

Measured at the unit layer, on m5:

  • Targeted test.sh (BACKEND_PYTEST_WORKERS=4, omi-heavy, nice -n 19): 21 files pass, including the new test_batch_pipeline_sweep_owner_chain.py, the owner-chain, projection, follow-up, serving and discovery tests, the assign_sync_conversation callers, the Firestore query-shape guards and the policy tests.
  • New tests cover:
    • a 100-row backlog drains 1 + 64 rows in one pass (legacy: page size only);
    • the shared budget;
    • the fence/privacy stop;
    • a busy claim starts no walk (max claim depth 1);
    • follow-ups still scheduled with no pending rows;
    • no follow-up starved behind a 250-row blocked pending backlog;
    • sync-policy receipts finish from the finish page;
    • both switches off gives the legacy store-call trace;
    • the switches are independent;
    • the timing line counts SDK commit-retry attempts, has a bounded field set and no IDs, and is silent when off.
  • scripts/typecheck.sh: 0 errors. scan_async_blockers: 0. check_feature_flag_registry: OK.

Full suite: m1-check (see comment).

Line count

Line-Count-Exception: backend/database/conversations.py | 4435 -> 4448 | per-attempt sub-phase timing must wrap the existing transaction body in place; the clock itself lives in database/sync_assignment.py

Failure class

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

Product invariants affected

none

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

Git-on-my-level and others added 4 commits October 20, 2026 08:16
…e only pending rows

During the 5% ramp run 10, one owner's ordered projection chain fell to
3.2 rows/min: it sat idle ~60% of the time between sweep pages, and
persisted/ready replays filled most of each 100-row assignment page.

- Sweep owner-chain continuation (BATCH_PIPELINE_SWEEP_OWNER_CHAIN_ENABLED,
  kill switch, default on): when the sweep persists a pending row it walks
  that owner's chain from the projection watermark with the existing
  recovery-wake walk. One walk per owner per sweep, 64 rows / 30 s each,
  30 s per sweep across owners. Rows the walk persisted are skipped unread;
  every other page row is attempted as before. Owner claim, predecessor,
  privacy and receipt fences are unchanged; no new per-owner concurrency.
- Pending-only assignment page (BATCH_PIPELINE_PROJECTION_PENDING_PAGE_ENABLED,
  kill switch, default on): assignment discovery asks only for pending rows.
  A separate persisted/ready page with its own cursor finishes
  synchronous-policy receipts as the mixed page did and keeps async
  follow-ups scheduled. Follow-up discovery keeps its own mixed page.
  Same results composite index.
- Assignment sub-phase timing: projection times load_result, manifest,
  context, build and candidate; assign_sync_conversation(timing=True) logs
  one bounded line (attempts, fence/plan/encode/persist/body/commit/retry/
  index ms, donor count), no IDs. Legacy sync callers are unchanged.

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-20T04:35:09.792388Z 81a5368 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.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Full backend unit suite on m1-mac-studio (hermetic, no GCP creds): SCA-907 PASS at b8d404b — 2059 files, 0 failed, suite_exit=0, 633s.

Git-on-my-level and others added 2 commits October 20, 2026 09:21
- A walk that persisted async rows sets has_async_followups, so an async
  tail behind a sync head is not left waiting for the finish cursor to wrap.
- The shared 30 s walk budget starts at the first walk, not the page, so a
  slow head no longer forfeits its continuation.
- Rows a walk persisted are left out of the sweep counts; the sweep_chain
  summary reports them.
- The finish page records projection contention before skipping async
  receipts, so the sweep summary line is still emitted.
- The assignment timing clock wraps the live-overlap lookup, and logs the
  real donor count.

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

Copy link
Copy Markdown
Member Author

Full backend unit suite on m1-mac-studio at review-fix head 1a237e2: SCA-910 PASS — 2060 files, 0 failed, suite_exit=0, 624s. GitHub CI green at the same head (59 checks).

Re-review findings on the sweep owner-chain continuation:
- A walk's async follow-ups are handed to the follow-up queue as owed rows.
  They are held (bounded, durable either way) until the next discovery pass
  and queued behind its page without moving the rotation, so a parked
  discovery or finish cursor cannot strand them, and they never jump
  discovered work or keep discovery from running.
- A sibling-read failure after an async row persisted ends the walk with
  that row still returned as owed, instead of losing the walk's result.
- The finish page skips rows this sweep already assigned or finished.

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

Copy link
Copy Markdown
Member Author

Head 4b6084c: m1 full suite SCA-911 PASS (2060 files, 0 failed). CI green after one rerun: the first Sync Cloud Tasks Stack Gauntlet attempt failed its two-worker lease-distribution assertion (only one GPU worker replica leased the 5 units; projection is downstream of leasing and this commit touched only the sweep/follow-up queue). It passed on the rerun, on both earlier heads, and on the last 15 main runs; recording it here as a timing flake, not hidden.

Second re-review findings on the walk-owed follow-up handoff:
- Serving keeps calling start_followups while the projector owes walk
  follow-ups, even on a pass that saw no async row.
- schedule() falls through to discovery when launching drains the queue and
  rows are still owed, including after a priority wake.
- Walk read failures (successor, result row, watermark) end the walk and
  return the rows it already persisted instead of losing them.
- Owed rows past the 256 bound restart follow-up discovery at the head once.

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: a8300e6163

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


def sweep_owner_chain_enabled() -> bool:
"""Kill switch: a sweep that advances an owner's head keeps walking that chain."""
from config.policy import kill_switch

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 Hoist the new policy imports to module scope

Move the config.policy.kill_switch imports used by both new getters to module scope (or another non-circular module-level location). These additions introduce function-local imports even though the backend guide explicitly requires all imports to be declared at module scope, making dependency behavior less predictable and extending an expressly prohibited pattern.

AGENTS.md reference: backend/AGENTS.md:L161-L163

Useful? React with 👍 / 👎.

after_assign(transaction, planned)
with clock.timed('persist'):
after_assign(transaction, planned)
clock.body_done()

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 Record failed transaction bodies before rethrowing

Call clock.body_done() from a finally path around each transaction-body attempt rather than only after all planning and persistence succeeds. When before_assign, assign_in_transaction, encoding, or after_assign raises—especially when a read-side contention error is retried—the failed attempt is counted in attempts and its phase timers, but its elapsed time is omitted from body_ms and consequently charged again to retry_ms. This makes the new contention diagnostics double-count or misclassify precisely the slow/error attempts they are intended to diagnose.

Useful? React with 👍 / 👎.

"""Kill switch: a sweep that advances an owner's head keeps walking that chain."""
from config.policy import kill_switch

return kill_switch('BATCH_PIPELINE_SWEEP_OWNER_CHAIN_ENABLED')

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 Wire the new kill switches into runtime manifests

Add both new switches to the authoritative runtime environment manifest and the applicable GKE values/classification alongside BATCH_PIPELINE_PROJECTION_PAGINATION_ENABLED. A repo-wide search shows BATCH_PIPELINE_SWEEP_OWNER_CHAIN_ENABLED and BATCH_PIPELINE_PROJECTION_PENDING_PAGE_ENABLED only in code, tests, and generated documentation, so the deployment renderer cannot carry a production false value and an export/replace deployment will restore the code-default-on behavior. That makes the documented rollback path unavailable during an incident.

AGENTS.md reference: backend/AGENTS.md:L153-L153

Useful? React with 👍 / 👎.

Git-on-my-level and others added 3 commits October 20, 2026 11:00
…ow-ups

Third re-review findings:
- The row the sweep page itself persisted was owed to nobody when its
  content had no later walked sibling (one-segment contents). It now seeds
  its owner's walk and is owed when the walk's initial watermark read shows
  it advanced. Later page rows of a walked owner, and rows reached after the
  shared budget is spent, get a seed-only hand-off (one watermark read,
  nothing persisted). A partial multipart that did not advance stays out.
- A watermark read failure right after a persist still owes that async row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fifth review (SHIP) follow-ups:
- The scan for a content's persisted, not-ready siblings now stops at the
  walk deadline, so a seed-only hand-off (no budget) reads no siblings and a
  full walk cannot spend its budget there. Unscanned siblings stay durable
  and are rediscovered.
- Cover an opening watermark read failure: the page row is still owed.

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

Copy link
Copy Markdown
Member Author

Final head 81a5368: m1 full suite SCA-917 PASS (2060 files, 0 failed, 617s); GitHub CI green (59 checks). Note: the intermediate head ea8ee32 had one m1 failure (SCA-915, test_sync_cloud_tasks.py::test_sequenced_attempt_heartbeat_drain_is_bounded, a wall-clock-bounded test, on a run that took 1468s vs ~620s). The file passed 3/3 locally (186 tests) and passes in SCA-917; it is outside this diff. Recorded as a host-load flake, not hidden.

@Git-on-my-level
Git-on-my-level merged commit 554d484 into main Oct 20, 2026
59 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/proj-chain branch October 20, 2026 04:52
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