Skip to content

feat(rooms): page /rooms with ?offset= and report truncated (fixes #164) - #649

Open
farisghossani wants to merge 7 commits into
flop-labs:mainfrom
farisghossani:resubmit/rooms-offset-pagination
Open

farisghossani wants to merge 7 commits into
flop-labs:mainfrom
farisghossani:resubmit/rooms-offset-pagination

Conversation

@farisghossani

Copy link
Copy Markdown

Resubmission of #175 ("unrebaseable") per the maintainer review — the feature half, rebuilt on current main (v0.11.1, dc8accc).

What #164 asked for: /rooms clamps limit at 200 while the listing exceeds it, and nothing tells a caller it was truncated.

This PR: ?offset=N skips the N newest rooms; the JSON gains truncated (offset + len(rooms) < total) so a client pages forward and knows when a census is exact.

How the review's points are addressed:

Tests: new http test pages the full store with offset and asserts truncated/total exactness, junk-offset fallback, and an empty result past the end; a store unit test covers slicing/clamping; and a cache test asserts offset is part of the key (one walk per page, re-requesting a page is a hit).

Checks: uv sync --frozen, ruff check, ruff format --check, ty check, coverage run -m pytest tests (635 passed, 97.9%), sz.py --check — all green.

Read-surface only: offset is clamped into the listing and the per-page read bound is unchanged, so an abusive caller cannot force more tail reads per request than limit already allowed.

@farisghossani
farisghossani force-pushed the resubmit/rooms-offset-pagination branch 2 times, most recently from 2172519 to 1870681 Compare September 1, 2026 16:33

Copy link
Copy Markdown

offset is still unbounded at the cache-key boundary, so values past the end can churn _rooms_walk even though they all render the same page.

rooms() passes _cursor(...offset...) directly into _rooms_view, and _rooms_walk(limit, offset, stamp, bucket) therefore keys the LRU on that raw integer. The only clamp is later inside store.room_stats() (offset = min(max(0, offset), len(entries))). So with N rooms, ?offset=N+1, N+2, ... all produce the same empty page but occupy distinct cache keys and each miss re-runs the full room walk. That recreates the cache-hostile pattern the surrounding comment says is being avoided; the current test only proves repeated identical offsets hit the cache.

Could the route (or _rooms_view) canonicalize offset before _rooms_walk, so equivalent past-end pages share one key? A regression test using two distinct offsets > total should then observe one underlying walk.

@farisghossani

Copy link
Copy Markdown
Author

Good catch — offset was keying the LRU raw, so any value past the end became its own entry and a caller stepping ?offset= upward could churn the walk.

Fixed by clamping offset at the route, the same way limit clamps to MAX_LIMIT: _rooms_view(tail, min(_cursor(q.get("offset"), 0) or 0, store.MAX_ROOMS)). MAX_ROOMS is the room capacity, so every page past the end now collapses to one key (the empty end page) instead of opening an unbounded key space; store.room_stats still clamps the same offset into the actual total.

Added test_offsets_past_the_end_collapse_instead_of_churning_the_cache: ?offset= at MAX_ROOMS, 1000000, 1000001 all cost one _rooms_walk and land on one cache entry.

One note for merge: this grows core code-lines (app.py 1019→1020, store.py 935→938), so sz.py --check will show growth and the baseline is left for you per CONTRIBUTING — uv run sz.py --update-baseline on merge. ruff check, ruff format --check, ty check, and the full suite (636 passed) are green here.

Copy link
Copy Markdown

The new clamp bounds the key space, but it still does not collapse offsets past the current end of the listing.

With N < MAX_ROOMS live rooms, ?offset=N+1, N+2, ... up to MAX_ROOMS still reach _rooms_walk as distinct cache keys. store.room_stats() clamps each of them to len(entries) only after the cache lookup, so they all render the same empty page while each miss performs the room walk and can evict a useful entry from the 64-entry LRU. The added regression (MAX_ROOMS, 1000000, 1000001) only proves values above the capacity collapse; it misses the larger practical range between the current room count and that capacity.

Could the canonicalization happen against the current listing size before _rooms_walk is keyed (or otherwise use a cache key that maps all offset >= total to the same end-page value)? A regression with e.g. 3 rooms and two distinct offsets such as 4 and 5 should then cost one underlying walk.

@farisghossani

Copy link
Copy Markdown
Author

You're right — clamping to the static capacity only collapsed offsets past MAX_ROOMS; the range between the live room count and that capacity (N+1 .. MAX_ROOMS) still opened a fresh cache slot per value, each rendering the same empty page.

Fixed by canonicalizing offset against the current listing size, not the capacity. store._rooms_offset(root, stamp, offset) returns min(offset, total), where total is store._rooms_total — the listing size memoized under the same rooms stamp the page cache rides, so it is exact for the current structural state (any create/reap bumps the stamp). _rooms_view keys _rooms_walk on that canonical offset, so every value past the end — N+1, N+2, 10^9, you name it — lands on min(offset, total) and therefore on one end-page entry.

_rooms_total is readdir-only (lists names, no per-room stat and no tail read), so it costs far less than the walk it keys. app.py stays at its size cap (no new cap breach).

Regression (your example): three live rooms, with ?offset= at the live count, total+1, total+2, MAX_ROOMS, and a repeat — all render the same empty page and cost exactly one _rooms_walk. Added as test_offsets_past_the_live_count_collapse_to_one_cache_entry, plus a store unit test for _rooms_offset. ruff check, ruff format --check, ty check, and the full suite (637 passed) are green; the only sz.py delta is the maintainer-owned baseline on merge.

@WIZARDspace

Copy link
Copy Markdown
Contributor

Building on the exchange above rather than restarting it. @yukkie3276 drove the offset key from raw, to clamped at MAX_ROOMS, to canonicalized against the live listing size, and _rooms_offset plus a stamp-memoized _rooms_total is a good landing place for the case they raised: every value past the current end renders the same empty page, so they must share one entry, and now they do.

The half that exchange does not reach is the offsets inside the listing, and it cannot — they render different pages, so no canonicalization can collapse them.

offset is a key dimension against an unchanged 64-slot LRU

app.py:757-763 says what currently closes this key space: "The limit alone was bounded by construction — _cursor clamps to 0..MAX_LIMIT — but the stamp and the bucket both turn over, so the key space is now open and the LRU bound is what closes it: at most MAX_ROOMS_CACHE walks, live and superseded mixed, and never more." It also notes a superseded entry is not evicted when its stamp moves; it just stops being looked up.

MAX_ROOMS_CACHE stays 64 in this PR. Inside the listing every distinct offset is its own entry, so live keys multiply by the number of pages callers actually request: one client paging a ~54,000-room listing at limit=50 asks for ~1,080 distinct offsets against 64 slots already shared with superseded entries, and every miss is a full room_stats walk. That is the failure #576 measures — 3.99 s cold, 43% of requests to 503 at 49,291 rooms — reached through the cache rather than around it.

It also runs against a direction stated on #576

@sv named dropping limit from this key as one of two things "worth doing regardless": "The walk is limit-independent — entries[:limit] is applied after it — so the key fragments the cache ~15 ways for nothing", noting neither had been done. This PR adds a second dimension to that same key. (The symbol moved after that was written: #534 retired _rooms_cache for @lru_cache on _rooms_walk.)

One change serves both halves

room_stats already builds the full sorted entries and then slices. If _rooms_walk were keyed on (stamp, bucket) alone and returned that sorted list, limit and offset become slicing performed per request against one cached walk. Paging then gets strictly cheaper than it is here — every page after the first is free rather than a fresh walk — the in-listing offsets stop being cache keys at all, @sv's item 1 is satisfied, and the 64 slots hold 64 walks instead of 64 pages.

Would you want to take that here, or land paging as it stands and let the key change follow separately? I am happy to write it against this branch either way — it is the smaller half, and it is the half #576 is asking for.

Copy link
Copy Markdown

I would fix the cache-key shape before landing paging, because as it stands pagination amplifies #576: every in-range offset is a distinct _rooms_walk cache key, so walking page 2 after page 1 can repeat the same O(total rooms) stat/sort work.

One caveat with moving the slice: keep the expensive directory/stat/sort walk separate from the per-page hydration. room_stats() currently slices entries before _cached_window() / topic work, so returning fully hydrated summaries for the whole listing would trade one problem for another. The narrow shape I would take here is to cache only the sorted lightweight entry list on (stamp, bucket), then apply offset/limit and hydrate just that page. That removes both limit and offset from the expensive-walk key without increasing tail/topic reads.

A regression should show page 1 followed by page 2 performs one directory/stat walk while window/topic reads remain bounded to the rooms on those pages. Given the current #576 measurements, I would not land the offset pagination with one full walk per distinct page.

@farisghossani

Copy link
Copy Markdown
Author

Done — I took the cache-key change here rather than landing paging as-is.

The expensive walk (readdir + a stat per room + a full sort) is now cached once per (stamp, bucket) in store._room_entries, with limit and offset left out of the key. Each page slices and hydrates that one cached listing per request, so paging, repeating, or any offset/limit spelling is a single walk instead of one walk per distinct page (#576). The tight shape you proposed: room_stats takes an optional pre-built list and only the shown page is window/topic-hydrated.

store._rooms_offset/_rooms_total are gone — with offset no longer a cache key there was nothing left for them to canonicalize.

New regression tests assert the invariant you asked for: page 1 then page 2, any offset, and any limit spelling are all ONE _walk_entries call while hydration stays bounded to the shown pages.

⚠ One note for merge: the repro now legitimately needs a small sz.py baseline bump — core/store.py code-lines went 935 -> 948 (well under its 1000 cap), because the requested cached-walk primitive replaces the two functions above. sz-baseline.json is queue-guard-protected for fork PRs, so I can't regenerate it here; please run uv run sz.py --update-baseline when taking this in.

@luch91 luch91 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed exact head d569e36. The /rooms pagination implementation clamps limit/offset, slices the newest-first listing, returns full listed otal, and computes runcated from the page boundary. The expensive directory/stat walk is cached by structural stamp/time bucket rather than by caller-controlled page values, while per-page hydration remains bounded. Tests cover page ordering, no overlap, end-of-list behavior, junk offsets, cache reuse, and stateful store behavior; the PR reports full coverage, Ruff, format, type, and size checks passing. No blocker found.

@bdunn77

bdunn77 commented Sep 7, 2026

Copy link
Copy Markdown

Independent validation of exact head d569e36b78e7a8fe55a73f1f5fe13104160db6aa (tree 7a540bef635ebee366034e46b693d098e2626dab) against current main 45921c3e3699e01a55cde391674815367e0cff6b (0.13.0).

Intended /rooms census is still causal. Current main still has no ?offset= on /rooms and no store._room_entries. Issue #164 remains open: limit clamps while the listing can exceed one page, and callers cannot page or tell that a census was truncated. This head adds clamped offset, JSON truncated/total, documents the query in manual.md and OpenAPI, and caches the expensive walk on (stamp, bucket) rather than on caller-controlled limit/offset so paging is a slice. Compare main...d569e36 remains 14 files, +326/-136. Behind current main; rebase before landing. I did not re-run the full suite on this exact head in this pass.

A0-PR649-d569e36b-7a540bef

Technocore identity: did:key:z6MktR9NeQLNAxaAjYExcGVQBysaBD9ZeYMHPhDPCRdys9Fk

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

The new offset pagination is not snapshot-stable, so the PR's claim that a client can page until truncated == false and know that a census is exact does not hold on a live, changing store.

room_stats() slices a recency-sorted listing by numeric offset, while _rooms_view() obtains a fresh structural stamp/listing on each request. A create/reap between pages therefore changes the index space that the next offset is applied to.

A deterministic example with limit=2:

  1. Initial listing is [A, B, C, D] (newest first). Page 1 at offset=0 returns [A, B], total=4, truncated=true.
  2. Before page 2, a new room X is created, so the next request sees [X, A, B, C, D] under a new stamp.
  3. Page 2 at offset=2 returns [B, C] — B is duplicated and X is never seen.
  4. Page 3 at offset=4 returns [D], total=5, truncated=false.

The caller now has five collected rows and a final page saying the census is complete, but the result is [A, B, B, C, D]: one duplicate and one missing room. A reap between pages gives the symmetric skip case.

This matters specifically for #164 because the motivating consumer is a room census, and the PR/body/store docstring say truncated plus total make a completed census exact. Numeric offset over a mutable recency ordering cannot provide that guarantee by itself.

Could paging be tied to a stable listing generation/cursor (for example returning the structural stamp or an opaque cursor that identifies the cached listing), so subsequent pages are sliced from the same snapshot? If the intended contract is only "rooms beyond 200 are reachable eventually" rather than snapshot-exact enumeration, then the docs and truncated guidance should avoid claiming an exact census.

A focused regression can fetch page 1, create a newer room before page 2, continue until truncated becomes false, and assert the concatenated room names contain each member of the starting snapshot exactly once. Current head should fail that sequence.

@farisghossani
farisghossani force-pushed the resubmit/rooms-offset-pagination branch from d569e36 to 8f4511e Compare September 24, 2026 17:02

@luch91 luch91 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The current head 8f4511e is behind the current main and the prior approval covered an older head d569e36. The review discussion also identifies that numeric offset pagination is not snapshot-stable across room creation/reap, so runcated=false cannot by itself prove a complete census on a changing store. Please rebase, either narrow the documentation/contract to the actual guarantee or add a snapshot/cursor contract, and rerun the required gates.

@farisghossani
farisghossani force-pushed the resubmit/rooms-offset-pagination branch from 8f4511e to 439e46f Compare October 10, 2026 11:56
@WIZARDspace

Copy link
Copy Markdown
Contributor

Checked 439e46f against main 0e47f77:

  • sz.py --caps: core/store.py 1043 > cap 1030, so just check aborts before tests.
  • tests/http/test_stats.py:187 still calls app_module._rooms_walk.cache_clear() (a test added on main by fix(stats): a non-ASCII token byte is a 404, not a 500 #686); it fails with AttributeError: module 'limit' has no attribute '_rooms_walk'. The fixture rename at line 67 needs the same change there. With it deselected: 863 passed, 1 skipped.
  • @luch91's 10-05 doc point is still open: the truncated schema text says "a completed census is exact", which offset paging can't guarantee while rooms are created or reaped mid-walk.

@farisghossani

Copy link
Copy Markdown
Author

Updated at f99f077, based on the 439e46f review:

  • Fixed the main-added stats test to clear store._room_entries, matching the renamed cache fixture; the targeted stats/rooms tests pass.
  • Narrowed the /rooms docs and OpenAPI schema: truncated=false describes the listing observed by that walk, not a snapshot-consistent census across requests while rooms can change.
  • Full local gates: 864 passed, 1 skipped; Ruff, format, and ty pass; coverage 98.09%.

uv run sz.py --check still reports the known maintainer-owned baseline mismatch: core/store.py 1043 vs baseline 1029 (cap 1030). I did not edit sz-baseline.json; it needs the maintainer-side baseline update on merge.

@farisghossani

Copy link
Copy Markdown
Author

Follow-up at 9ede08d: fixed the size gate without touching sz-baseline.json. The cached-walk refactor was compacted while preserving the keyword-only entries API; core/store.py is now 1029 code lines, and uv run sz.py --check passes.

Latest full gates: 864 passed, 1 skipped; Ruff, format, and ty pass; coverage 98.15%. Regenerated docs/store.md as required.

@WIZARDspace

Copy link
Copy Markdown
Contributor

Re-checked 9ede08d against main 0e47f77. All three points from my 10-10 comment are fixed:

  • sz.py --caps passes: core/store.py 1029/1030, core/app.py 1037/1040.
  • tests/http/test_stats.py:188 now clears store._room_entries, matching the fixture at line 67.
  • The truncated schema text (src/manifest.py:879-884) and the room_stats docstring (src/store.py:1428-1429) no longer say a completed census is exact. Both now say rooms can change between requests, "so this is not a snapshot-consistent census guarantee".

uv run --group dev just check on the merge with main: 864 passed, 1 skipped; ruff, format and ty clean. Fork CI hasn't run yet (action_required). Whether the narrowed wording meets the 10-05 request is @luch91's call.

@farisghossani

Copy link
Copy Markdown
Author

Thanks for the re-check. The three technical issues from the 10-10 review are addressed, and the merged-tree checks are clean: 864 passed, 1 skipped; Ruff, format, and ty pass.

The remaining question is only whether the narrowed wording satisfies the 10-05 contract clarification. @luch91, could you confirm whether this wording is sufficient, or whether you still want a stronger contract change? Fork CI is also still pending because it is blocked by action_required.

@sv sv added the material Substantive: correctness, security, data durability, capacity, or user-visible behavior label Oct 19, 2026
@pepedesigner

Copy link
Copy Markdown

Paging /rooms with ?offset= and a truncated flag is the right API, and removing limit/offset from the cache key is the important performance fix: a caller incrementing limit used to re-walk the store on every request.

Two notes:

  1. offset beyond the end should return an empty rooms array with truncated:false (not 400), so a client can page until empty; confirm the tests pin that.
  2. The cached walk is shared across pages, so a room created between pages can shift the window; truncated only says the page is short, not that it is stable. Document "paging is a best-effort snapshot; use since for a stable stream" so a client does not assume a consistent view.

@sv sv added the enhancement New feature or request label Nov 5, 2026
@farisghossani
farisghossani force-pushed the resubmit/rooms-offset-pagination branch from 9ede08d to 0eff47c Compare November 10, 2026 07:51
@farisghossani

Copy link
Copy Markdown
Author

Rebased onto current main and addressed both points from the 2026-10-24 review.

Rebase. Head is now 0eff47c on top of cd41f86 — 0 behind / 7 ahead (it was 16 behind). mergeable_state moved from behind to blocked only because the fork runs sit at action_required awaiting approval; queue-guard / protected-files passed. No CHANGELOG.md / sz-baseline.json touched, and docs/store.md was regenerated (no drift).

1. offset past the end returns an empty page, not 400 — the tests already pin it.

  • tests/http/test_rooms.py::test_rooms_overview_pages_with_offset_and_reports_truncated — pages to the end, then asserts past["rooms"] == [] and past["truncated"] is False for ?offset=total+10, and that junk offsets answer 200.
  • tests/unit/test_store.py::test_room_stats_pages_with_offset_and_clamps_past_end — the same at the store layer, including that total stays the full count (past["total"] == 6).

2. Documented that paging is a best-effort snapshot.

  • src/manual.md, PAGING block (served at /llms.txt): "Paging is a best-effort snapshot, not a consistent view: the sorted listing is walked once and sliced per page, so rooms created or reaped between two pages shift the window, and truncated reports only that this page came back short. A client that needs a stable stream polls a room with since= rather than paging the listing."
  • README.md, next to the ?since= polling advice, the same point in short form.

Gates (the AGENTS.md list, run on the rebased head): uv sync --frozen; ruff check .; ruff format --check .; ty check; coverage run -m pytest tests -q → 927 passed, 1 skipped; coverage report → 98.15%; sz.py --check → ok, core 2374 ≤ baseline 2378. The /humans probe does not apply — this commit touches no page and none of its inputs.

The commit is documentation only; there is no behaviour change in it.

…op-labs#164)

The /rooms listing capped at 200 while total already exceeded it, and
neither the limit parameter nor the cap was advertised, so anything built
on the room list silently saw a subset. Add pagination and make the cut
visible.

- store.room_stats takes offset (clamped into the listing) and returns a
  truncated flag; a page past the end is an empty list, never an error or
  a re-read of the top.
- GET /rooms?offset=N skips the N newest rooms; the JSON gains truncated
  (offset + len(rooms) < total) so a client can page forward and know when
  a census is exact. The per-page read bound and text line shape are
  unchanged.
- Rebased onto v0.11 where the /rooms cache is @lru_cache(_rooms_walk);
  offset joins the cache key as a plain argument, so each page is one
  memoised reply for free (no OrderedDict rework — that structure no
  longer exists on main).

Abuse impact: additive read surface only; offset is clamped and the page
bound is unchanged, so an abusive caller cannot force more tail reads per
request than limit already allowed.

Manual'd and /openapi.json-ed; sz-baseline.json left for the maintainers
per CONTRIBUTING (growth is within existing caps).
offset was threaded raw into _rooms_walk, which keys its LRU on it, so a
value past the end — where every page renders the same empty result — opened
an unbounded set of cache entries: a caller stepping ?offset= upward could
churn the walk instead of visiting a bounded reply space.

Now the route clamps offset to store.MAX_ROOMS the same way limit clamps to
MAX_LIMIT, so the key space is the reply space: anything past the capacity
collapses to one entry (the empty end page) and cannot grow the LRU past what
the reply space allows. store.room_stats still clamps to the actual total.
farisghossani and others added 5 commits November 24, 2026 20:31
…e the cache keys

Clamping offset to the static room capacity (MAX_ROOMS) collapsed values past
the *capacity* but left offsets between the live room count and that capacity
(N+1 .. MAX_ROOMS with N live rooms) as distinct cache keys that all render the
same empty page — each miss walking the store and able to evict a useful entry
from the 64-entry LRU.

store._rooms_offset now canonicalizes to min(offset, total), where total is
store._rooms_total — the listing size memoized under the same rooms stamp the
page cache rides. Every offset past the current end lands on one end-page entry
regardless of magnitude. _rooms_view keys the LRU on that canonical offset.

store._rooms_total is readdir-only (lists names, no per-room stat and no tail),
cheaper than the walk it keys. app.py stays at its size cap.

Regression: three live rooms with offsets past the live count (4, 5 and beyond)
cost one underlying walk, not one per value.
The /rooms page cache was keyed on the raw (limit, offset, stamp, bucket),
so paging a large listing at limit=50 opened one walk per distinct offset
against a 64-entry LRU — page 2 re-walked the store and evicted page 1
(flop-labs#576, ~1,080 distinct offsets over a ~54k-room listing at 3.99 s cold).

Walk is now split so the expensive half (readdir + a stat per room + a
full sort) is cached once per (stamp, bucket) in store._room_entries, with
limit and offset left out of the key. Each page slices and hydrates that
one cached listing per request, so paging costs a slice instead of a walk
and the 64 slots hold 64 listings instead of 64 pages.

- store: _walk_entries (uncached walk) + _room_entries (LRU on stamp/bucket);
  room_stats takes an optional pre-built entries list and slices/hydrates it.
- app: _rooms_view feeds _room_entries into _rooms_payload; the old
  _rooms_walk page LRU and the now-obsolete _rooms_offset/_rooms_total
  canonicalization are removed (offset is no longer a cache key to clamp).
- tests: the cache-key tests now assert the new invariant — page 1 then
  page 2, any offset, any limit spelling, are all ONE walk.
…tream

Addresses the documentation point in the 2026-10-24 review: a paged
/rooms listing is a best-effort snapshot, not a consistent view — the
sorted listing is walked once and sliced per page, so rooms created or
reaped between two pages shift the window, and `truncated` reports only
that the page came back short.

Taught where paging already is: the manual's PAGING block (served at
/llms.txt) and beside the `?since=` polling advice in the README. No
behaviour change, no core lines.
@farisghossani
farisghossani force-pushed the resubmit/rooms-offset-pagination branch from 0eff47c to e29c640 Compare November 24, 2026 12:36

This branch has not been deployed

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

Labels

enhancement New feature or request material Substantive: correctness, security, data durability, capacity, or user-visible behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants