Skip to content

SCA-2015: add durable owner cursor for ready-result discovery - #25266

Merged
Git-on-my-level merged 12 commits into
mainfrom
lane/ready-owner-cursor
Nov 14, 2026
Merged

Git-on-my-level merged 12 commits into
mainfrom
lane/ready-owner-cursor

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

The 100-oldest ready-result page can be filled with held backlog and never offer a quiet owner's fresh work. Discover distinct ready owners in a durable, ceiling-bounded pass. Seek above the saved owner key and at or below the pass ceiling; advance only after an attempted drain, and reset the cursor/ceiling at wrap. New owners behind the cursor or beyond the ceiling wait for the next pass. Existing merge, privacy, result-chain and provider-backlog gates remain enforced.

Current head: 5a67d5a, source tree 00b128d161dd59371a06c86bf0fd609359cf5245. Integration/fix author model: GPT-6.1 Sol. No SHIP exists for this head. SCA-2166 remains held.

Shared cursor and stored-field contract

Cursor recovery: after_owner_key advances only after attempted drains or counted missing ids. At the pass ceiling or an empty seek, the pass ends and both cursor and ceiling reset to null; the next tick starts a new pass.

Serving and the GPU pump use separate maintenance leases, so their discovery pages can overlap. Each page captures the full stored cursor snapshot. Its finish transaction reads the cursor again and writes only if that snapshot is unchanged. Accepted finishes increment the new nonnegative integer revision; missing means 0. This distinguishes repeated positions across passes even when pass_started_at repeats. A stale finish writes nothing and cannot claim a published wrap; the next tick resumes the newer progress. Malformed revisions and datastore errors retain the old-page fallback without a cursor write.

Readers/writers: ReadyDiscovery in backend-integration serving maintenance and the GKE worker pump, on Firestore/Postgres, plus simulator clients. Pre-cursor versions ignore this document. Earlier cursor versions preserve unknown fields but write unconditionally and do not increment revision; every cursor writer must run the conditional code before protection is an acceptance claim. No job/result schema changes.

Owner budget defaults to 20, clamped 1..100. Cooperative tick deadline defaults to 10 seconds, clamped 1..60; it is checked between queries/drains and cannot interrupt an in-flight synchronous operation. Normal maintenance cadences remain 20 seconds for serving and 5 seconds for the pump. Cursor read/write/query failures fall back to the old page; missing indexes back off 300 seconds. Durable marker re-offer remains active on the cursor path.

Cost per tick: owner seek rows and drain reads, two cursor-document reads, one ceiling query per pass, plus empty-query minimums. Accepted ticks write one cursor document; stale ticks write none. Transactions/retries add RPCs. Duplicate concurrent drains remain possible and transaction-fenced. With no clipping or arrivals within the ceiling, a pass needs max(1, ceil(O/B)) accepted ticks; elapsed time depends on successful shared progress, not either advisory lease alone.

Validation and CI repairs

  • Three overlap/ABA regressions first failed on the preceding source. The cursor suite now passes 35 tests, including malformed revisions and fresh work beyond held owners.
  • Publication/config/terminal-poll suites pass 16 + 89 + 41 tests in isolated processes.
  • New shared-cursor store conformance: 1 simulator pass, 2 real-store skips. Real-store proof remains required in CI.
  • All eight flood tests pass with the existing refreshed golden unchanged after this conditional-write fix.
  • Vendor drills pass 10 tests with the normal 1.0-second CPU guard. The previous CI head failed that guard at 1.07 seconds; it was not waived or budget-adjusted. Fresh CI is required.
  • The inherited provider-conformance mocks only intercepted fresh_pending, which default transactional selection never calls. They now cover both modes, assert each race executed, and retain custody/predecessor assertions. Local result: 18 simulator passes, 36 real-store skips.

The deliberate flood re-pin was verified with the documented updater and then without it, with all acceptance assertions unchanged. On source 202448d, the same held_15 counterfactual with the cursor off/on projects the same 396 GPU rows in 138.020/67.980 seconds: 172.149/349.515 rows per minute. flood_metrics divides by max(60, last_projection-flood_at)/60, so the denominator changes 2.300333→1.133000 minutes; neither hits the floor. Distinct-owner discovery shortens completion of the eligible GPU subset. Both runs retain 7,524 held provider rows, zero fresh pending and valid chains. This is observed projection throughput, not a provider release rate, and authorizes no metering-rate increase.

Golden metric groups: held arms change p50 126.16→126.56 s (ratio 1.002→1.005), backlog ahead 16→5, with p90 unchanged at 198.979 s (0.995 baseline ratio). Unmetered FIFO p50/p90 move 171.769/423.5→168.004/417.65 s (ratios 1.364/2.118→1.334/2.088), retaining the >2x incident counterfactual. Unmetered fair-queue throughput moves 450.987→451.87 rows/min and p50/p90 134.897/208.71→134.71/207.073 s (ratios 1.071/1.044→1.07/1.035). Baselines, route mix, pending/held counts, chain validity and guard shares are unchanged. Workload, capacity, clock formula and acceptance thresholds were not changed.

Independent review and release prerequisites

Actual reviewer model: DeepSeek V4.1 Flash. Round one returned FIX on 2894ae8; round two returned FIX on 202448d for stale cursor writes: #25266 (comment). The current conditional-write fix addresses that finding, but these verdicts do not approve the new head. The issue Limits cap review at two rounds; owner disposition is pending. No third review, self-authorized release, merge or deploy is authorized.

This cursor addresses the 62-owner discovery population. After both committing services serve it and a full pass wraps, run the counts-only infra/rollout/provider-stt-drain/stalled_fresh_owners.py re-count. Baseline: 62 stalled owners / 1,317 ready fresh rows; 60 owners outside the 36-hour nudge window. Record serving identities and remaining head shapes before proposing more code. “Under a day late is fixed” remains open until that read shows the owners draining. The separate selection patch directly matched one owner and is not the fix for this population.

Release owner dispatches the carried Firestore index definitions as step 0. 0007_ready_owners.sql uses plain CREATE INDEX inside a transaction and is not online-safe under PostgreSQL write traffic; production Postgres serving status remains unverified. Missing-index fallback is not acceptance proof. Rollback: BATCH_PIPELINE_READY_DISCOVERY_CURSOR_ENABLED=false restores the old page and retains cursor state. No production action was performed.

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

Git-on-my-level and others added 5 commits November 14, 2026 12:11
Persist pass ceilings, stop discovery at the tick deadline, and retain undrained progress. Correct error/count telemetry and keep saturation tests within the existing timing budgets.

Failure-Class: FC-backlog-release-shares-lane-with-fresh-work
…ssify permanent errors

Review of 89e69ef1: a slow cursor read could be followed by the ceiling
query after the tick budget expired. Permanent API errors are logged as
errors. Smaller saturation fixture for the unit time budget.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…the cursor page key 'cursor'

Merges lane/tx-fresh-gate at 953ce1e (one test-inventory commit) and
renames the page dict key state to cursor in ready_discovery.py, which a
CI-only lifecycle writer guard reads as a job state payload. No behaviour
change.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Git-on-my-level and others added 4 commits November 14, 2026 13:39
…dget

CI measured 1.16 s CPU for the switch-off case against a 1.00 s limit.
Two held owners with 51 rows each still fill the old 100-row page, and
the switch-off case needs one tick to show the miss, not three.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…r and the row sweep

With the owner cursor on by default, maintenance finds owners by key and
reads no job to learn its owner, so the memo count this test asserted is
zero. The test now runs both: zero owner reads with the cursor, the
original memoised counts with the switch off.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@Git-on-my-level Git-on-my-level changed the title feat(batch): discover ready owners with a durable cursor SCA-2015: add durable owner cursor for ready-result discovery Nov 14, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Independent exact-head review. Reviewer model: DeepSeek V4.1 Flash (M1 Studio OpenCode, via Multica). Reviewed commit: 2894ae8ad247d9957942be3a36c06668b07226a5 (source tree ccdea1a14df5). No earlier verdict was carried forward.

VERDICT: FIX 2894ae8ad247d9957942be3a36c06668b07226a5

One defect attributable to this head owns the verdict.

1. The deterministic backlog-flood golden is broken by this head

backend/tests/unit/test_pipeline_sim_backlog_flood.py::test_seed_one_metrics_match_the_deterministic_golden fails at this commit, 3 of 3 local runs. The same file passes on the same interpreter at the merge base 26981e31cf and at current main (af24862981), so this is the head's behaviour change, not a golden that went stale on main. It is also the file that failed CI in Backend unit shard 7/8 (and therefore Backend unit suite).

PIPELINE_GOLDEN_UPDATE=1 diff against the committed fixture, this head:

held_0 / held_15
  backlog_rows_projected_per_minute          172.149 -> 349.515
  max_own_backlog_rows_ahead_of_fresh             16 -> 5
  fresh_p50_ratio                              1.002 -> 1.005
  fresh_capture_to_projection_p50_seconds     126.16  -> 126.56
unmetered_0
  fresh_p50_ratio                              1.364 -> 1.334
  fresh_p90_ratio                              2.118 -> 2.088
  fresh_capture_to_projection_p50_seconds     171.769 -> 168.004
  fresh_capture_to_projection_p90_seconds      423.5  -> 417.65
unmetered_15
  backlog_rows_projected_per_minute          450.987 -> 451.87
  fresh_p50_ratio                              1.071 -> 1.070
  fresh_p90_ratio                              1.044 -> 1.035

The bounded assertions still hold at this head (p50/p90 ratio <= 1.1, max_own_backlog_rows_ahead_of_fresh <= 16), and the direction is neutral-to-better for fresh work. What the PR does not explain is the 2.03x move in the held arms' backlog_rows_projected_per_minute (396 projected rows in both cases; the denominator max(60, last_projection - flood_at) goes 2.30 -> 1.13 min). Backlog rows per minute is the unit the metered releaser's rate is denominated in, so this needs a stated reason before the fixture is re-pinned — not a blind PIPELINE_GOLDEN_UPDATE=1. Either the owner-order change legitimately compresses the held arm's projection window (then say so in the body and re-pin), or the discovery ordering changed more than intended.

What I reviewed as sound (no finding)

Full diff vs 26981e31cf: 25 files, ~457 non-test lines, under the 500-line limit.

  • ready_discovery pass state is coherent: ceiling captured at pass start, seek strictly above after_owner_key and at or below the ceiling, wrap recorded in the same tick, after_owner_key advanced after every attempted owner including counted-missing ones. A missing merge_discovery/cursor document reads {} in both stores and initialises cleanly.
  • Failure handling fails closed: cursor read/write/query errors return None/False, which restores the old 100-oldest page, so nothing is committed by a half-read cursor. FailedPrecondition (missing index) backs off 300 s; permanent client errors log outcome=error and still fall back.
  • Missing index on deploy is safe in both stores: Firestore raises FailedPrecondition -> backoff + old page; Postgres only loses the index (sequential scan), because state/merge_pending are generated columns from 0001.
  • Owner-grain seeking is correct: an owner block is skipped in one round trip and the query filters state='result_ready' + merge_pending, matching the readiness predicate the old page used through due().
  • Overlapping serving/pump passes share one cursor with last-writer-wins writes. I traced the interleavings: a stale write can only move the cursor backwards (re-visiting owners) or reset a pass; drains are transaction-fenced, so duplicates are idempotent and no owner is skipped. Documented as a known limit.
  • The serving change also moves reoffer_marked out of the fallback-only branch, so durable markers are re-offered on the cursor path too — that is required for the held-backlog case and is correct.
  • Independently run here on this head: test_batch_ready_discovery.py + test_batch_pipeline_scheduler.py + test_batch_pipeline_serving_config.py -> 179 passed; the new ready_owners conformance case passes on the simulator (Postgres/emulator fixtures unavailable on this host, as usual).

Minor, non-blocking: ReadyDiscovery.retry() sets no backoff for errors outside FailedPrecondition/unavailable, so a permanent non-client error re-logs at ERROR on every tick; correct, but noisy.

CI facts

  • The 6 scripts/provider_merge_emulator_test.py failures (pl585/pl584 x sim/emulator/postgres) are inherited from main, not caused here: identical test ids fail on main at 54b960d947, and backend/utils/batch_pipeline/merge.py plus that script are byte-identical to main in this head. They are stale mocks of store.fresh_pending under the fix(batch): pick fresh merge rows inside the commit transaction #25263 transactional gate. Separate work.
  • Fixing the golden above is the only head-local red I found.

Any new head needs a fresh confirmation; this verdict covers only 2894ae8ad247d9957942be3a36c06668b07226a5.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Round-two exact-head review. Reviewer model: DeepSeek V4.1 Flash (M1 Studio OpenCode, via Multica). Reviewed commit: 202448d155d47a4f8b9b2847343b30637accc994 (source tree 86722859a58e). Nothing carried forward from my round-one verdict on 2894ae8ad247.

VERDICT: FIX 202448d155d47a4f8b9b2847343b30637accc994

The two things this successor was built to fix are fixed, and I verified them. The blocker is elsewhere and is in production code, unchanged by this successor.

Blocking: the shared cursor write is last-writer-wins, and a stale page rewinds it

ReadyDiscovery.page() snapshots merge_discovery/cursor and finish() writes that snapshot back unconditionally (backend/utils/batch_pipeline/ready_discovery.py:66,138). Serving and the GPU pump hold separate maintenance leases and share the one cursor. I reproduced the regression with two ReadyDiscovery instances against the same store, budget 2:

pump tick 0 drains ['b','d'] -> persists 'd'
pump tick 1 drains ['f','h'] -> persists 'h'
serving (page read before tick 0) drains ['b','d'] -> persists 'd'   # cursor h -> d
next pass starts at 'f'

No owner is lost — coverage resumes from the rewound point — but the work is redone. With the production cadences this is systematic, not incidental: the pump ticks every 5 s and serving every 20 s, so serving's page is always older than the pump's last write, and one serving finish discards up to four pump pages (~80 owner visits). Effective discovery then runs at the serving cadence, about 4x slower than the fast path, on exactly the held-owner population this change exists to drain cheaply. My round-one comment called overlapping visits "harmless"; that was too generous — they are harmless to correctness, not to cost, and the cost lands on the metric the release is judged by.

Remedy is small: make the write conditional (compare the pass_started_at/version read in page() with the stored document before put, and abandon or re-read on mismatch), or serialize cursor ownership to one writer. Add the overlapping-page regression with held owners ordered before a ready-fresh owner. The PR's Known limits section currently states "overlapping visits are normal and harmless" and should record this instead once fixed.

This is the second FIX at the two-round cap, so it needs an owner decision (extend, or fix and ship on your own verification).

Verified as fixed — CI repairs

  • scripts/provider_merge_emulator_test.py: the race is now injected at the boundary each mode actually uses and each test asserts the interleaving ran (raced == [True]). Locally: 23 passed, 13 skipped, 3 errors where the errors are only this host's Postgres fixture failing initdb; the pl584/pl585 sim cases pass in both probe and transactional modes, and custody (row(h,'fresh') == original, no result doc) and predecessor order are still asserted. Before this repair the same selection gave 4 failures on sim and Postgres.
  • The transactional predecessor case now asserts the stronger outcome (the predecessor itself commits first), which is what the added acceptance contract asks for.

Verified as fixed — the deliberate fixture pin

I re-ran the same counterfactual on this source, switching only BATCH_PIPELINE_READY_DISCOVERY_CURSOR_ENABLED:

cursor off: 396 rows, last projection 138.019996 s -> 172.149 rows/min
cursor on : 396 rows, last projection  67.979998 s -> 349.515 rows/min
both: held_result_ready 7524, fresh_pending 0, owner_chain_valid true

That reproduces your numbers to the millisecond and resolves the round-one finding: the numerator is unchanged, the denominator moves 2.300333 -> 1.133000 min (neither hits the 60 s floor), and the effect is GPU projection completion, not a provider release rate. The 17-value golden delta is exactly the observed drift, no more, and test_pipeline_sim_backlog_flood.py passes 8/8 without PIPELINE_GOLDEN_UPDATE. I also re-ran discovery/scheduler/serving-config/publication/terminal-poll/flag-budget: 260 passed.

Still open from earlier rounds (not re-litigated here)

Real Firestore/Postgres query and index readiness is unverified locally; 0007_ready_owners.sql is not online-safe and the flag ships on; missing-index and cursor errors fall back to the old page, which I confirmed in the code path. Dead-letter/provider-conformance real-store coverage remains CI's job.

Any new head needs a fresh confirmation; this verdict covers only 202448d155d47a4f8b9b2847343b30637accc994.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Co-authored-by: multica-agent <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Independent exact-head review, round three (gpt-6-luna via agentctl review pool; last commits authored by Sol): no BLOCKER or SHOULD-FIX. VERDICT: SHIP 5a67d5a6d61a. Confirms the conditional cursor finish (snapshot compare plus revision in one transaction), safe loser path, fail-closed fallback and kill switch; focused suite 35 passed; conformance does not race simultaneous finish transactions. CI at this head: 68 checks, 0 not green. Hold on SCA-2166 lifted by the pipeline lead.

@Git-on-my-level
Git-on-my-level merged commit c69d06d into main Nov 14, 2026
72 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/ready-owner-cursor branch November 14, 2026 13:28
Git-on-my-level added a commit that referenced this pull request Nov 14, 2026
…25283)

An unready fresh or unstamped GPU head can leave a later ready fresh
result stuck indefinitely when an intervening ready provider backlog row
is held. The expired head-wait path repeatedly selects the held row,
while the existing transactional fresh selector only runs for catch-up
or held-provider heads.

After that head-wait path hits held provider stock, retry fresh
selection and commit in one transaction. The selected fresh row must
satisfy its own head wait. The provider backlog remains held; stored
classes, privacy checks, result-log predecessors and projection fences
are preserved. This shared merge path runs in backend-integration and
the GKE batch worker.

## Proof limits and release order

This fixes the three-row selection shape above. The production metadata
read at 2026-11-14 08:38Z matched this shape directly for **one owner**.
It is not the fix for the 62 stalled owners: 60 were outside the 36-hour
nudge window. The durable discovery cursor in #25266 must release first,
followed by a counts-only re-count after a full wrapped pass; report
remaining owners' head shapes before proposing further code. The claim
that uploads under a day late are fixed remains open until that
production check passes.

The Firestore and Postgres conformance cases **skip** on this host
because their backends are unavailable. The simulator passes do not
establish real-store behavior or production acceptance.

## Validation

- Unmodified main reproduces 2 failures (fresh and unstamped heads),
with 1 stored-false control pass.
- Selection regression, transactional fresh gate and bounded head-wait
suites: 208 passed.
- Existing fresh-first: 59 passed; provider merge membership: 46 passed.
- New conformance cases: 8 simulator passes, 16 Firestore/Postgres
skips. Covers 40 unready predecessors, disabled head wait and privacy
refusal.
- Repository preflight passed all 38 selected checks before publication.
CI is reported separately on the final head.

No endpoint or deployment configuration changes. Synthetic tests invoke
the real OrderedMerge.commit_next path. No production writes or customer
content reads were performed.

## Review and rollback

Author model: GPT-6.1 Sol. Current head:
`5a0bb5abe6550792fe891eabe97074f986ab2c63`. Requested independent
reviewer: DeepSeek V4.1 Flash through Multica. Round-two independent
review: DeepSeek V4.1 Flash, VERDICT: SHIP for this exact head, recorded
at
#25283 (comment).
CI and cursor-first release prerequisites remain separate. No earlier
SHIP applies to this change. Record the actual reviewer model and
reviewed SHA here before release.

Rollback: BATCH_PIPELINE_MERGE_TX_FRESH_GATE_ENABLED=false disables the
additional selection. Missing transactional indexes fail closed with
backoff. No knobs, queue budgets or lifecycle states are added or
retuned.

Part of SCA-2015; this PR alone does not complete the metered-release
contract.

Failure-Class: FC-backlog-release-shares-lane-with-fresh-work

## CI conformance repair on this successor

The provider conformance tests were intercepting only fresh_pending,
which the default transactional gate never calls. The privacy revoke and
predecessor settlement therefore did not occur in the failing CI cases.
The tests now parameterize the outside-probe and transactional modes,
inject each race at the boundary used by that mode, and assert the
interleaving actually executed. Privacy still requires no result and
unchanged custody; the predecessor must commit first or prevent the
later result from passing. No production code changes in this successor.
Local provider conformance: 18 simulator passes, 36 real-store skips;
full real-store proof remains with CI. This commit invalidates any
confirmation of the previous head.

Prior exact-head review: **DeepSeek V4.1 Flash, SHIP at
45a802b**, recorded at
#25283 (comment).
That verdict does not cover current head
5a0bb5a; round-two exact-head
confirmation is now recorded above. Cost: the target head shape now uses
three transactions per drain attempt rather than two, adding one
transactional fresh-selection attempt and its reads/contention; no
backlog budget is increased.

CI receipt: at 2026-11-14 11:32Z, the GitHub API reported 66 terminal
outcomes on 5a0bb5a: 41 SUCCESS and 25
SKIPPED, with no pending or failed checks. DeepSeek V4.1 Flash SHIP
names this same head. The PR remains draft while cursor-first release
and verification prerequisites are unresolved.
Git-on-my-level added a commit that referenced this pull request Nov 14, 2026
Integrate c5cf5a2, including the provider conformance fixture repair from PR #25266. Keep delivered-share sampling in general maintenance and retain the fresh-only independent timer.
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