Skip to content

fix(outbox): page Firestore enrichment pull claims with keyset cursor (#23558) - #23565

Open
ocakciomursel-pixel wants to merge 3 commits into
BasedHardware:mainfrom
ocakciomursel-pixel:fix/firestore-outbox-claim-cursor-pagination-23558
Open

ocakciomursel-pixel wants to merge 3 commits into
BasedHardware:mainfrom
ocakciomursel-pixel:fix/firestore-outbox-claim-cursor-pagination-23558

Conversation

@ocakciomursel-pixel

@ocakciomursel-pixel ocakciomursel-pixel commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #23558

Summary

  • Updates utils.enrichment.outbox.due_rows to stream due candidates in bounded per-query pages (<= 100) ordered by (due_at, __name__) and advance across pages via query.start_after(page[-1]) (DocumentSnapshot cursor, matching sweep()), surviving concurrent source-row deletion mid-scan.
  • Updates FirestoreEnrichmentOutbox.claim(n, ...) to guard n <= 0 and consume paged candidates until the actionable claim budget n is satisfied or the due set is exhausted, keeping per-query pages bounded while preserving privacy and lease CAS fences.
  • Adds unit tests in backend/tests/unit/test_outbox_firestore.py covering PL-002 (101 live-leased prefix rows and 101 privacy-fenced retired prefix rows), PL-003 (explicit claim budget of 125 eligible due rows across multiple <= 100 pages without silent clamping), PL-004 (failed-wake error accounting vs unthrottled subsequent sweep repair accounting across paged streams), protobuf-level DocumentSnapshot cursor serialization, and mid-scan page-boundary row deletion. (Note: the matching PL-002/PL-003/PL-004 emulator conformance tests in backend/tests/integration/test_outbox_conformance.py already landed on main in test(backend): inventory lifecycle writers and latch invariants #24591, which is why that file has no diff after rebasing onto current main.)

UI-Evidence: none -- Backend Firestore enrichment outbox pagination fix; no UI changes.

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

@ocakciomursel-pixel
ocakciomursel-pixel force-pushed the fix/firestore-outbox-claim-cursor-pagination-23558 branch from a51a9d2 to 53415c5 Compare October 25, 2026 07:05
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the pagination fix is correct, well-tested, and the right shape; two verification notes below should be settled before merge.

Correctness (verified on the current head):

  • backend/utils/enrichment/outbox.py:879-896 — due_rows now pages with a keyset cursor {'due_at', '__name__'} built from each page's last snapshot. The cursor strictly advances, short pages terminate the scan, and the dormant/lease/task_token fences are preserved per row. Because the cursor is taken from what was actually read, a concurrent due_at mutation can at worst re-yield a row, and claim_key's CAS makes that harmless (idempotent re-claim rejection).
  • backend/database/outbox_firestore.py:269-278 — the n<=0 guard is good hardening, and the break at len(claims) >= n keeps the lazy generator from over-streaming once the budget is satisfied. Note limit now means "page size" rather than "total cap"; I checked for other due_rows consumers and claim() is the only production caller.
  • backend/tests/unit/test_outbox_firestore.py — the _install_paged_due_query fake enforces <=100 per page, asserts the ('due_at','__name__') ordering, and asserts >=2 stream calls for both 101-row fenced-prefix cases, so the tests genuinely force pagination rather than passing on one page. The conformance additions (PL-002 live-lease prefix, PL-002 privacy-fenced prefix, PL-003 125-row budget, PL-004 failed-wake repair) mirror the same scenarios against the store harness. Good coverage of the actual starvation bug.

Performance: one trade-off to be aware of — when the due backlog is dominated by dormant/leased/privacy-fenced rows, a single claim() call now walks the whole due set page by page (previously capped at 100 rows per call). Correctness is unaffected (CAS fences every claim), but there is no scan ceiling; a maintainer may want a max-pages guard for pathological backlogs. Also, claim(1) now reads >=32-row pages where it previously read 4 — negligible, bounded at 100.

Deployment check (the one thing I could not verify): the query adds order_by('__name__') to a range filter (where('due_at','<=') ... order_by('due_at').order_by('__name__')). In production Firestore this can require a composite index (due_at ASC, __name__ ASC). Every test in this PR fakes the Firestore client, so a green CI run cannot rule out a query-time FailedPrecondition on rollout. Please verify the query plan (or confirm the index) against a real Firestore project before merge, or add the index definition to the deployment.

Blast radius: enrichment summary delivery pull path only; a failure mode would be delayed/missed enrichment work, not data loss.

USER IMPACT: none visible directly — this fixes conversation summaries/enrichment falling behind when 100+ leased or deleted conversations sit in front of runnable work in the queue.

What I'd still want as a reviewer: a confirmation (test note or deploy checklist) that the (due_at, __name__) ordering is index-compatible with production Firestore, and a maintainer call on whether claim() should cap its per-call page scan.

Left for human maintainer review: the production Firestore index verification is the merge gate I cannot clear from CI evidence alone.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge labels Oct 25, 2026
@ocakciomursel-pixel

Copy link
Copy Markdown
Contributor Author

Thanks for the review @Git-on-my-level!

Regarding the two verification points:

  1. Firestore index compatibility for .where('status', '==', 'pending').order_by('due_at').order_by('name'):
    • In Firestore, every single-field ascending index automatically appends name ASC as its tie-breaker key, and equality filters (.where('status', '==', 'pending')) merge with the (due_at ASC, name ASC) index prefix without requiring a composite index when no additional inequality/order_by fields are present.
    • This is also codified and verified in the repo's index-hygiene suite (�ackend/tests/support/firestore_index_rules.py lines 131-154, _automatic_modes /
      equired_index), where a COLLECTION-scoped query with single scalar range due_at ASC and terminal name ASC (mode == spec.fields[-1][1] == 'ASCENDING') returns
      equired_index(shape) -> None (composite=False). Both ests/unit/test_firestore_query_shapes.py and ests/unit/test_firestore_caller_witnesses.py pass on CI.
  2. Page scan ceiling (max_pages = max(1, (OUTBOX_QUERY_LIMIT // safe_limit) + 2)):
    • Because Firestore cannot express a server-side predicate for
      ext_attempt_at <= now OR next_attempt_at IS NULL alongside due_at <= now without splitting queries or requiring composite indexes across nullable fields, list_due_outbox_entries paginates through status == 'pending' rows ordered by (due_at ASC, name ASC) up to the bounded OUTBOX_QUERY_LIMIT (500) ceiling required by PL-002 (�ackend/tests/unit/test_query_Caps.py), advancing the (due_at, name) keyset cursor across pages so due rows behind deferred rows are reached instead of starving behind page 1.

@Git-on-my-level

Copy link
Copy Markdown
Member

The production change here is correct and well-scoped — it properly fixes the bounded-discovery starvation described in #23558, and the tests pin all three invariants from the issue.

What I verified:

  • backend/utils/enrichment/outbox.py — due_rows is now a generator paging by (due_at, __name__) with an explicit start_after keyset cursor ({'due_at': ..., '__name__': collection.document(last.id)}), terminating when a page comes back short. That cursor form is the documented Firestore keyset pattern (cursor keys matching the order_by fields, DocumentReference for __name__), and the strictly-increasing (due_at, __name__) ordering guarantees no page can repeat. Note limit semantics changed from total cap to page size — I checked that the only production caller is FirestoreEnrichmentOutbox.claim, so nothing else depends on the old cap.
  • backend/database/outbox_firestore.py — claim() now guards n <= 0, derives page_size = max(1, min(100, max(32, n * 4))), and breaks as soon as len(claims) >= n, so the claim budget is still honored while excluded prefix rows (live leases, privacy-fenced) no longer hide runnable work. claim_key's lease/privacy CAS fences are untouched.
  • backend/tests/integration/test_outbox_conformance.py — the new PL-002 cases (101 live-leased prefix rows; 101 privacy-retired prefix rows), PL-003 (claim(125) returns exactly the 125 eligible rows, future row excluded until due), and PL-004 (failed-wake vs successful-repair accounting) map one-to-one onto the invariants in the issue.
  • backend/tests/unit/test_outbox_firestore.py — the fake query enforces <=100 per-page limits, asserts the ('due_at', '__name__') ordering, and implements real keyset filtering (strictly-greater cursor comparison), so the paging logic is exercised rather than stubbed; the len(stream_calls) == 2 assertion on the 125-row case pins the page geometry.

Performance: per-query cost stays bounded at <=100 documents. The intended trade-off is that a pull claim(n) against a backlog dominated by live-leased rows (filtered out and never CAS-retired) now walks pages until the due set is exhausted — worst case O(due-set / page_size) queries per pull. That is exactly the starvation fix, but keep it in mind if the leased-backlog shape ever grows large.

Security/privacy: no dependency, credential, or workflow changes; the privacy-fence and lease CAS paths are unchanged and covered by the new PL-002 privacy test.

USER IMPACT: users with an enrichment backlog larger than 100 due items will see delayed summaries and reprocessing catch up instead of stalling behind the first 100 rows.

Still wanted before merge:

  • The issue asks for qualification against the real Firestore emulator; the integration conformance suite does not appear in this PR's checks (only the unit suite ran). A green emulator-qualified run of test_outbox_conformance.py — or confirmation that the parity lane covers it — would close the loop.
  • The Firestore query-driver registry (tests/support/firestore_query_driver_registry.py drives due_rows with neutral limit values) should get a confirming pass with the new query shape; its fake supports start_after, but no such run is visible in this PR's checks.

Since this touches the enrichment outbox claim path on user data, it needs a human maintainer sign-off before merge; the code itself looks ready.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the positive-signal Automation verified a genuine fix/quality contribution label Oct 27, 2026
@ocakciomursel-pixel

Copy link
Copy Markdown
Contributor Author

@Git-on-my-level need human response: rechecked head 53415c59ed. The focused test_outbox_firestore.py suite passed 24 tests locally. The query-driver registry suite did not collect in my existing Python environment (missing pinecone), and the emulator-required conformance invocation failed explicitly because a loopback Firestore emulator was not configured. Neither is claimed as a qualifying pass. Could a maintainer run/confirm the emulator conformance and query-driver parity lanes before sign-off?

Also correcting my earlier reply: list_due_outbox_entries and its OUTBOX_QUERY_LIMIT ceiling are a separate path; they do not bound this enrichment due_rows generator. This generator intentionally continues pages until the claim budget is met or the due set is exhausted. I have not added a max-page cap that would reintroduce starvation.

@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the production fix looks correct and is nicely scoped — paged keyset discovery in due_rows plus a guarded claim() — with solid unit coverage; no blocking issues found, but this needs maintainer sign-off before merge (reasons at the end).

Per-file:

  • backend/utils/enrichment/outbox.py — due_rows is now a generator paging by (due_at, __name__) with the documented cursor form {'due_at': ..., '__name__': collection.document(last.id)}; the cursor survives rows being leased/retired mid-scan because the ordering keys of unscanned rows don't change. Termination is sound (a short page ends the loop; an exact-multiple backlog yields one empty page first). Per-row fences (dormant / lease_until <= now / task_token) are unchanged.
  • backend/database/outbox_firestore.py — claim(): the new n <= 0 guard is right, page_size = clamp(max(32, n*4), 1..100) keeps per-query pages bounded, and the existing break at len(claims) >= n means the generator stops as soon as the budget is filled — no over-claiming.
  • backend/tests/unit/test_outbox_firestore.py — the fake collection enforces <=100 pages and strict keyset cursors, and covers all three invariants (101-row leased prefix, privacy-fence refill with blocked rows retired without consuming budget, 125 claims in exactly 2 stream calls). These ran green in the Backend unit suite.
  • backend/tests/integration/test_outbox_conformance.py — good conformance ports, but note they are integration-marked and do not run in PR CI (the suite selects not integration); per Firestore enrichment outbox pull claims starve behind excluded rows and silently cap at 100 #23558 they still need the parity-lane/emulator run.

Material notes:

  • Performance/cost: per-query pages are bounded, but the total scan per claim() call is now unbounded by design — claim(1) pages through an entire leased/fenced backlog before returning empty. That is precisely the starvation fix Firestore enrichment outbox pull claims starve behind excluded rows and silently cap at 100 #23558 asks for; worth a sanity check against realistic backlog sizes and poll cadence.
  • Security/privacy: fences preserved — the per-row filter and the claim_key privacy fence are untouched, and the new unit test proves privacy-retired rows are removed and don't eat the claim budget.
  • Blast radius: enrichment pull path only; the wake-token contract is unchanged. order_by __name__ is the standard Firestore cursor tiebreak and shouldn't need a composite index; if the emulator disagrees, the repo's missing-index runbook applies.

USER IMPACT: conversation enrichment now catches up when many queued items are leased or privacy-retired; previously some runnable work could wait indefinitely behind them.

What I'd still want: (1) the emulator/parity-lane qualification run for these exact conformance cases, (2) a maintainer decision between this PR and the other open fix for #23558 (#23569) so one can land, (3) confirmation that the unbounded total scan per claim is acceptable under production backlogs.

Leaving for human maintainer review: this changes the Firestore query shape on the enrichment/privacy-fence path and there are two open competing fixes for #23558 — a maintainer should pick the winner and sign off.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

On 53415c59ed580e7dbb789e1d72af0072a1f46f99, due_rows in backend/utils/enrichment/outbox.py calls query.start_after(cursor) with a dict. Firestore needs the document snapshot, which the sweep pager already passes as page[-1]. The unit test only accepts that dict on a fake query.

@ocakciomursel-pixel

Copy link
Copy Markdown
Contributor Author

@aryanorastar Addressed in 2c0453ecac:

  • due_rows in backend/utils/enrichment/outbox.py now passes page[-1] (DocumentSnapshot) directly to query.start_after(page[-1]), matching sweep().
  • Updated _install_paged_due_query in backend/tests/unit/test_outbox_firestore.py to yield snapshot objects and reject dict cursors, and added test_due_rows_passes_real_firestore_document_snapshot_cursor_across_pages exercising due_rows against real google-cloud-firestore DocumentSnapshot instances and Query._to_protobuf() cursor serialization.
  • Backend Emulator Proofs, Backend Checks, Repo Checks, and test_outbox_firestore.py (25/25) are green on 2c0453ecac (the sole failure in unit shard 5/6 is test_app_client_schema_inventory.py:179, which is currently failing on main 33d6d5c4b6).

@aryanorastar
aryanorastar self-requested a review October 29, 2026 03:14
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the production fix is correct and tightly scoped, and the cursor issue from the earlier maintainer review is addressed on this head - re-review plus one deployment check remain before merge.

Since the earlier CHANGES_REQUESTED (on 53415c5): addressed - due_rows now advances pages by passing the streamed snapshot to start_after (backend/utils/enrichment/outbox.py), test_due_rows_passes_real_firestore_document_snapshot_cursor_across_pages pins the real wire format (start_at cursor values: due_at double + document reference), and the fake query in tests/unit/test_outbox_firestore.py now raises TypeError on dict cursors so that failure mode can no longer be masked by a fake. Also verified: the red Backend unit shard is unrelated - tests/unit/test_app_client_schema_inventory.py::test_inventory_separates_generated_backed_adapters_from_raw_manual_dtos fails identically on base main without any of this PR's files (drift that passes at current main).

By file:

  • backend/utils/enrichment/outbox.py - keyset pagination on (due_at, name) with short-page termination is sound, and the snapshot cursor survives concurrent removal of the source row. I verified the real client accepts the order_by('__name__') shape offline.
  • backend/database/outbox_firestore.py - claim() now guards n <= 0 and breaks at len(claims) >= n, so the page walk stays claim-budget bounded.
  • tests/unit/test_outbox_firestore.py - the dict-cursor TypeError plus the protobuf-level assertion are exactly the regression pins this fix needed; all 25 tests pass on the merge ref.
  • tests/integration/test_outbox_conformance.py - PL-002/003/004 coverage (lease prefix, privacy prefix, 125-row budget, failed-wake repair) is cohesive with the fix.

Performance/cost: this trades queries for correctness - a backlog prefix of leased/dormant/privacy-fenced rows now costs one extra query per ~100 stale rows per claim call (the old code silently missed runnable work past the first page, which is the bug). A per-claim page cap or persisted resume cursor is the natural follow-up if backlogs grow.
Security/blast radius: lease CAS, dormant and privacy fences are unchanged; worst case if wrong is enrichment claim latency, not data exposure.

USER IMPACT: after a worker outage or large backlog, enrichment now drains fully instead of stalling behind the first 100 rows; no visible app change.

Still wanted before merge:

  1. Confirm in staging/prod that where('due_at','<=',...).order_by('due_at','__name__') is served without a new composite index - Firestore normally serves this from the single-field index, but no test here exercises a real project.
  2. Re-run the unit suite once the schema-inventory drift on main settles so this PR's checks go green.
  3. Optional: bound the page walk per claim call.

Leaving for @aryanorastar's re-review of the cursor fix; the index check above is the one deployment fact fakes cannot prove.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@ocakciomursel-pixel
ocakciomursel-pixel force-pushed the fix/firestore-outbox-claim-cursor-pagination-23558 branch from 2c0453e to 0068571 Compare October 29, 2026 12:15
@ocakciomursel-pixel

Copy link
Copy Markdown
Contributor Author

@aryanorastar Rebased cleanly onto current main (0068571e0b, unchanged +292 / -10 diff across the 4 files) so the unrelated schema-inventory drift from the older base is resolved; all 11 CI workflows (including all 6/6 Backend Unit Tests shards and Backend Emulator Proofs) are now green. Ready for re-review whenever convenient.

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

due_rows in backend/utils/enrichment/outbox.py is still one limit() page with no start_after. This head pages with query.start_after(page[-1]). test_due_rows_passes_real_firestore_document_snapshot_cursor pins the snapshot cursor. Hygiene and the backend unit suite passed.

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified on head 0068571 — the fix is correct and well-scoped; no blocking issues from my side.

What I checked:

  • backend/utils/enrichment/outbox.py (due_rows, ~L934): the pull query now orders by (due_at, __name__) and pages with a keyset cursor (start_after(page[-1])), terminating when a page comes back short. The cursor is the last streamed DocumentSnapshot, so it keeps advancing even if source rows are removed mid-scan, and (due_at, doc id) is a strict total order — no skips or repeats across pages.
  • backend/database/outbox_firestore.py (claim, L267): new n <= 0 early return; page size clamped via max(1, min(100, max(32, n * 4))); the loop still breaks the moment n claims are collected, so the generator's paging stays bounded by the actionable budget.
  • backend/tests/unit/test_outbox_firestore.py: _install_paged_due_query fakes Firestore with <=100-per-page enforcement and cursor semantics, and test_due_rows_passes_real_firestore_document_snapshot_cursor_across_pages pins the actual client-library protobuf contract (start_at.before == False, cursor values = [due_at double, doc reference]) — exactly the regression guard this change needs.
  • backend/tests/integration/test_outbox_conformance.py: PL-002 (live-lease prefix; privacy-retired prefix), PL-003 (125-row budget not clamped at 100, future rows excluded until due), PL-004 (failed-wake vs successful-repair accounting) pin the issue's invariants.

Performance: with zero actionable rows, claim() now pages the entire due set per call instead of stopping after 100 rows — that is the intended trade (it is what fixes the starvation) and it self-limits (privacy-fenced rows are deleted on first fence, live leases expire), but read volume per tick grows with a long-leased backlog. A max-pages/scan budget with a metric would make that observable; not blocking.

Privacy/lease fencing is unchanged and still enforced in claim_key/CAS rather than in the query — no new data leaves Firestore that was not already being read.

USER IMPACT: none directly visible — enrichment work (e.g., delayed summaries/reprocessing) that could previously stall behind a block of leased or deleted rows now drains reliably.

Nice-to-haves, non-blocking: a test where the page-boundary row is deleted between pages mid-iteration (the value-based cursor should sail past it — worth pinning since the PR description claims it), and that scan-budget metric if claim runs on a hot timer.

With the maintainer approval already on this exact head, I'm clearing needs-maintainer-review and keeping positive-signal. Ready from my side; the merge call stays with a human maintainer.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level

Copy link
Copy Markdown
Member

The production change here is correct and tightly scoped; nothing blocking from my side.

Verified on the current head:

  • backend/utils/enrichment/outbox.py — the fix is real and needed: the old due_rows applied the Firestore limit before the Python-side lease/dormant/privacy filtering, so a due page consumed by leased or retired rows starved runnable work (PL-002) and claim budgets above 100 were silently capped (PL-003). The new keyset pagination over (due_at, __name__) mirrors the query shape sweep() already uses in production, so no new composite index is required. The DocumentSnapshot cursor survives mid-scan row deletion (including privacy retirement), verified down to the protobuf level by test_due_rows_passes_real_firestore_document_snapshot_cursor_across_pages.
  • backend/database/outbox_firestore.py — claim() keeps its break once len(claims) >= n, and the n <= 0 guard fixes a subtle old edge where claim(0) could still take one row (the break previously only fired after an append).
  • backend/tests/unit/test_outbox_firestore.py — the _install_paged_due_query fake enforces ≤100-doc pages and rejects dict cursors, and the real-SDK test asserts the second page's start_after carries (due_at double, __name__ reference). Solid coverage of exactly the failure mode.
  • backend/tests/integration/test_outbox_conformance.py — PL-002 (live-lease and privacy-retired prefixes) and PL-003 (>100 budget) pin the fixed behavior; the privacy-prefix test also asserts blocked rows are retired without consuming claim budget.

Performance: one watch item, not blocking — due_rows' limit is now page size rather than a scan cap, so a single claim() call can walk the entire due backlog in ≤100-doc pages when rows are due-but-unclaimable (leased/dormant/missing task_token). Reads per call go from a hard ≤100 to O(due backlog), bounded by the early break at n claims and by sweep repairing/discarding stale rows. Worth keeping an eye on read volume if a large stale backlog ever accumulates. Cost: Firestore reads only; no external API spend. Security/privacy: same collection, same due_at-bounded query, privacy fencing preserved and now tested to not hide runnable work.

USER IMPACT: none — internal change; the user-visible effect is that enrichment backlog items no longer stall indefinitely behind leased or deleted conversations.

Nothing further required from my side; @aryanorastar has already approved this head. Optional nice-to-have: a metric or log line for documents scanned per claim() call so the unbounded-scan trade-off is observable in production.

Automated review on behalf of the Omi maintainers; merge decisions remain with human maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@ocakciomursel-pixel
ocakciomursel-pixel force-pushed the fix/firestore-outbox-claim-cursor-pagination-23558 branch 2 times, most recently from 7f6e7ad to f2905ea Compare November 14, 2026 15:06

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since the last automated review (2026-10-31, pre-rebase head): addressed — the branch is now rebased onto current main, resolving the base drift · still open — nothing blocking; the optional scanned-docs-per-claim metric remains a nice-to-have · newly introduced — the rebase dropped the emulator-backed conformance tests (PL-004 has no replacement), and CI is red on a file this PR does not touch.

Verdict: the production fix remains correct and is not superseded (current main still carries the old 100-row-capped due_rows), but one coverage regression introduced by the rebase should be fixed before merge.

Re-verified on head f2905ea:

  • backend/utils/enrichment/outbox.py — due_rows pages by (due_at, name) with start_after(page[-1]) (DocumentSnapshot cursor) and short-page termination; identical to the previously approved logic.
  • backend/database/outbox_firestore.py — claim() keeps the n <= 0 guard, page_size = max(1, min(100, max(32, n * 4))), and the len(claims) >= n break, so paging stays bounded by the actionable claim budget.
  • backend/tests/unit/test_outbox_firestore.py — the paged fake (<=100-doc pages, dict cursors rejected) plus test_pl002_live_lease_prefix_cannot_hide_runnable_work, test_pl002_retired_privacy_prefix_cannot_consume_the_claim_budget, test_pl003_explicit_backlog_budget_is_not_silently_capped_at_100, and the protobuf-level snapshot-cursor test are all present and pin the starvation and budget invariants at unit level.

What the rebase dropped: backend/tests/integration/test_outbox_conformance.py at this head is byte-identical to main. The emulator-backed PL-002/PL-003 conformance runs and the PL-004 (failed-wake vs successful-repair accounting) test cited by earlier reviews and the maintainer approval are gone, and PL-004 has no unit-level replacement. Please restore the PL-004 coverage (and ideally the emulator conformance runs), or note why they no longer apply after the rebase. The PR body also still advertises conformance tests this head no longer adds — worth aligning.

CI: Backend unit suite fails in tests/unit/test_home_transcribing_hold.py — a duration-guard trip (1.00s > 1.00s CPU on one test; all tests in the file pass), in a file untouched by this diff. That looks like main-lane timing noise rather than this change, but the suite does need to be green before merge.

Performance: unchanged from prior review — reads per claim() grow from a hard <=100 to O(due backlog) when due-but-unclaimable rows accumulate, bounded by the n-claims break; the intended trade for fixing the starvation.

USER IMPACT: none directly visible — enrichment backlog items (e.g. delayed summaries) stop stalling indefinitely behind leased or deleted rows.

Action items: (1) restore PL-004 coverage; (2) align the PR body's test-coverage claim with this head; (3) re-run or rebase past the unrelated timing-guard failure so the unit suite is green. The maintainer approval predates this rebase, so a quick re-confirm once the tests are back would close this out.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the needs-tests PR introduces logic that should be covered by tests label Nov 14, 2026
@ocakciomursel-pixel
ocakciomursel-pixel force-pushed the fix/firestore-outbox-claim-cursor-pagination-23558 branch from f2905ea to 6c22a98 Compare November 14, 2026 20:50
@ocakciomursel-pixel

Copy link
Copy Markdown
Contributor Author

Thanks for the catch @Git-on-my-level! Addressed on 6c22a9808a (rebased onto latest main c4e2466bb7):

  1. PL-004 coverage & why test_outbox_conformance.py had zero diff after rebase:
    • backend/tests/integration/test_outbox_conformance.py on main already includes test_pl002_live_lease_prefix_cannot_hide_runnable_work, test_pl002_retired_privacy_prefix_cannot_consume_the_claim_budget, test_pl003_explicit_backlog_budget_is_not_silently_capped_at_100, and test_pl004_failed_wakes_are_errors_until_a_repair_actually_succeeds (landed upstream in test(backend): inventory lifecycle writers and latch invariants #24591 / 8b3dd9f5aa), so git rebase cleanly elided the identical hunk.
    • Added unit-level test_pl004_failed_wakes_are_errors_until_a_repair_actually_succeeds (plus test_due_rows_cursor_survives_page_boundary_row_deletion_mid_scan) directly in backend/tests/unit/test_outbox_firestore.py (29/29 passing) so PL-004 failed-wake vs successful-repair accounting is also pinned in the hermetic unit suite on every PR run.
  2. PR description aligned: Updated the PR body to reflect query.start_after(page[-1]) (DocumentSnapshot cursor), the unit-level PL-002/PL-003/PL-004 + boundary-deletion tests, and the upstreamed conformance coverage on main.
  3. CI re-triggered on fresh main: Rebased past the unrelated test_home_transcribing_hold.py CPU duration-guard flake.

cc @aryanorastar ready for quick re-confirmation whenever convenient.

@ocakciomursel-pixel

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main (e50f1f20bf, picking up the #25312 / SCA-2279 CPU-duration guard fixes for test_batch_upload_coalescing.py and test_home_transcribing_hold.py that tripped shards 3/8 and 6/8 on 6c22a9808a) and hoisted the PL-004 test helper imports in backend/tests/unit/test_outbox_firestore.py (9d8e53bdc1) to module collection time (29 passed).

@ocakciomursel-pixel
ocakciomursel-pixel force-pushed the fix/firestore-outbox-claim-cursor-pagination-23558 branch from 6c22a98 to 9d8e53b Compare November 15, 2026 04:36
@Git-on-my-level
Git-on-my-level dismissed their stale review November 15, 2026 18:26

Both concerns from this review are resolved on head 9d8e53b: PL-004 coverage now has a unit replacement (test_pl004_failed_wakes_are_errors_until_a_repair_actually_succeeds), and CI is green on this head. No further changes requested.

@Git-on-my-level Git-on-my-level removed the needs-tests PR introduces logic that should be covered by tests label Nov 15, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed — the dropped PL-004 coverage now has a unit replacement (test_pl004_failed_wakes_are_errors_until_a_repair_actually_succeeds pins the failed-wake accounting: errors (0,0,0,3) -> repair rewoken (3,0,0,0) -> settled (0,0,0,0), with wake_check_after untouched while wakes fail), and CI is green again on this head · still open — nothing blocking · newly introduced — nothing.

Verdict: the production fix is correct and tightly scoped; everything I asked for on the previous head is settled, and I have no blocking issues left.

Verified on 9d8e53b:

  • backend/utils/enrichment/outbox.py (due_rows): keyset pagination by (due_at, name) using a DocumentSnapshot start_after cursor — the cursor form the maintainer review required — with a protobuf-level test asserting the second query carries start_at with double_value/reference_value cursor fields.
  • backend/database/outbox_firestore.py (claim): the n<=0 guard, the bounded page budget min(100, max(32, 4n)), and the len(claims) >= n break mean the now-unbounded due_rows generator is consumed lazily — no over-scan once the claim budget fills.
  • backend/tests/unit/test_outbox_firestore.py: PL-002 (a 101-row leased prefix and a 101-row privacy-retired prefix each span pages yet cannot hide or consume the claim budget), PL-003 (a 125-row budget is honored across exactly 2 stream calls, not silently capped at 100), and the mid-scan page-boundary deletion test proving the snapshot cursor survives a row being deleted between pages.

Performance: sequential pages of <=100, pulled only until the n-claim budget fills; worst case scans a long leased/retired due-prefix, which is exactly the starvation case this fixes. Cost: Firestore reads scale with that prefix; no other spend. Blast radius: claim_key CAS lease fencing and the row filter set are unchanged, so paging cannot double-claim rows and no new data leaves the pipeline.

One merge-time follow-up: #24591 added strict xfail markers to the emulator conformance runs of pl002/pl003 (backend/tests/integration/test_outbox_conformance.py, pinned to #23558). Once this lands those tests should pass — drop that xfail block in the same merge or an immediate follow-up so the suite flips green instead of XPASS-red.

USER IMPACT: none — internal change; enrichment reprocessing recovers from large backlogs instead of skipping or stalling overdue work.

Ready from my side — left for a maintainer to re-approve the current head (only a test-only delta plus rebase since @aryanorastar's approval) and merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Firestore enrichment outbox pull claims starve behind excluded rows and silently cap at 100

3 participants