Skip to content

fix(backend): fill scoring memory pages past hidden rows - #12714

Merged
kodjima33 merged 6 commits into
BasedHardware:mainfrom
aryanorastar:fix/memory-scoring-visibility-pagination
Sep 6, 2026
Merged

kodjima33 merged 6 commits into
BasedHardware:mainfrom
aryanorastar:fix/memory-scoring-visibility-pagination

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #12713.

Summary

get_memories default scoring_desc applied Firestore .limit().offset() before filtering user-rejected (user_review is False) and invalidated (invalid_at set) 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_messages reported pagination: walk the scoring order until offset visible rows are skipped and limit visible 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-filter
  • backend/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 contract

No router / client API shape change. The updated_desc path already filtered visibility before slicing and is unchanged.

Product invariants affected

  • INV-MEM-1

Failure-Class: FC-raw-page-limit-before-visibility-filter

The class was new when this PR opened. Sibling #12712 has since merged and landed
the definition on main, so this is now the second recorded instance of an existing
class rather than its birth — the memories scoring_desc path alongside the chat
get_messages path. The registry edit here is the minimum an instance fix is allowed: this PR's test is
appended to canonical_prevention_artifact, and every other field is exactly main's.
My first resolution also merged the violated_contract wording, scope_hints and
evidence_prs -- scripts/failure-class validate rejected that with
instance_fix_mutates_registry, and it is right to. An instance PR quietly rewriting
shared 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_contract wording naming both hidden-row kinds, scope_hints covering the
memories paths, and evidence_prs citing 12712 and 12714 rather than staying empty.

Verification

  • Before the fix, the new tests failed on main with ['visible-a'] instead of ['visible-a', 'visible-b'] (short page after visibility filter).
  • After the fix:
    • 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 passed

Honest gaps

  • No live Firestore / emulator integration run (hermetic fakes only).
  • Physical / on-device smoke not run (no kit); backend-only change.
  • Open sibling PR fix(backend): fill chat message pages past reported rows #12712 may land the same failure-class id for chat; if both merge, combine canonical_prevention_artifact lists in the FC JSON.

Review in cubic

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 encrypted content, without a ListReadBudget or 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

Comment thread backend/database/memories.py Outdated
visible_limit = max(0, int(limit))
visible_offset = max(0, int(offset))
scan_budget = min(
_MEMORY_SCORING_VISIBLE_PAGE_SCAN_CAP,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: 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())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: 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 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.

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:

  1. Blocking — this head breaks a pinned contract. backend/testing/contracts/test_desktop_backend_parity.py::test_python_memory_query_and_filter_semantics now fails (assert 100 == 11): the fake pins limit_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).
  2. Read-cost on a path with 504 history. The scan streams full documents (encrypted content included) for up to min(2000, max(100, (offset+limit)*4)) rows, while the updated_desc path in this same file was redesigned to metadata-only windows + per-page id fetches with budgeted_stream_list + per-RPC timeouts (#11831) after the 2026-08-18 GET /v3/memories 504 (comment above list_memory_updated_or_created_index). Skipped rows only need user_review/invalid_at, so a .select() projection for the scan (full docs only for the returned page) and/or a ListReadBudget would match the file's own bounding discipline.
  3. Once scanned == scan_budget with the page unfilled, callers get a short page indistinguishable from EOF — the same failure class at a deeper boundary (relevant around visible_offset + limit ≥ 2000 with 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.

@Git-on-my-level Git-on-my-level added needs-tests PR introduces logic that should be covered by tests needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Sep 4, 2026
kodjima33 added a commit that referenced this pull request Sep 4, 2026
…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
aryanorastar and others added 2 commits September 4, 2026 20:44
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]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Sep 4, 2026
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]>
@aryanorastar
aryanorastar force-pushed the fix/memory-scoring-visibility-pagination branch from c0f16a8 to 1189368 Compare September 4, 2026 15:25
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed 1189368f62, rebased onto current main (176a02fe0d). All three items addressed.

The blocking parity contract. You were right that this head broke it, and the fix is not a fixture bump. The contract 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, so keeping the pin would have pinned the bug. It now asserts the visible-page contract: offset_value is None, and a first read of exactly offset + limit.

Updating it turned up a second problem in the same test. The old result == ["active"] passed only because FakeQuery recorded offset_value without applying it — the raw offset was asserted but never exercised, so the contract could not distinguish a correct page from a mis-paginated one. With real visible-offset semantics the fixture's offset of 4 is past the only visible row, so the correct page is empty. That is now asserted as [], with visibility filtering pinned separately at offset 0 where it is actually reachable.

Read cost and truncation-as-EOF. Both had the same root, and one reframing fixes both. A page with nothing hidden needs exactly offset + limit documents — which is what the old raw query already streamed — so the budget floors at the page and bounds only the slack above it:

needed = visible_offset + visible_limit
scan_budget = needed + _MEMORY_SCORING_VISIBLE_PAGE_SCAN_SLACK

The first batch reads exactly needed, so the 100-document floor is gone and a clean page streams no more than it returns. And because the floor is the page, a deep offset can never be unreachable — the scan never reads fewer documents than the query it replaced.

Your multi-batch request caught a live bug, not just missing coverage. My first version scaled the slack with the page (needed * 3), which gives limit=2 a six-document allowance — so a dense run of hidden rows still returned an empty page. That is the truncation-as-EOF defect surviving at a different threshold, and only the 150-hidden-row fixture exposed it. The slack is now flat; read cost is set by the batch sizing, not by that ceiling, so a flat allowance costs a clean page nothing. The same correction is on the chat sibling #12712, which had shipped the identical proportional slack.

Test gaps. 150 hidden rows now force the start_after continuation no earlier fixture reached. The patch.object(memories_db, '_prepare_memory_for_read', ...) is gone, with a comment recording why it never worked — @prepare_for_read binds the original into its wrapper closure at decoration time.

.select() projection — not landed, deliberately. You left the scan read-budget design for maintainer sign-off, and the flooring changes the numbers that decision rests on: a clean page now streams exactly offset + limit documents rather than 100, so the remaining exposure is dense-hidden-row scans only. Doing it properly means projecting the scan and hydrating the emitted page through _fetch_memory_docs_by_ids — the pattern updated_desc already uses — which is a real change to both fakes. Say the word and it goes in this PR; otherwise it is a clean follow-up.

Suites, run individually: pagination 7, test_memories_user_review 9, test_memory_offset_read_cost 5, test_list_read_budget_contract 34, test_desktop_backend_parity 8.

undivisible pushed a commit that referenced this pull request Sep 5, 2026
* 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]>
aryanorastar and others added 2 commits September 5, 2026 11:43
…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).
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Merged current main (09ff17e4e5) on c9766a3a7a. The conflict was the one this PR's description predicted, and it needed a real decision rather than picking a side.

FC-raw-page-limit-before-visibility-filter.json was an add/add conflict. #12712 merged and brought its own copy of the same failure-class id. Taking either side wholesale would have dropped the other instance's guard from the registry — which defeats the point of the record, since a class that names only one artifact reads as a one-off rather than a pattern with two known occurrences.

My first resolution merged the two records wholesale — both artifacts, union of scope_hints, combined violated_contract wording, evidence_prs citing both PRs. scripts/failure-class rejected it, and 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

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 main's byte for byte, plus this instance's test appended to canonical_prevention_artifact — the one field an instance fix owns.

The wider edits are still worth making, as a registry-only lifecycle PR: violated_contract wording naming both hidden-row kinds, scope_hints covering the memories paths, and evidence_prs citing 12712 and 12714 rather than staying empty. Happy to send that separately.

The declaration also changed. It said Failure-Class: new, which was true when this opened. #12712 merged during review and landed the definition, so this is now the second recorded instance of an existing class rather than its birth — declared as FC-raw-page-limit-before-visibility-filter.

Verification after the merge

  • scripts/failure-class validate --pr-body-file — OK: validate (declaration=FC-raw-page-limit-before-visibility-filter)
  • test_get_memories_scoring_visibility_pagination.py — 7 passed
  • test_memories_user_review.py — 9 · test_memory_offset_read_cost.py — 5
  • testing/contracts/test_desktop_backend_parity.py — 8 passed
  • test_get_messages_reported_pagination.py — 6 passed, now that the chat sibling arrives from main

Merged rather than rebased so the review history on the earlier heads stays intact. The memories.py scan is unchanged by the merge — needed = visible_offset + visible_limit, scan_budget = needed + _MEMORY_SCORING_VISIBLE_PAGE_SCAN_SLACK, flat slack — and 0 behind main.

The three review items from your last pass remain addressed; this only resolves the conflict.

@kodjima33 kodjima33 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.

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.

@Git-on-my-level
Git-on-my-level dismissed their stale review September 6, 2026 10:06

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.

@Git-on-my-level

Copy link
Copy Markdown
Member

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 (needed = visible_offset + visible_limit) with a flat 2000-document slack, so a clean page streams exactly what it returns (the 100-document first-batch floor is gone) and a deep offset can never become unreachable — that closes both the read-cost concern and the truncation-as-EOF-at-depth regression the intermediate total-cap design had. The 100-doc continuation batches via start_after match the fixture's batch telemetry, and the updated_desc branch is untouched.

backend/testing/contracts/test_desktop_backend_parity.py — The deliberate pin update is the right call. The old fake recorded offset_value without ever applying it, so the previous result == ["active"] assertion genuinely could not distinguish a correct page from a mis-paginated one. Pinning offset_value is None + limit_value == offset + limit, asserting [] at the fixture's unreachable offset, and re-pinning visibility at offset 0 is strictly stronger than what it replaces. Green on this head in the contracts job.

backend/tests/unit/test_get_memories_scoring_visibility_pagination.py — The multi-batch gap is closed: 150 consecutive rejected rows force the start_after continuation (the actual fix mechanism) and assert more than one raw read. The no-op patch.object stub is gone with a comment recording why it never worked. All 7 tests pass on this head.

.github/failure-classes/FC-raw-page-limit-before-visibility-filter.json — Verified against main: the only substantive delta is the appended canonical_prevention_artifact entry, exactly the field an instance fix owns (the canonical_prevention wording delta is a \u2014 escaping normalization of identical text).

On the red Backend unit suite: I pulled the log — both failures (tests/unit/test_batch_upload_storage.py, tests/unit/test_merge_validation.py) are ModuleNotFoundError: No module named 'models.client_processing' in files this PR doesn't touch, and the identical failure reproduces at this PR's exact base commit 09ff17e4e5 on main (fixed on main later that day). It's inherited base breakage, not this diff; merging current main will clear it.

Two non-blocking notes:

  • The deferred .select() projection + per-page id hydration (the updated_desc metadata-window pattern) remains a worthwhile follow-up; with the page-floored budget the residual exposure is dense-hidden-row scans only.
  • A page that exhausts the full needed + slack budget mid-hidden-run still reads as EOF to callers. Bounded scans can't fully avoid that edge; a log line at budget exhaustion would make it observable in production.

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 need human response.

@Git-on-my-level Git-on-my-level removed needs-tests PR introduces logic that should be covered by tests needs-maintainer-review Needs a human maintainer to sign off before merge labels Sep 6, 2026
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.
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed a2b503a — merged current main, and took your second non-blocking note.

The red check. Merged main, which carries #12785. Your diagnosis was exactly right: both failures were ModuleNotFoundError: No module named 'models.client_processing' in test_batch_upload_storage.py and test_merge_validation.py, neither of which this PR touches, reproducing at this PR's base commit and fixed on main later that day. Nothing in the diff needed to change for it.

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: test_a_page_that_dies_on_the_budget_says_so and test_a_page_that_simply_ran_out_of_rows_stays_quiet. Mutation-checked — making the condition unconditional fails the quiet test; downgrading the log fails the loud one.

Left the deferred .select() projection alone. It's a real improvement but it's a different change from a pagination fix, and with the page-floored budget the residual exposure is dense-hidden-row scans only, as you said.

Verification: test_get_memories_scoring_visibility_pagination.py 9 passed. test_desktop_backend_parity.py 8 passed — worth noting that main's version of that file fails 1 of those same 8, and this PR's pin update is what fixes it. PR preflight passed: 28 checks.

One thing I found while verifying, not a blocker and not from this diff: running the parity contract and tests/unit/test_batch_upload_storage.py in the same pytest process errors all 27 of the latter with AttributeError: <module 'utils.other.storage'> has no attribute 'storage_client'. It reproduces with main's copy of the contract file, so it is pre-existing, and CI never sees it because contracts and unit run as separate jobs. It is the same shape as #12779 though — a suite that stubs a module and leaks — so it is a latent trap worth an issue if you agree.

@kodjima33 kodjima33 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.

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.

@kodjima33
kodjima33 merged commit 0e92583 into BasedHardware:main Sep 6, 2026
32 checks passed
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Sep 6, 2026
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.
undivisible pushed a commit that referenced this pull request Sep 7, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: memory scoring_desc list pages shrink when rejected/invalid rows sit in the raw Firestore page

3 participants