[BUG] JSONLStorage.query() pages before it sorts, so a jsonl store returns the OLDEST rows while sqlite returns the NEWEST
Description
JSONLStorage.query() applies limit and offset while reading the file, and only sorts afterwards — so a jsonl:// store returns the oldest rows for a paged query, while sqlite:// (the default) returns the newest. The two built-in backends implement the same Storage.query() contract and disagree on which records a page contains.
The paging happens in file order (iter_all() yields append order), and the break at len(results) >= limit fires long before the rest of the file is read:
# headroom/storage/jsonl.py:108-131
for metrics in self.iter_all():
...filters...
# Handle offset
if skipped < offset:
skipped += 1
continue
results.append(metrics)
# Handle limit
if len(results) >= limit:
break
# Sort by timestamp descending
results.sort(key=lambda m: m.timestamp, reverse=True)The # Sort by timestamp descending comment states the intent; the sort only ever reorders the already-truncated page.
SQLiteStorage.query() does the opposite order — ORDER BY timestamp DESC LIMIT ? OFFSET ? (headroom/storage/sqlite.py:157-176) — i.e. it sorts over the whole filtered set and then pages.
To Reproduce
No install beyond the package, no provider, no network, no credentials. Save the same 250 requests oldest-first into each backend and ask each for the first page of 5:
from datetime import datetime, timedelta, timezone
from headroom.config import RequestMetrics
from headroom.storage import create_storage
BASE = datetime(2026, 9, 20, tzinfo=timezone.utc)
def m(i):
return RequestMetrics(
request_id=f"req-{i:03d}", timestamp=BASE + timedelta(minutes=i),
model="gpt-4o", stream=False, mode="optimize",
tokens_input_before=1000 + i, tokens_input_after=500 + i, tokens_output=10)
for url in ("sqlite:///tmp/w.db", "jsonl:///tmp/w.jsonl"):
s = create_storage(url)
for i in range(250): # natural append order: oldest first
s.save(m(i))
print(url.split(":///")[0], [x.request_id for x in s.query(limit=5)])
print(" page 2:", [x.request_id for x in s.query(limit=5, offset=5)])Expected Behavior
Both backends return the 5 newest requests, newest first, and offset=5 continues from there — that is what the SQLite backend does and what "sort by timestamp descending, then page" means.
Actual Behavior
sqlite query(limit=5) -> ['req-249', 'req-248', 'req-247', 'req-246', 'req-245']
query(limit=5, offset=5) -> ['req-244', 'req-243', 'req-242', 'req-241', 'req-240']
jsonl query(limit=5) -> ['req-004', 'req-003', 'req-002', 'req-001', 'req-000']
query(limit=5, offset=5) -> ['req-009', 'req-008', 'req-007', 'req-006', 'req-005']query(limit=5) on the JSONL store returns the five oldest requests in the file, each backend's page-2 containing rows the other never shows.
The smaller the page relative to the store, the worse the mismatch: the default limit=100 means HeadroomClient.get_metrics() on a jsonl:// store reports the first 100 requests ever recorded and silently omits everything since.
Why the existing suite does not catch it
tests/test_storage_backends.py exercises both backends with fixtures of three records, where paging-before-sorting is invisible for most call shapes — and the one assertion that does page encodes the buggy order as the expectation. Run against the repo's own three-record fixture (one @ now−2 h, two @ now−1 h, three @ now), identical rows in both stores:
| call | sqlite:// |
jsonl:// |
|---|---|---|
query(start_time=now-1h30m, offset=1, limit=1) |
['two'] |
['three'] |
query(start_time=now-1h30m, offset=1, limit=2) |
['two'] |
['three'] |
query(offset=1, limit=2) |
['two', 'one'] |
['three', 'two'] |
tests/test_storage_backends.py:162-163 asserts the JSONL row of that table (["three"]), while tests/test_storage_backends.py:241-242 asserts a SQLite page whose result is only correct under sort-before-page. The suite pins each backend's current behaviour, so it documents the divergence instead of failing on it.
Suggested fix
Order before paging: collect the filtered records, sort descending, then slice [offset : offset + limit]. For an append-only log a full scan is unavoidable if the page must be the newest one, so the current early break cannot be kept as an optimisation — heapq could bound memory if a large store makes that a concern. This makes query() on a JSONL store mean what it means on the default SQLite store; the JSONL assertion above would move from ["three"] to ["two"].
Environment
- Headroom version: 0.39.2-dev (source tree at
d13e196, the commit that shipped as 0.39.1) - Python version: 3.14.4
- OS: macOS 27 arm64
- LLM Provider: none — nothing here reaches a provider
Additional Context
- Not tested: performance on a multi-gigabyte JSONL store (the fix makes
query()scan the whole file, which I have not measured); whether any external tool depends on the current oldest-first page; Windows paths (the file-URI handling there is separate and already covered by the merged #3475). - Related in spirit only: #3820 is a different storage/reporting value bug; #3116 changes how timestamps are serialised, which would affect string ordering in the SQLite backend but not the order-of-operations problem here — this reproduction uses real
datetimecomparisons on the JSONL side and never touches the serialised form. - I'm going to open the PR for this.
Source: headroomlabs-ai/headroom