Repository navigation
fix(backend): fill chat message pages past reported rows - #12712
undivisible merged 3 commits into
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
All reported issues were addressed across 3 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
|
Thanks @aryanorastar — this fixes a real pagination bug and follows the pattern this codebase already established for the same failure class. What I verified:
Two tradeoffs worth a maintainer eye (neither blocking from my side):
Leaving for human maintainer review before merge: user-data pagination surface plus the chat-send read-cost tradeoff above. No split requested — the change is cohesive. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
…leanup (#12740) The `Backend unit suite` CI lane (added in c094859, merged this morning) fails unconditionally on every PR to main: - tests/slow_guardrail_manifest.txt lists tests/unit/test_ws_g_module_aliases.py, which was deleted by a7bc5fd (dead-code removal) the day before the manifest was built, so run-slow-guardrails-ci.sh exits 1 before running anything. - Once that's fixed, test_managed_call_sites_absent_from_the_inventory_fail_ci (backend/tests/unit/test_llm_gateway_coverage_guardrails.py) fails because docs/llm/model_endpoint_inventory.yaml still lists call sites in utils/llm/promotion_proposals.py and utils/llm/promotion_routes.py, also removed by a7bc5fd. Both are stale references to the same commit's deletions, not code bugs. Verified: 5 of 6 currently-open backend PRs (#12739, #12721, #12719, #12714, #12712) show this exact "Backend unit suite" FAILURE. Fix: remove the stale manifest line (with a dated note per the file's own "never silently dropped" convention) and the two stale inventory entries. Tested: `PYTHON=.venv/bin/python bash scripts/run-slow-guardrails-ci.sh` now passes (103 passed, 1 skipped, was: hard-failing before any test ran). Also ran test_llm_gateway_coverage_guardrails.py + test_firestore_query_contract.py directly: 72 passed. Failure-Class: none
kodjima33
left a comment
There was a problem hiding this comment.
Real fix, confirmed not already fixed on main (get_messages on origin/main still does .limit().offset() before the reported-filter). Root cause clearly stated, scoped diff, new regression tests. Backend unit suite shows one failure (test_client_processing_trust_boundary.py) unrelated to this diff -- confirmed stale-base: that guardrail was independently repaired on main via #12729, and this PR's base is 118 commits behind (fab6031 vs current main). Holding at approve per stale-base policy rather than merging on a red required check; not rebasing the branch.
Firestore limit/offset ran before the Python reported filter, so hidden rows stole visible page slots and later pages could skip messages the client never saw. Scan with a bounded budget like reconcile until the visible limit is filled. Failure-Class: new
Two review findings on the visible-page scan, both real. Read amplification. The budget floored at 100 and the first batch was a flat min(100, budget), so a page that needed 5 rows streamed 100 documents. The chat-send path reads history at limit=5/10/15, so every send paid ~20x the documents the old raw query did. Read exactly `needed` on the first batch; slack is now paid only by a page that actually meets a reported row. Deep-offset truncation. Capping the *total* scan at 1000 meant offset + limit beyond the cap could never be reached and the page came back empty, which routers/chat.py reads as end-of-results. That is the same "later visible messages are never fetched" defect this scan exists to fix, reintroduced at depth, and a regression against the raw .offset() it replaced. The fix for both is the same reframing: a page with no reported rows needs exactly offset + limit documents, which is what the previous raw query already streamed. Floor the budget there and bound only the slack above it. The scan can then never read fewer documents than the query it replaced, so it can never fail to service an offset that used to work, while dense reported clusters stay bounded by the slack cap. Verified by mutation: with the old budget restored, the clean-page test reports `assert 100 == 5` and the deep-offset test returns [] instead of the page. Failure-Class: none Co-Authored-By: Claude Opus 5 <[email protected]>
58ac12a to
6721a84
Compare
|
Pushed Read amplification. The budget floored at Deep-offset truncation. This one was the more serious of the two: capping the total scan at 1000 meant Both have the same root, and fixing the framing fixes both rather than patching them separately. A page with no reported rows needs exactly needed = max(offset, 0) + max(limit, 0)
scan_budget = needed + min(CHAT_MESSAGES_VISIBLE_PAGE_SCAN_SLACK, needed * 3)The scan can now never read fewer documents than the query it replaced, so it can never fail to service an offset that used to work; and the first batch reads exactly Mutation-checked — with the old capped budget and flat first batch restored: Three new tests: a clean page streams no more documents than it returns, a deep offset is still serviced, and the slack stays bounded when every scanned row is reported. 12 passed across the pagination and message-count suites; On the suggested The |
Scaling the slack with the page size gave a small page a tiny allowance -- limit=2 got six documents -- so a run of reported rows longer than that still returned an empty page, which routers/chat.py reads as end-of-results. That is the same defect this scan exists to fix, surviving at a different threshold. Found while applying the identical fix to the memories sibling (BasedHardware#12714), where a new multi-batch test with 150 hidden rows ahead of the page failed against the proportional slack. Read cost is set by the batch sizing (first batch reads exactly what the page needs), not by this ceiling, so a flat allowance costs a clean page nothing and only bounds how far a page that meets reported rows may scan. Failure-Class: none Co-Authored-By: Claude Opus 5 <[email protected]>
…ing-visibility One conflict, and it is the collision this PR's description predicted. BasedHardware#12712 merged and brought its own copy of FC-raw-page-limit-before-visibility-filter.json, so the two sides added the same failure-class id -- an add/add conflict rather than a content one. Taking either side wholesale would have silently dropped the other instance's guard from the registry, which is the opposite of what a failure-class record is for. Merged the two into one record covering both instances: * canonical_prevention_artifact now lists both tests, chat and memories. A class with one artifact named looks like a one-off; both named is what makes the next occurrence greppable from either side. * canonical_prevention keeps main's get_messages_reconcile_page precedent (this PR's version had dropped it) and adds the budget-flooring rule the review surfaced: floor at offset + limit, bound only the slack, so a deep offset stays serviceable and a clean page reads no more than it returns. * violated_contract keeps the broader wording naming both hidden-row kinds. * scope_hints is the union. * evidence_prs cites 12712 and 12714 rather than staying empty, matching FC-task-candidate-unowned-commitment citing its own defining PR. scripts/failure-class validate: OK (fix commits=True; declaration=new). Suites after the merge: scoring-visibility pagination 7, memories_user_review 9, memory_offset_read_cost 5, desktop-backend parity 8, and the chat sibling's reported-pagination suite 6 now that it arrives from main. Co-Authored-By: Claude Opus 5 <[email protected]>
…change The merge resolution rewrote the shared failure-class record: violated_contract wording, canonical_prevention, scope_hints and evidence_prs, on top of adding this PR's test. scripts/failure-class rejects that, correctly: instance_fix_mutates_registry: an instance-fix PR must not edit failure-class definitions except to add or update 'canonical_prevention_artifact' on the declared class The rule is sound. An instance PR quietly rewriting shared contract text is how a registry stops meaning the same thing to everyone who greps it. So the record is now main's byte for byte, plus this instance's guard appended to canonical_prevention_artifact -- the one field an instance fix owns. The wider edits (wording that names both hidden-row kinds, memories scope_hints, evidence_prs citing 12712 and 12714) belong in a registry-only lifecycle PR. Also corrects the declaration from 'new' to the class id: BasedHardware#12712 merged while this was in review and landed the definition, so this is the second recorded instance of an existing class, not its birth. scripts/failure-class validate: OK (declaration=FC-raw-page-limit-before-visibility-filter).
* fix(backend): fill scoring memory pages past hidden rows Failure-Class: new scoring_desc applied Firestore limit/offset before the Python visibility filter, so rejected/invalidated rows shortened pages and skipped later visible memories. Scan with a bounded budget until the visible page fills. * fix(backend): bound the visible-page slack and update the parity pin Three review items, all real. Parity contract (blocking). test_python_memory_query_and_filter_semantics pinned limit_value == data["limit"] and offset_value == data["offset"] -- that a raw Firestore limit/offset was applied to the scoring stream. That is the defect itself: limit/offset applied before user_review / invalid_at were filtered in Python, so a hidden row inside the raw page stole a visible slot. Keeping the pin would pin the bug. It now asserts the visible-page contract: no raw offset at all, and a first read of exactly the documents the page needs. The old result assertion (["active"]) passed only because the fake recorded offset_value without applying it. With real visible-offset semantics the fixture's offset of 4 is past the only visible row, so the correct page is empty. Visibility filtering is now pinned separately at offset 0, where it is reachable. Read cost. The budget floored at max(100, ...) and the first batch was a flat min(100, budget), so every small page streamed 100 full documents on an endpoint with a documented 504 history (#11831). A page with nothing hidden needs exactly offset + limit documents, which is what the old raw query streamed, so the budget now floors there and the first batch reads exactly that. Truncation at depth. Capping the *total* scan at 2000 meant offset + limit past the cap could never be reached and the page came back empty, which callers read as end-of-data -- the same defect at a deeper boundary. Flooring the budget at the page fixes it. The slack above the floor is flat rather than proportional. Scaling it with the page size gave a small page a six-document allowance, so a dense run of hidden rows still returned an empty page; the new multi-batch test caught that. Read cost is set by the batch sizing, not by this ceiling, so a flat allowance costs a clean page nothing. Tests: a dense block of 150 hidden rows now forces the start_after continuation that no earlier fixture reached, plus clean-page read cost, deep offset, and bounded slack. Dropped the ineffective _prepare_memory_for_read patch -- @prepare_for_read binds the original into its closure at decoration time, so patching the module attribute never changed decryption. Failure-Class: new Co-Authored-By: Claude Opus 5 <[email protected]> * fix(backend): keep the registry edit inside what an instance fix may change The merge resolution rewrote the shared failure-class record: violated_contract wording, canonical_prevention, scope_hints and evidence_prs, on top of adding this PR's test. scripts/failure-class rejects that, correctly: instance_fix_mutates_registry: an instance-fix PR must not edit failure-class definitions except to add or update 'canonical_prevention_artifact' on the declared class The rule is sound. An instance PR quietly rewriting shared contract text is how a registry stops meaning the same thing to everyone who greps it. So the record is now main's byte for byte, plus this instance's guard appended to canonical_prevention_artifact -- the one field an instance fix owns. The wider edits (wording that names both hidden-row kinds, memories scope_hints, evidence_prs citing 12712 and 12714) belong in a registry-only lifecycle PR. Also corrects the declaration from 'new' to the class id: #12712 merged while this was in review and landed the definition, so this is the second recorded instance of an existing class, not its birth. scripts/failure-class validate: OK (declaration=FC-raw-page-limit-before-visibility-filter). * fix(backend): make a budget-exhausted memories page visible in logs Merged current main, which clears the red Backend unit suite: both failures were ModuleNotFoundError: No module named 'models.client_processing' in files this PR does not touch, reproducing at this PR's base commit and fixed on main by #12785. Also takes the reviewer's second non-blocking note. A page that spends its whole needed + slack budget mid-hidden-run returns short, and a caller cannot tell that apart from end-of-data. A bounded scan cannot design that edge away -- it can only make it observable -- so the loop now logs when it stopped on its own ceiling rather than on the end of the collection, with the offset, limit, scanned count and budget needed to tell whether the slack is wrong for that account. The guard is exact: scanned >= scan_budget AND the page is unfilled. Warning on every short page would report ordinary end-of-data as a budget failure and make the signal worthless, so both directions are pinned by test and mutation-checked -- making the condition unconditional fails the quiet test, and downgrading the log fails the loud one. 9 tests pass in test_get_memories_scoring_visibility_pagination.py. The parity contract passes 8/8 on this head; main's version of that file fails 1 of the same 8, which this PR's pin update is what fixes. --------- Co-authored-by: Claude Opus 5 <[email protected]>
BasedHardware#12714 merged at 14:39Z, producing exactly the conflict its review predicted: both PRs rewrite `canonical_prevention`, so the line collides even though the edits mean different things. Resolved by keeping this PR's text, which is a strict superset -- main's version is the original two sentences, this one adds the two lessons the second instance paid for (floor the budget at offset + limit; keep the slack flat) and widens `violated_contract` to name both hidden-row kinds. Two details the mechanical "keep ours" would have got wrong: - main re-encoded the em-dash as `—` and this branch had degraded it to a hyphen. Restored the em-dash, and kept this file's own escaped convention rather than switching it to a literal. - `canonical_prevention_artifact` now carries both tests, because BasedHardware#12714 added the memories one and this merge keeps it. That field was always BasedHardware#12714's to own; the boundary the validator draws held on its own. `evidence_prs` cites BasedHardware#12712 and BasedHardware#12714, and both are now merged -- the review's concern about citing an open PR resolved itself by merge order. Verified: JSON parses, `scripts/failure-class validate --pr-body-file` returns ok: true, and the diff against main is exactly the four fields this PR claims.
…it-before-visibility-filter (#12780) Registry-only. One JSON file, no code and no behaviour change. The class was born in #12712 for chat get_messages and now has a second recorded instance in #12714 for the memories scoring_desc path, but the definition still described only the first. violated_contract now names both hidden-row kinds. "for example reported chat messages" reads as a chat-specific defect; the memories path hides rows on user_review is False and invalid_at, for the same reason -- the predicate cannot become a Firestore where without dropping legacy documents missing the field (#4498) -- and with the same consequence. canonical_prevention gains the two rules the second instance's review actually established, both non-obvious and both paid for twice: * Floor the budget at offset + limit and bound only the slack. Capping the total leaves a deep offset unreachable, so the page returns empty and the caller reads that as end-of-data -- the original defect at a deeper boundary. * Keep the slack flat rather than proportional. A proportional slack gives limit=2 a six-document allowance, too thin to cross a dense run of hidden rows. That was caught by a reviewer-requested multi-batch test only after the proportional version had already shipped to both PRs. A canonical prevention that omits them lets the third instance rediscover them. scope_hints adds the memories paths; evidence_prs goes from [] to [12712, 12714]. canonical_prevention_artifact is deliberately untouched -- #12714 appends the memories test there, which is the one field an instance fix owns. This PR exists because scripts/failure-class rejected folding these edits into that merge (instance_fix_mutates_registry), and routing around that rule would defeat it. Failure-Class: none Co-authored-by: Claude Opus 5 <[email protected]>
Fixes #12709.
Summary
get_messagesapplied Firestore.limit().offset()before filteringreported is Truein Python. A reported row in the middle of a raw page stole a visible slot, so pages came back short and later visible messages were left unfetched for single-page callers.This walks the newest-first stream until
offsetvisible rows are skipped andlimitvisible rows are collected, with a bounded scan so one request cannot stream unbounded history.Change
backend/database/chat.py—get_messagesvisible-page scan instead of raw limit/offset-then-filterbackend/tests/unit/test_get_messages_reported_pagination.py— behavioral coverage.github/failure-classes/FC-raw-page-limit-before-visibility-filter.json— new failure classNo router / client API shape change.
get_app_messages(no offset) andget_cache_aligned_messages(already over-fetches) are left alone.How the scan is bounded
A page with no reported rows needs exactly
offset + limitdocuments — which is what the raw.offset(n).limit(m)query already streamed. So the budget floors at the page and bounds only the slack above it:Two consequences worth stating, because the first version of this PR got both wrong:
needed.Review findings, both fixed
Both were real. Thanks for catching them — the second one in particular was the reviewed bug reintroduced at depth, which is not something I would have found from the passing tests.
Read amplification (cubic P2, and Git-on-my-level's first tradeoff). The budget floored at
max(100, ...)and the first batch was a flatmin(100, budget), so a page needing 5 rows streamed 100 documents.backend/utils/chat.pyreads history atlimit=5/10/15on the chat-send path, so every send paid ~20x the documents it used to. Fixed by reading exactlyneededon the first batch.Deep-offset truncation (cubic P2, and Git-on-my-level's second tradeoff). Capping the total scan at 1000 meant
offset + limitbeyond the cap could never be reached, so the page came back empty — androuters/chat.pyreads an empty page as end-of-results. That is the same "later visible messages are never fetched" defect this PR exists to fix, reintroduced at depth, and a straight regression against the raw.offset()it replaced. Fixed by the floor above.On cubic's suggestion of an explicit
has_more/ resume signal: I did not add one. It would change the shape of an endpoint this PR is otherwise transparent to, and with the budget floored at the page it is no longer needed to avoid the EOF masquerade — an offset that used to be serviceable still is. A cursor for/v2/messagesis worth doing, but as its own change rather than inside a pagination bug fix.Verification
Mutation-checked — with the old capped budget and flat first batch restored:
Both original tests still fail on
main's limit-then-filter path with['visible-a']instead of['visible-a', 'visible-b'].With the fix:
pytest tests/unit/test_get_messages_reported_pagination.py tests/unit/test_chat_message_count.py— 12 passedpytest tests/unit/test_desktop_migration.py -k MessageReconcileKeyset— 3 passedFive tests now cover: reported-in-the-middle, visible offset continuity, a clean page streaming no more documents than it returns, a deep offset still being serviced, and slack staying bounded when every scanned row is reported.
Rebased onto current
main(176a02fe0d). The branch was 112 commits behind; thetest_client_processing_trust_boundary.pyfailure kodjima33 correctly diagnosed as stale-base was repaired on main in #12729 and is gone from this head.Honest gaps
Failure-Class: new