Skip to content

fix(backend): fill chat message pages past reported rows - #12712

Merged
undivisible merged 3 commits into
BasedHardware:mainfrom
aryanorastar:fix/chat-message-reported-pagination
Sep 5, 2026
Merged

undivisible merged 3 commits into
BasedHardware:mainfrom
aryanorastar:fix/chat-message-reported-pagination

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #12709.

Summary

get_messages applied Firestore .limit().offset() before filtering reported is True in 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 offset visible rows are skipped and limit visible rows are collected, with a bounded scan so one request cannot stream unbounded history.

Change

  • backend/database/chat.py — get_messages visible-page scan instead of raw limit/offset-then-filter
  • backend/tests/unit/test_get_messages_reported_pagination.py — behavioral coverage
  • .github/failure-classes/FC-raw-page-limit-before-visibility-filter.json — new failure class

No router / client API shape change. get_app_messages (no offset) and get_cache_aligned_messages (already over-fetches) are left alone.

How the scan is bounded

A page with no reported rows needs exactly offset + limit documents — 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:

needed = max(offset, 0) + max(limit, 0)
scan_budget = needed + min(CHAT_MESSAGES_VISIBLE_PAGE_SCAN_SLACK, needed * 3)

Two consequences worth stating, because the first version of this PR got both wrong:

  • The scan can never read fewer documents than the query it replaced, so it can never fail to service an offset that used to work.
  • Slack is paid only by a page that actually meets a reported row. The first batch reads exactly 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 flat min(100, budget), so a page needing 5 rows streamed 100 documents. backend/utils/chat.py reads history at limit=5/10/15 on the chat-send path, so every send paid ~20x the documents it used to. Fixed by reading exactly needed on the first batch.

Deep-offset truncation (cubic P2, and Git-on-my-level's second tradeoff). Capping the total scan at 1000 meant offset + limit beyond the cap could never be reached, so the page came back empty — and routers/chat.py reads 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/messages is 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:

E       assert collection.streamed == 5
E       assert 100 == 5
E       AssertionError: assert [] == ['visible-1200', ...]
E         Right contains 5 more items, first extra item: 'visible-1200'
2 failed, 3 passed

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 passed
  • pytest tests/unit/test_desktop_migration.py -k MessageReconcileKeyset — 3 passed

Five 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; the test_client_processing_trust_boundary.py failure kodjima33 correctly diagnosed as stale-base was repaired on main in #12729 and is gone from this head.

Honest gaps

  • No live Firestore / emulator integration run (the hermetic fake mirrors offset/limit/start_after including keyset resume).
  • Physical device smoke not run — backend-only change, no device path involved.

Failure-Class: new

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

All reported issues were addressed across 3 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/database/chat.py Resolved
Comment thread backend/database/chat.py Resolved
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @aryanorastar — this fixes a real pagination bug and follows the pattern this codebase already established for the same failure class.

What I verified:

  • backend/database/chat.py — get_messages now scans the newest-first stream with a bounded budget (min(1000, max(100, (offset+limit)*4)), 100-doc batches, start_after cursor) and counts offset/limit in visible rows, mirroring get_messages_reconcile_page. The cursor advances per document, reported rows don't consume page capacity, and short-batch EOF terminates the scan. Offset semantics stay coherent for clients: page N at offset = N*L continues at the exact next visible row, and get_cache_aligned_messages' delegate-then-slice still holds since it calls with offset=0.
  • backend/tests/unit/test_get_messages_reported_pagination.py — both tests fail on main's limit-then-filter path and pass with the fix (ran them locally on this head). The fake mirrors Firestore offset/limit/start_after semantics, including keyset resume.
  • .github/failure-classes/FC-raw-page-limit-before-visibility-filter.json — matches the existing FC schema exactly (same keys as the other 192 entries) and points at the new test as the canonical prevention artifact.

Two tradeoffs worth a maintainer eye (neither blocking from my side):

  1. Read amplification on hot paths: the max(100, …) budget floor means internal calls with small limits (backend/utils/chat.py prev-message reads with limit=5/10/15, and get_cache_aligned_messages' over-fetch) now stream a 100-doc first batch where they previously read exactly limit docs. Firestore bills streamed documents, so the chat-send path reads ~20× more docs per send. If that matters operationally, a smaller first batch (sized to limit + reported slack, then 100s) would keep the fix without the floor cost.
  2. Deep-offset truncation: offset + limit beyond the 1000-doc budget now returns a short/empty page (e.g. deep /v2/messages offsets) where main would have returned the correct page — the same bounded-scan tradeoff get_messages_reconcile_page makes, but offset callers have no cursor to resume with. For the pagination depths clients actually use this looks fine; noting it so it lands as a conscious choice.

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

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution 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

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

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.

aryanorastar and others added 2 commits September 4, 2026 20:27
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]>
@aryanorastar
aryanorastar force-pushed the fix/chat-message-reported-pagination branch from 58ac12a to 6721a84 Compare September 4, 2026 15:11
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed 6721a84e2a. Both review findings were real and are fixed; the branch is also rebased onto current main (176a02fe0d).

Read amplification. The budget floored at max(100, …) and the first batch was a flat min(100, budget), so a page needing 5 rows streamed 100 documents. backend/utils/chat.py reads history at limit=5/10/15 on every chat send, so that path was paying ~20x the documents it used to.

Deep-offset truncation. This one was the more serious of the two: capping the total scan at 1000 meant offset + limit past the cap could never be reached, the page came back empty, and routers/chat.py reads an empty page as end-of-results. That is the exact "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.

Both have the same root, and fixing the framing fixes both rather than patching them separately. A page with no reported rows needs exactly offset + limit documents, which is precisely what the old raw query streamed. So the budget floors at the page and bounds only the slack above it:

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 needed, so slack is paid only by a page that actually meets a reported row.

Mutation-checked — with the old capped budget and flat first batch restored:

E       assert collection.streamed == 5
E       assert 100 == 5
E       AssertionError: assert [] == ['visible-1200', ...]
2 failed, 3 passed

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; MessageReconcileKeyset still 3 passed.

On the suggested has_more / resume signal — I did not add one. It changes 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 prevent the EOF masquerade, since an offset that used to be serviceable still is. A cursor for /v2/messages is worth doing on its own rather than inside a pagination bug fix.

The test_client_processing_trust_boundary.py failure was diagnosed correctly as stale base — it was repaired on main in #12740 / #12729 and is gone from this head after the rebase.

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]>
@undivisible
undivisible merged commit 09ff17e into BasedHardware:main Sep 5, 2026
30 checks passed
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Sep 5, 2026
…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]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Sep 5, 2026
…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).
kodjima33 pushed a commit that referenced this pull request Sep 6, 2026
* 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]>
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) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Chat message pagination drops visible rows when reported messages sit in the Firestore page

4 participants