Repository navigation
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.
2 issues found across 3 files
Confidence score: 2/5
- In
backend/database/memories.py, the scan cap can return a silently short page once the visible offset reaches 2,000 or hidden rows use the scan slack, despite more visible memories being available; continue scanning until the requested visible page is filled. - In
backend/database/memories.py, the scoring scan may stream up to 2,000 full documents, including encryptedcontent, without aListReadBudgetor per-RPC timeout, increasing resource and latency risk; enforce the read budget and timeout.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/database/memories.py">
<violation number="1" location="backend/database/memories.py:435">
P1: When the visible offset reaches 2,000, or hidden rows consume the scan slack, this cap returns a short page silently even though more visible memories exist. Continue scanning until the requested visible page is filled, or propagate a truncation/continuation result so callers do not treat the shortened page as end-of-data.</violation>
<violation number="2" location="backend/database/memories.py:446">
P2: The scoring scan streams full documents (including encrypted `content`) for the whole window — up to 2000 per request — via a raw `.stream()` with no ListReadBudget or per-RPC timeout, whereas the prior code streamed only `limit` full docs. This is up to 4x the full-doc reads for the default page, and up to 2000 for accounts with many hidden rows or deep offsets — the full-document streaming pattern the updated_desc path was redesigned to avoid after the GET /v3/memories 504. Stream a metadata projection (index fields) and hydrate only the emitted page, or wrap the scan in `budgeted_stream_list` with a per-RPC timeout.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| visible_limit = max(0, int(limit)) | ||
| visible_offset = max(0, int(offset)) | ||
| scan_budget = min( | ||
| _MEMORY_SCORING_VISIBLE_PAGE_SCAN_CAP, |
There was a problem hiding this comment.
P1: When the visible offset reaches 2,000, or hidden rows consume the scan slack, this cap returns a short page silently even though more visible memories exist. Continue scanning until the requested visible page is filled, or propagate a truncation/continuation result so callers do not treat the shortened page as end-of-data.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/memories.py, line 435:
<comment>When the visible offset reaches 2,000, or hidden rows consume the scan slack, this cap returns a short page silently even though more visible memories exist. Continue scanning until the requested visible page is filled, or propagate a truncation/continuation result so callers do not treat the shortened page as end-of-data.</comment>
<file context>
@@ -416,18 +420,50 @@ def get_memories(
+ visible_limit = max(0, int(limit))
+ visible_offset = max(0, int(offset))
+ scan_budget = min(
+ _MEMORY_SCORING_VISIBLE_PAGE_SCAN_CAP,
+ max(100, (visible_offset + visible_limit) * 4),
+ )
</file context>
| while scanned < scan_budget and len(result) < visible_limit: | ||
| batch_limit = min(100, scan_budget - scanned) | ||
| page_query = memories_ref.start_after(cursor_snapshot) if cursor_snapshot is not None else memories_ref | ||
| documents = list(page_query.limit(batch_limit).stream()) |
There was a problem hiding this comment.
P2: The scoring scan streams full documents (including encrypted content) for the whole window — up to 2000 per request — via a raw .stream() with no ListReadBudget or per-RPC timeout, whereas the prior code streamed only limit full docs. This is up to 4x the full-doc reads for the default page, and up to 2000 for accounts with many hidden rows or deep offsets — the full-document streaming pattern the updated_desc path was redesigned to avoid after the GET /v3/memories 504. Stream a metadata projection (index fields) and hydrate only the emitted page, or wrap the scan in budgeted_stream_list with a per-RPC timeout.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/memories.py, line 446:
<comment>The scoring scan streams full documents (including encrypted `content`) for the whole window — up to 2000 per request — via a raw `.stream()` with no ListReadBudget or per-RPC timeout, whereas the prior code streamed only `limit` full docs. This is up to 4x the full-doc reads for the default page, and up to 2000 for accounts with many hidden rows or deep offsets — the full-document streaming pattern the updated_desc path was redesigned to avoid after the GET /v3/memories 504. Stream a metadata projection (index fields) and hydrate only the emitted page, or wrap the scan in `budgeted_stream_list` with a per-RPC timeout.</comment>
<file context>
@@ -416,18 +420,50 @@ def get_memories(
+ while scanned < scan_budget and len(result) < visible_limit:
+ batch_limit = min(100, scan_budget - scanned)
+ page_query = memories_ref.start_after(cursor_snapshot) if cursor_snapshot is not None else memories_ref
+ documents = list(page_query.limit(batch_limit).stream())
+ if not documents:
+ break
</file context>
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks @aryanorastar — the diagnosis is right and the core fix is well executed. Verified per file:
backend/database/memories.py — The visible-scan (counting visible_offset skips / visible_limit fills over a start_after cursor) correctly fixes both failure modes of raw .limit().offset() + post-filter: short pages and raw-slot offset advancement. Keeping visibility in Python (no user_review/invalid_at FieldFilters) preserves legacy-doc semantics per #4498. One blocking item and two design notes:
- Blocking — this head breaks a pinned contract.
backend/testing/contracts/test_desktop_backend_parity.py::test_python_memory_query_and_filter_semanticsnow fails (assert 100 == 11): the fake pinslimit_value == data["limit"]/offset_value == data["offset"]on the query, which the visible-scan intentionally no longer applies (it batches.limit(min(100, budget))and never calls.offset()). The Desktop Backend Contracts workflow is red on this head while neighboring PR heads are green, so merging as-is would break the contract gate on main. Please update the parity contract/fixture for the new query shape in this PR (same deliberate-pin-update flow the repo uses elsewhere). - Read-cost on a path with 504 history. The scan streams full documents (encrypted
contentincluded) for up tomin(2000, max(100, (offset+limit)*4))rows, while theupdated_descpath in this same file was redesigned to metadata-only windows + per-page id fetches withbudgeted_stream_list+ per-RPC timeouts (#11831) after the 2026-08-18 GET /v3/memories 504 (comment abovelist_memory_updated_or_created_index). Skipped rows only needuser_review/invalid_at, so a.select()projection for the scan (full docs only for the returned page) and/or aListReadBudgetwould match the file's own bounding discipline. - Once
scanned == scan_budgetwith the page unfilled, callers get a short page indistinguishable from EOF — the same failure class at a deeper boundary (relevant aroundvisible_offset + limit ≥ 2000with dense hidden rows). A log line (or continuing while the last batch came back full) would make the truncation observable.
backend/tests/unit/test_get_memories_scoring_visibility_pagination.py — Good behavioral pinning of rejected/invalidated mid-page and visible-offset continuity, and the fake's offset+limit vs start_after semantics are faithful. Two gaps: (a) with scan_budget = max(100, (offset+limit)*4) and ≤6 fixture rows, the first batch always covers everything, so the start_after multi-batch branch — the actual fix mechanism — never executes; the docstring's "start_after scan (fixed) semantics" currently overstates coverage. A fixture with >100 raw rows (or an injectable batch size) would pin it. (b) patch.object(memories_db, '_prepare_memory_for_read', ...) is a no-op — @prepare_for_read bound the original into the wrapper closure at decoration time, so patching the module attribute never changes decryption; the tests pass because no row uses data_protection_level='enhanced'. Dropping it (or noting why) avoids implying decryption is stubbed.
.github/failure-classes/FC-raw-page-limit-before-visibility-filter.json — Follows the established failure-class schema; the contract statement is accurate and the scope hints are sensible. Minor: evidence_prs is empty — worth referencing the report PR/issue behind #12713 once linked.
CI fairness note: the "Backend unit suite" red is pre-existing on main (test_pinned_conversation_dump_set_is_exact, utils/llm/external_integrations.py — untouched here), not caused by this PR. The blocking item is only the contracts gate above.
Requesting changes just for the parity-contract update; the read-budget alignment and multi-batch test can land in the same push. Leaving the scan read-budget design (full-doc scan vs metadata-window pattern) for maintainer sign-off given the documented 504 history on this endpoint — happy to re-review.
— automated review on behalf of the Omi maintainers (AI-generated).
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
…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
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.
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 (BasedHardware#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]>
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]>
c0f16a8 to
1189368
Compare
|
Pushed The blocking parity contract. You were right that this head broke it, and the fix is not a fixture bump. The contract pinned Updating it turned up a second problem in the same test. The old Read cost and truncation-as-EOF. Both had the same root, and one reframing fixes both. A page with nothing hidden needs exactly needed = visible_offset + visible_limit
scan_budget = needed + _MEMORY_SCORING_VISIBLE_PAGE_SCAN_SLACKThe first batch reads exactly Your multi-batch request caught a live bug, not just missing coverage. My first version scaled the slack with the page ( Test gaps. 150 hidden rows now force the
Suites, run individually: pagination 7, |
* fix(backend): fill chat pages past reported rows 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 * fix(backend): bound the visible-page slack, not the page itself 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]> * fix(backend): make the visible-page slack flat rather than proportional 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 (#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]> --------- 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).
|
Merged current
My first resolution merged the two records wholesale — both artifacts, union of That rule is right and I had not internalised it. An instance PR quietly rewriting shared contract text is how a registry stops meaning the same thing to everyone who greps it. The record is now The wider edits are still worth making, as a registry-only lifecycle PR: The declaration also changed. It said Verification after the merge
Merged rather than rebased so the review history on the earlier heads stays intact. The The three review items from your last pass remain addressed; this only resolves the conflict. |
kodjima33
left a comment
There was a problem hiding this comment.
Confidence gate: root cause stated + fixes #12713 (confirmed still open/unfixed on main) + new regression test = 3/5; diff is 371 lines (over the 300-line scoped-diff cap) and Backend unit suite is red on test_batch_upload_storage.py/test_merge_validation.py — neither touched by this diff, and identically red on sibling #12714... er #11183 while main's own latest runs are green, so this looks like the known stale-frozen-merge-ref CI artifact, not a real regression (reran once per policy, same result). The previously-blocking pinned parity-test failure (test_python_memory_query_and_filter_semantics) is now fixed — contracts check passes. Below the 4/5 merge bar either way; approving only, not merging.
Dismissed: verified resolved on the current head 6119bdb. The blocking parity-contract failure is fixed by the deliberate pin update in backend/testing/contracts/test_desktop_backend_parity.py (green on this head); the multi-batch start_after continuation is now covered by the 150-hidden-row fixture; the no-op patch.object stub was removed; the first batch now reads exactly offset+limit so the read-cost floor is the page itself. A maintainer has signed off on this head.
|
Re-verified on the current head 6119bdb — everything from the earlier change request is resolved, and that review is now dismissed. Per file: backend/database/memories.py — The budget now floors at the page ( backend/testing/contracts/test_desktop_backend_parity.py — The deliberate pin update is the right call. The old fake recorded backend/tests/unit/test_get_memories_scoring_visibility_pagination.py — The multi-batch gap is closed: 150 consecutive rejected rows force the .github/failure-classes/FC-raw-page-limit-before-visibility-filter.json — Verified against On the red Backend unit suite: I pulled the log — both failures ( Two non-blocking notes:
Thanks @aryanorastar — the parity-contract root-cause writeup (the fake that asserted an offset it never applied) and the failure-class merge resolution under the instance-fix rule were both excellent contributions beyond the fix itself. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
…sibility-pagination
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 BasedHardware#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.
|
Pushed The red check. Merged Budget exhaustion is now observable. You put it well — a bounded scan can't avoid that edge, only make it visible. The loop now logs when it stopped on its own ceiling rather than on the end of the collection, carrying the offset, limit, scanned count and budget, which together say whether the slack is wrong for that account's data: if scanned >= scan_budget and len(result) < visible_limit:
logger.warning('get_memories_scan_budget_exhausted offset=%s limit=%s scanned=%s budget=%s returned=%s', ...)The guard is deliberately exact rather than "the page came back short". Warning on every short page would report ordinary end-of-data as a budget failure, and a warning that fires on the common case is one nobody reads — which would cost the signal you asked for. Both directions are pinned: Left the deferred Verification: One thing I found while verifying, not a blocker and not from this diff: running the parity contract and |
kodjima33
left a comment
There was a problem hiding this comment.
Confirmed: raw limit/offset before visibility filter is still on main (memories.py:424) — real bug, not already fixed. Bounded visible-page scan is well-tested (13+8 passing), scoped fix, CI green. Merging.
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 #12713.
Summary
get_memoriesdefaultscoring_descapplied Firestore.limit().offset()before filtering user-rejected (user_review is False) and invalidated (invalid_atset) rows in Python. A hidden row in the middle of a raw page stole a visible slot, so pages came back short and later visible memories were left unfetched for single-page callers.This mirrors the bounded visible-page scan used for chat
get_messagesreported pagination: walk the scoring order untiloffsetvisible rows are skipped andlimitvisible rows are collected, with a hard scan cap so one request cannot stream unbounded history. Visibility stays in Python (#4498 / #11915) — no FieldFilter that would drop legacy docs missing the fields.Change
backend/database/memories.py— scoring_desc visible-page scan instead of raw limit/offset-then-filterbackend/tests/unit/test_get_memories_scoring_visibility_pagination.py— behavioral coverage for rejected/invalidated-in-the-middle and visible offset continuity.github/failure-classes/FC-raw-page-limit-before-visibility-filter.json— new failure class for this contractNo router / client API shape change. The
updated_descpath already filtered visibility before slicing and is unchanged.Product invariants affected
Failure-Class: FC-raw-page-limit-before-visibility-filter
The class was
newwhen this PR opened. Sibling #12712 has since merged and landedthe definition on
main, so this is now the second recorded instance of an existingclass rather than its birth — the memories
scoring_descpath alongside the chatget_messagespath. The registry edit here is the minimum an instance fix is allowed: this PR's test isappended to
canonical_prevention_artifact, and every other field is exactlymain's.My first resolution also merged the
violated_contractwording,scope_hintsandevidence_prs--scripts/failure-class validaterejected that withinstance_fix_mutates_registry, and it is right to. An instance PR quietly rewritingshared contract text is how a registry stops meaning the same thing to everyone.
Those wider edits are still worth making, as a registry-only lifecycle PR: the
violated_contractwording naming both hidden-row kinds,scope_hintscovering thememories paths, and
evidence_prsciting 12712 and 12714 rather than staying empty.Verification
['visible-a']instead of['visible-a', 'visible-b'](short page after visibility filter).pytest tests/unit/test_get_memories_scoring_visibility_pagination.py tests/unit/test_memories_user_review.py→ 13 passed (with query-contract index check)pytest tests/unit/test_memory_offset_read_cost.py tests/unit/test_list_read_budget_contract.py -k memor→ 8 passedHonest gaps
canonical_prevention_artifactlists in the FC JSON.Line-Count-Exception: backend/database/memories.py | 1459 -> 1527 | The visible-page scan replaces a three-line raw limit/offset slice with a cursor loop, and carries the comments recording why visibility cannot move into a FieldFilter (#4498) and why the budget floors at the page. The last 15 lines are the budget-exhaustion warning: a page that stops on its own ceiling is indistinguishable from end-of-data to the caller, so the loop says which one happened. Splitting this file is a larger refactor than a pagination bug fix should carry.