Skip to content

fix(store): clamp since past head to the real head in read_messages - #585

Merged
sv merged 5 commits into
flop-labs:mainfrom
Sertug17:fix/since-past-head-565
Sep 24, 2026
Merged

sv merged 5 commits into
flop-labs:mainfrom
Sertug17:fix/since-past-head-565

Conversation

@Sertug17

@Sertug17 Sertug17 commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #565.

A ?since= cursor past the room's head was echoed back as last_seq, causing the text lane's next: line to print a dead cursor. Agents following that line poll forever.

Fix: track the room's real head during the reverse scan and clamp last_seq to min(since, head_seq) when no messages match. Normal polling is unchanged when out is non-empty, out[-1]["seq"] is still used.

Verified against 019b57a.

Copy link
Copy Markdown

Current head a963692 contains unrelated inserted head_seq blocks outside read_messages that make src/store.py invalid at runtime. In room_window, _stillborn, _sweep_orphan_locks, and _reap, the added code references head_seq without defining it; several sites also reference rec where no rec exists in that scope. For example, _sweep_orphan_locks now executes if not head_seq: head_seq = rec["seq"] immediately before unlinking an orphan lock, so that path raises UnboundLocalError instead of sweeping it. The intended read_messages clamp is narrowly scoped; these extra insertions appear accidental and should be removed before merge.

@Sertug17
Sertug17 force-pushed the fix/since-past-head-565 branch from a963692 to f39e374 Compare August 30, 2026 19:21
@Sertug17

Copy link
Copy Markdown
Contributor Author

Fixed in f39e374 the original sed matched every continue in the file, not just the one inside read_messages. Rewrote with a targeted Python edit; head_seq now appears only in read_messages (4 lines, verified with grep -n head_seq src/store.py). Thanks for catching it. @yukkie3276

@Elfet

Elfet commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Applied f39e374's four lines onto main at 248bcf3 and ran it, since the diff is small enough
that what matters is the boundaries and the CI it has to pass. The logic holds; three things stand
between it and green.

The boundaries, measured

Direct store.read_messages calls on a scratch root:

room state call count last_seq
3 messages since=999 0 3 (was 999)
3 messages since=3 (== head) 0 3
3 messages since=1 2 3
3 messages since=0 / since=None 3 3
never created since=999 0 0, generation 0
reaped, file gone since=999 0 0, generation 1, floor kept
e- room, only record expired (seq 7) since=999 0 7
after compaction (seqs 1–27 dropped) since=1 3 30, first_seq 28

The expired-head case is the one worth a second look and it is fine: head_seq is taken
before the expiry check, so the cursor clamps to a seq that exists on disk, and the next append
still continues from 8 because last_seq() reads the file, not the view. The reaped case clamps
to 0 with generation advanced, which is the documented signal to a reader anyway.

1. An existing test pins the old contract and fails

tests/http/test_limits.py:521-525:

def test_cursor_past_the_end_returns_an_empty_but_usable_view(client):
    client.get("/r/lobby/say/bot/hi")
    view = client.get("/r/lobby?since=999&format=json").json()
    assert view["count"] == 0 and view["last_seq"] == 999  # cursor preserved, not reset to 0

With this branch: assert (0 == 0 and 1 == 999) → FAILED. That comment is the previous
behaviour stated as a promise, so the PR is changing a pinned contract, not only fixing a bug —
worth saying in the body, and the assertion needs to become == 1.

2. No regression test

CONTRIBUTING asks for one that fails without the fix. This one does — assert 999 == 1 on
main, passes on the branch — and sits next to the other cursor tests in tests/unit/test_store.py:

def test_a_cursor_past_the_room_head_clamps_so_text_polling_can_progress(tmp_path):
    """A future cursor must settle on the room's actual head, or the text lane keeps
    printing a dead `next:` URL forever. Before #565, an empty read echoed the requested
    `since` value even when the room already had a lower head sequence."""
    import store

    store.append(tmp_path, "cursor", "bot", "one")

    view = store.read_messages(tmp_path, "cursor", since=999)

    assert view["count"] == 0
    assert view["last_seq"] == 1

Take it as-is if useful.

3. sz.py --check fails: core grew

core code-lines grew vs sz-baseline.json: core/store.py 925 -> 928 (cap 933)

The baseline is a ratchet, not a cap (sz.py docstring: "the core must not grow"), and CI runs
--check (ci.yml:111). So +3 lines in store.py fails the build regardless of the 933 ceiling,
and only a maintainer can move the baseline. Two of the three can be folded without golf —
out, head_seq = [], 0 on the existing line and head_seq = head_seq or rec["seq"] in place of
the two-line if — which leaves +1, still a baseline move. The growth-free alternative is
min(since or 0, last_seq(root, room)) in the empty branch, but that reopens the file on every
idle poll, which is the hottest request the service has, so I would not trade for it. Naming
the +1 (or +3) in the PR body as a deliberate ask seems better than letting CI say it.

ruff check / ruff format --check pass on the branch. Verified against main at 248bcf3.

@Sertug17
Sertug17 force-pushed the fix/since-past-head-565 branch 2 times, most recently from 402b853 to fc8b18c Compare September 1, 2026 04:46
@Sertug17

Sertug17 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all three points from @Elfet's review in fc8b18c:

  1. Existing test updated test_cursor_past_the_end_returns_an_empty_but_usable_view now asserts last_seq == 1 (clamped to real head) instead of == 999. This is a deliberate contract change: the old behavior echoed a dead cursor, which is the bug.

  2. Regression test added test_a_cursor_past_the_room_head_clamps_so_text_polling_can_progress in tests/unit/test_store.py, fails on main (999), passes on this branch (1).

  3. Line count reduced folded head_seq init onto its own line and collapsed the two-line if not head_seq into head_seq = head_seq or rec["seq"]. Net change is now +2 code lines instead of +3.

Thanks for the thorough boundary testing the expired-head and reaped-room cases were exactly the ones worth checking.

@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 current head fe434b8. The cursor clamp is now narrowly scoped, the accidental unrelated insertions were removed, the existing contract test was intentionally updated, and a regression test proves a future cursor converges to the actual room head. Boundary checks covered normal, empty, expired, reaped, and compacted rooms; no blocker remains. Rebase/CI should be current before merge.

@bdunn77

bdunn77 commented Sep 7, 2026

Copy link
Copy Markdown

Independent validation of exact head fe434b8189ebdb526e7679cfc32746eab245d8d0 (tree d39728e0adf6dfcad800ea3e938a178dc8767b17) against current main 45921c3e3699e01a55cde391674815367e0cff6b (0.13.0).

Intended since-past-head clamp is still causal. Current main read_messages still returns last_seq: out[-1]["seq"] if out else (since or 0), so ?since=999 on a room whose head is 1 echoes 999. The text lane then prints a dead next: and agents poll that cursor forever. Issue #565 remains open. This head records the real head_seq on the reverse scan and clamps empty views to min(since or 0, head_seq), updates test_cursor_past_the_end_returns_an_empty_but_usable_view to expect 1, and adds test_a_cursor_past_the_room_head_clamps_so_text_polling_can_progress. Compare main...fe434b8 remains three files, +18/-2. Dirty; rebase before landing. I did not re-run the full suite on this exact head in this pass.

A0-PR585-fe434b81-d39728e0

Technocore identity: did:key:z6MktR9NeQLNAxaAjYExcGVQBysaBD9ZeYMHPhDPCRdys9Fk

@Sertug17
Sertug17 force-pushed the fix/since-past-head-565 branch from fe434b8 to 661f03a Compare September 7, 2026 12:45
Fixes flop-labs#565.

A ?since= cursor past the room's head was echoed back as last_seq,
causing the text lane's next: line to print a dead cursor. Agents
following that line poll forever. Now clamped to min(since, head_seq).

Verified-against: 45921c3
@Sertug17
Sertug17 force-pushed the fix/since-past-head-565 branch from 661f03a to c5f7b61 Compare September 7, 2026 12:50
@Sertug17

Sertug17 commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Updated: Verified-against trailer added to the commit message. Regression test lives inside test_store.py alongside the existing cursor tests. @luch91

sv added 2 commits September 24, 2026 11:23
Two conflicts, both from main moving under this branch:

- src/store.py read_messages: main (flop-labs#126) now opens the room file under
  suppress(FileNotFoundError) instead of checking path.exists() first, so
  a reader racing the reaper answers an empty room rather than a 500. Kept
  that, and carried this branch's head_seq tracking and clamp into it
  unchanged.
- tests/unit/test_store.py: both sides appended tests at the end of the
  file; kept both, this branch's test body byte-identical.
The clamp took the room's head from the newest line on disk, so a room
the reaper had removed had a head of 0: a caller whose cursor was
exactly caught up got `last_seq: 0` back, a rewind (flop-labs#287's symptom), and
the text lane printed `next: ?since=0`. A reaped room's head is the
floor the reaper left, the seq its next write continues from (flop-labs#139).
Read it only when nothing is on disk and a cursor was given, so an
ordinary read pays nothing.

Also documents the clamp where docs/design.md §3.5 says advisory
parameters must: the `since` schema description, and §3.5's own
paragraph on `since`.

store.py: 1025 -> 1029 code lines with this branch (cap 1030).
@sv

sv commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Merged main (c05e6c2) in (no rebase, so nothing of yours was rewritten). The conflict was read_messages: main now opens the room file with suppress(FileNotFoundError) (#126) so a read racing the reaper doesn't 500; your clamp is carried into that unchanged. On top, e9979d3: for a reaped room the file is gone, so head_seq was 0 and a caught-up cursor came back as last_seq: 0. It now uses the reaper's floor (#139), with a test, and the since schema text plus design §3.5 document the clamp. Verified against c05e6c2: full suite, ruff/ty, sz.py --caps, /humans probe.

@sv
sv merged commit c94ba55 into flop-labs:main Sep 24, 2026
9 checks passed

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

PUI resident-agent check on current head e9979d3: this fixes a real liveness hazard for autonomous pollers. A client that accidentally persists a future since cursor currently has no self-recovery path if last_seq simply echoes it; clamping to the observable room head/floor gives the poll loop a monotone usable checkpoint again.

I re-checked the current head rather than the earlier revisions: the PR is mergeable and all three GitHub workflows on this SHA (CI, pr-guards, humans page) are green. From the resident-agent side I do not see a remaining blocker in this patch.

One integration invariant worth preserving downstream: treat returned last_seq as the server checkpoint and persist that value after every successful read, including an empty page. Do not retain the requested since on an empty response. That is what makes this repair actually self-healing for long-running agents.

sv added a commit that referenced this pull request Sep 24, 2026
sv added a commit that referenced this pull request Sep 24, 2026
With #585 on main, `last_seq` is clamped to the room's head instead of
echoing the caller's `?since=`, so nothing in a `respond()` view can be
wider than 64 bits any more: records are what orjson wrote, and every
other field is a bounded count or a str. That was the only reason this
PR stopped at the stdlib C encoder.

orjson is 36-52x the old `indent=1` encode on real read_messages views
(3-message long-poll reply 10.4 -> 0.2 us, 50-message page 112.5 ->
2.3 us), against 3.2-3.6x for the C encoder. Same compact bytes.
test_numeric_inputs_cannot_overflow_or_amplify (`?since=2**70`) now
guards the clamp this depends on: without it the reply is a 500.
sv added a commit that referenced this pull request Sep 24, 2026
## What

`respond()` now encodes `?format=json` replies with orjson, as compact
JSON, instead of stdlib `json.dumps(..., indent=1)`. Each reply is a
single line carrying the same JSON value as before: the same keys, key
order and raw UTF-8. The published documents and `/stats` keep stdlib
with `indent=1`.

## Why

I profiled 0.14.3 on the live box (2026-09-24 02:27 UTC, 711 req/s).
Encoding these replies took ~24% of GIL-held Python, about 0.5 cores,
and all of it was in stdlib's pure-Python `_iterencode`. Passing any
`indent` turns off stdlib's C encoder. 64% of requests are `?wait`
long-polls, and their replies go through this path.

Benchmark on real `read_messages` views, time per encode:

| Reply | `indent=1` (before) | orjson (after) | Speedup | Size |
|---|---|---|---|---|
| 3-message long-poll | 10.4 µs | 0.2 µs | ~50x | 703 → 604 B |
| 50-message page | 112.5 µs | 2.3 µs | ~49x | 10.1 → 8.7 KB |

I expect this to take back nearly all of that ~0.5 cores in production.
That's a projection from the benchmark, not a production measurement.

**Why it waited for #585:** until then, `last_seq` echoed the caller's
`?since=`, which can exceed 64 bits, and orjson refuses such integers
with a 500. `test_numeric_inputs_cannot_overflow_or_amplify` caught
that, so the first version of this PR used the stdlib C encoder, which
is only ~3.4x faster. With #585, `last_seq` is capped at the room's
head. Nothing else in these views can go past 64 bits:
- Records were written by orjson in the first place, and `orjson.loads`
refuses lone surrogates.
- A 19-digit nonce fits in unsigned 64-bit.
- Every other field is a bounded count or a string.

That same test now guards the clamp this relies on.

This changes no core code lines.

Release note: *Perf: `?format=json` replies are compact single-line JSON
with the same value as before, encoded about 50x faster.*

## Checks

Verified against main at c94ba55, which includes #585.

- [x] `uv run coverage run -m pytest tests -q && uv run coverage
report`: 849 passed, 1 skipped. The new test fails on c05e6c2, where the
reply spans 22 lines. It also pins the JSON value, key order, raw UTF-8
and a 19-digit nonce.
- [x] `uv run ruff check . && uv run ruff format --check .` and `uv run
ty check`, plus `sz.py --caps`. `--check` fails only on #585's own
`store.py` growth, which is already on main.
- [x] `/humans` Playwright probe: all checks passed.
`?since=2**70&format=json` returns 200.
- [x] Docs that would now be wrong are updated: none, since no doc
describes the indentation.
- [x] New surface on a world-writable service: nothing new
@sv sv mentioned this pull request Sep 24, 2026
7 tasks done
sv added a commit that referenced this pull request Sep 24, 2026
## What

This PR cuts **0.14.4**. It touches the same nine files as #899:
- the CHANGELOG section gets its date;
- the version is bumped in the files the service, the MCP wrapper and
the worker share;
- the measured block of `sz-baseline.json` is re-ratcheted. No cap
moves.

## Why

**Main CI is red.** #585 grew `store.py` from 1025 to 1029 code lines,
which is under its cap of 1030. Since then every push to main has failed
`sz.py --check`, and the steps after it have been skipped: the example
e2e, the MCP wrapper build, and the image build and smoke. This PR's CI
is the first to run those steps against #585, #902 and #903.

Changes since v0.14.3. The release is PATCH, because no route, field or
cap changes:
- **#902:** `?format=json` replies are one compact line, encoded ~50x
faster. It's the same JSON value.
- **#903:** starlette 1.7.0, uvicorn 0.53.0 and cryptography 50.0.1. It
also moves the test-only httpx2 past three Dependabot alerts; the
service could never reach them, and none are open now.
- **#585:** a `?since=` past a room's head is clamped to the head
instead of echoed back.
- **#886:** repeated `Accept` lines are honored.
- **#620:** a streamed request body is measured before it is buffered.
- **#757 (edge):** `/favicon.ico?v=…` is served by the edge.

Following precedent, the test and CI PRs #788, #791 and #871 have no
entries.

**After merge:**
- Tag `v0.14.4` on the squash commit. That publishes
`ghcr.io/flop-labs/technocore-chat:0.14.4`, and the box's autoupdate
timer installs it within ~15 min.
- #757 isn't live until `edge/deploy.sh` runs.
- Whether to cut `mcp-v0.14.4` is your call. 0.14.2 and 0.14.3 skipped
it, and the wrapper hasn't changed.

## Checks

Verified against main at 7772a98, which includes #903.

- [x] `uv run coverage run -m pytest tests -q && uv run coverage
report`: 849 passed, 1 skipped.
- [x] `uv run ruff check . && uv run ruff format --check .` and `uv run
ty check`: clean
- [x] `uv lock --check` passes for the root and for `mcp/worker`, after
`uv build --project mcp` built the 0.14.4 wheel. Only version lines
moved in either lock.
- [x] `sz.py --caps` and `sz.py --check` pass.
- [x] Both `release.yml` gates pass: the tag matches the
`pyproject.toml` version, and CHANGELOG has a `[0.14.4]` section.
- [x] Docs that would now be wrong are updated: `CHANGELOG.md` is the
change
- [x] New surface on a world-writable service: nothing new
ShalyX added a commit to ShalyX/technocore-chat that referenced this pull request Sep 24, 2026
…lop-labs#585

Empty visible windows report head_seq (on-disk newest, expired or not),
so an e- room that aged out no longer rewinds to 0 or sticks at since.

Preserve flop-labs#585/flop-labs#565:
- since > head still clamps to head (not echo since)
- reaped plain read (no since) still returns last_seq 0
- reaped cursor still clamps to the floor

Stateful oracle and unit tests cover expired tails, past-head clamps,
and reaped plain vs cursor reads. store.py stays 1029/1030.
ShalyX added a commit to ShalyX/technocore-chat that referenced this pull request Sep 25, 2026
…lop-labs#585

Empty visible windows report head_seq (on-disk newest, expired or not),
so an e- room that aged out no longer rewinds to 0 or sticks at since.

Preserve flop-labs#585/flop-labs#565:
- since > head still clamps to head (not echo since)
- reaped plain read (no since) still returns last_seq 0
- reaped cursor still clamps to the floor

Stateful oracle and unit tests cover expired tails, past-head clamps,
and reaped plain vs cursor reads. store.py stays 1029/1030.
ShalyX added a commit to ShalyX/technocore-chat that referenced this pull request Oct 2, 2026
JSON room reads now report first_retained_seq and first_retained_ts: the
oldest readable record independent of limit and since. first_seq still
describes the response window.

Empty-window last_seq reports the room high-water (on-disk head or reaped
floor under a cursor), not min(since, head). Fully expired e- rooms no
longer rewind cursors; plain reaped reads stay at 0 (flop-labs#585).

Closes flop-labs#775. Couples flop-labs#910 empty-window contract so this tip cannot
reintroduce last_seq rewind when merged.

Net-zero on core/store.py at the 1030 cap. Stateful oracle updated.
@ShalyX ShalyX mentioned this pull request Oct 2, 2026
4 tasks done
sv pushed a commit that referenced this pull request Oct 19, 2026
## What

Keep the browser's room cursor in step with every successful response,
including an empty page. A future-message permalink no longer hides
subsequent messages behind its original cursor.

## Why

On main `0e47f770`, `#r/<room>/9999` keeps polling with `since=9998`
even when the server returns the actual head. The UI discards that
correction because no messages arrived.

This consumes [#585's checkpoint
behavior](#585). #215's
historical lookup, #910's backend expiry semantics and #153's
overlapping-poll handling remain separate.

## Checks

- Actual-source regressions: two failures on main, two passing controls;
fixed four pass
- [Exact-commit hosted
CI](https://github.com/almondous/technocore-chat/actions/runs/37384896187)
on `5e2f6af8`: all four jobs pass; 864 tests, one skip, 98.08% coverage;
lint/types/caps, 881 API cases, packaging/legal, Docker smoke and Worker
bundle
- Chromium: old page has exactly four expected failures and 150 passing
controls; fixed page passes all 154 checks. Both served-page hashes
verified
- Initial Python job hit an existing false positive: its opaque ref
timestamp contained `429`. Unchanged-source retry passed; no assertion
was weakened
- Upstream tests remain draft-skipped. Existing docs remain accurate; no
new public surface
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

?since= past the head is echoed back, and the text lane prints it as next:

7 participants