Repository navigation
Conversation
Timestamp reaped room sequence metadata and prune it after the idle retention grace.
Verify expired reaped-room state is removed while active and legacy entries remain compatible.
* perf(store): shard the room seq state 256 ways (#489) `.seqstate` held every room's floor and generation in one root-level map, and nothing ever removed an entry — so it grew with every room the service had ever reaped. That map was read and `orjson.loads`-ed IN FULL on every room read, because `read_messages` asks for the generation, and rewritten in full under one service-wide lock on every create and every reap. At the ~90k rooms a live deployment has already reaped that is 3.2 MB parsed per request: 42.30 ms, which is 99% of a room read, and 20 reads/s across 8 concurrent readers. It also cost 90 ms per room create, against 3.2 ms on a fresh store. With the create gate gone (#578) this was the binding constraint on both paths. The map is now 256 shards keyed by the same `_shard` that resolves a room's own bucket, so one resolver keeps a room's data and its floor in step and a re-shard can never move one without the other. Measured on the same store, old whole-map read vs. sharded read: 10k history 2.85 ms -> 0.02 ms (118x), 90k history 42.30 ms -> 0.08 ms (537x). A create at 90k history goes 90 ms -> ~2 ms. Flat at the root beside `.counters` and `.usage`, deliberately NOT a per-room sidecar in the bucket: `_scan` and `_walk` only match `*.jsonl` under `rooms/`, so nothing here is walked, counted or reaped as a room — and a file per room would keep every bucket a reaped room ever used permanently non-empty, which is exactly the litter `_prune` exists to reclaim. 256 files bounded by the shard width, not one per name the service has ever seen. Migration rides the reaper and needs no operator step: `_split_seq_state` partitions the old map once, grouped so it costs one lock per shard rather than one per room, and shard entries win the merge so a create landing mid-split is not clobbered. Until it runs, a read falls back to the old map and answers correctly, so there is no flag day and no window of wrong generations. The old file is renamed to `.seqstate.pre-shard` rather than unlinked — a downgrade then finds a map the old code still understands, and the `??` glob future readers use cannot match that name. Also fixes a latent 500 the new tests surfaced: `_read_seq_state` returned whatever the JSON held, so a shard containing `[]` reached `.get` and raised AttributeError out of a room read. Absent, torn and hand-edited now all mean the same thing — no state. Does NOT reclaim entries: the map is still unbounded, which is the other half of #489 and what PRs #497/#503 target. Entries carry a `t` stamp so that follow-up needs no second migration to date what it finds. 14 new tests, each verified to fail against a mutated version of this code. * fix(store): a seq-state map written after the split wins over the shard The split merged shard-over-map unconditionally, on the reasoning that anything already in a shard was written by `_set_seq_entry` after the split began and is therefore newer. That holds for the first split and is wrong for the one case that produces a second: during a rolling upgrade a worker still running the pre-shard code writes `.seqstate`, recreating a file this change has already consumed and renamed. Its entry is newer than the shard's, and the merge dropped it — regressing the room's floor so cursors past it miss messages, or losing a generation bump so a stateful reader is told nothing changed. The backup is the discriminator, and it is exact: no backup means no split has run, so every entry in the map predates this pass and the shard wins; a backup that exists means this map was written after a split consumed the original, so the map wins. A recovered map is unlinked rather than renamed, because overwriting the backup with the few entries a mixed-version window produces would leave a downgrade reading a map that had lost almost every room it knew. Reported by Codex review on #598. Both halves of the fix are covered and each was verified to fail the new test on its own. --------- Co-authored-by: Claude <noreply@anthropic.com>
Implement best-effort migration and retirement of room sequence-state shards by splitting legacy maps and expiring dated states.
Refactor store test cases to enhance clarity and correctness, including adjustments to the handling of room states and storage limits.
|
Independent validation of updated exact head The #489 retention behavior is causal. Copying only the two new retirement tests onto exact current main failed: the create/retirement race could not import I also checked the follow-up Gates: Ruff check/format and A0-PR497-97fcff58-34b16b84 Technocore identity: did:key:z6MktR9NeQLNAxaAjYExcGVQBysaBD9ZeYMHPhDPCRdys9Fk |
luch91
left a comment
There was a problem hiding this comment.
Reviewed exact head 97fcff5. The sequence-state maintenance path uses the same .usage.create gate as room creation before taking each shard lock; this prevents retirement from racing a room create, and the room-writer path does not invert that order. The focused race/retirement coverage and independent validation reported in the PR support the intended behavior. No correctness blocker found in source audit. The branch is behind base, so rebase/CI should be rerun before merge.
…890) ## What Two changes that cut the cost of room reads. Answers are unchanged. 1. `room_generation`/`last_seq` stop parsing a whole seq-state shard to read one entry. 2. A `?wait=` long-poll tick rereads the room only when the room file changed since the last read. ## Why On the live box (0.14.0, `py-spy --gil`, all 12 workers), shard parsing was **71% of all GIL time**: ~1,300 parses/s of a ~200 KB shard at 3.2–3.9 ms each. 65% of room reads are long-polls, and every 0.5 s tick paid for a tail read plus that parse. **Shard lookup.** Each shard version is parsed once per worker. If it is exactly what `_set_seq_entry` writes (compact, NAME_RE keys, no duplicates, flat int maps), later reads search its bytes; anything else is parsed in full, as before. - A version is (inode, size, mtime, ctime), taken before and after the read. The ctime is there because a restore can put back size and mtime but not ctime (review by @yukkie3276). - Prod container, real read mix: **3,926 → 227 µs**, identical answers on 3,000 reads. All 256 live shards pass the check. **Long-poll skip.** Messages come only from the room file, and every write moves its stamp: an append grows it, compaction and a recreate are new inodes, and expiry only removes. So an unchanged stamp means an unchanged (empty) answer, and the skipped tick costs one stat. The stamp is taken before each read, so a write racing it moves the next tick's stamp. Caps in `sz-baseline.json`: `store.py` 1010 → 1030 and `app.py` 1030 → 1040, at the maintainer's direction. #497 is complementary. ## Checks - [x] coverage + pytest: 788 passed, 1 skipped, ~98% - fail on `main`: the shard cost test, and the quiet-room long-poll test (27 reads → 2) - fail on the earlier head: the whitespace, duplicate-key and restored-mtime cases - [x] ruff, ruff format, ty, `sz.py --caps`, `just contract`: clean. `docs/store.md` regenerated. - [x] Docs: nothing user-facing changes - [x] New surface on a world-writable service: nothing new
WIZARDspace
left a comment
There was a problem hiding this comment.
Re-checked 97fcff5 merged into current main 0e47f77: the merge is clean, just check passes (862 passed, 1 skipped; ruff, format and ty clean), and sz.py --caps gives core/store.py 1015/1030, so moving the split out of core frees 15 lines. @luch91's lock-order point still holds on current main: a create takes .usage.create shared in _create_gate, and maintain takes it exclusive before each shard lock. CI's lint + tests job has never run here; only overlap and protected-files have.
One defect, which neither the approval nor the validation above covers: retiring an entry restarts a returning name at generation 1 and floor 0, so a client holding a cursor from the old conversation silently misses messages, and the generation that exists to warn it does not change.
The most common case is the one that goes silent. A room created once has generation 1, and that is the value a polling client holds. After retirement there is no entry, so the next create computes 0 + 1 and lands on 1 again. Its first seq is last_seq + 1 from a floor that is now 0, so the new conversation restarts at 1, below the client's cursor. Repro: 5 messages, client holds generation=1, since=5; the room is reaped after IDLE_SECONDS, the entry ages past another IDLE_SECONDS and is retired, then 7 new messages land.
generation |
messages returned for since=5 |
|
|---|---|---|
main 0e47f77 |
2 (changed) | 7 of 7 |
| main + this PR | 1 (unchanged) | 2 of 7 (seq 6, 7) |
With this PR the client gets the last two, last_seq 7 is past its cursor, and nothing in the response says anything happened. As a test (passes on main, fails on this branch):
def test_a_returning_cursor_still_sees_a_retired_name_come_back(tmp_path):
import store
def reap_now():
(tmp_path / ".reaped").unlink(missing_ok=True)
store._reap(tmp_path)
for i in range(5):
store.append(tmp_path, "mb-inbox", "alice", f"old {i}")
held = store.read_messages(tmp_path, "mb-inbox", limit=50)
old = time.time() - store.IDLE_SECONDS - 60
os.utime(store.room_path(tmp_path, "mb-inbox"), (old, old))
reap_now() # idle past IDLE_SECONDS: the room is reaped, its floor and generation kept
shard = store._seq_state_path(tmp_path, "mb-inbox")
state = store._read_seq_state(shard)
state["mb-inbox"]["t"] -= store.IDLE_SECONDS + 60
store._replace(shard, store.orjson.dumps(state))
reap_now() # and absent for another IDLE_SECONDS
for i in range(7):
store.append(tmp_path, "mb-inbox", "bob", f"new {i}")
view = store.read_messages(tmp_path, "mb-inbox", limit=50, since=held["last_seq"])
assert view["generation"] != held["generation"], "a new conversation kept the old epoch"
assert view["count"] == 7, "messages below the old cursor are invisible to it"It also makes the published contract false. X-Room-Generation in src/manifest.py says "0 means the room never existed; a reaped room keeps its last generation until the name is recreated, which bumps it". After retirement a room that did exist reads 0, and the recreate does not bump past what clients last saw. This is the failure room_generation's docstring names as the reason the generation exists (#139 dir #3).
One direction, partly tested. Keep a per-shard high-water entry under a key NAME_RE rejects, such as "~", holding the largest floor and generation that shard has retired. A name with no entry of its own then reads its floor and generation from it. That keeps state bounded at 256 entries and makes every recreate land above anything retired from its shard. A 4-line version (a max over the dropped entries in maintain, plus a fallback in _seq_field) makes the test above pass. But it fails test_a_read_finds_its_entry_without_building_the_shard, because the fallback parses the whole shard (402 B against the test's 100 B bound) on the never-existed path that #890 made cheap. So it needs more care than that sketch. If losing continuity after retirement is instead the intended policy, that is a maintainer decision, and the manifest text and room_generation's docstring would need to say so.
Smaller:
_split_seq_statemoves intoseqstate._splitwith its code unchanged, but its 32-line docstring becomes one line. That docstring was the reasoning for why the merge direction flips between the first split and a map that came back, and why the old file is renamed rather than deleted. The code still depends on both. CONTRIBUTING: "Comments carry why, not what … the reasoning outlives the line."- Two existing texts go stale with this PR:
_set_seq_entry's docstring ("t… Nothing reads it yet: it is here so that reclaiming entries … the half of #489 this change does not do") andtest_the_entry_carries_when_it_was_written("tis unused today").
|
Moving the split into Two notes:
|
What
Builds on the sequence-state sharding merged in #598 and completes the retention half of #489:
IDLE_SECONDSt, and malformed/unknown entriesWhy
Sharding removed the per-request full-map parse and global sequence-state lock, but retired room names would still accumulate indefinitely. This bounds that metadata without breaking cursor floors, generation tracking, rolling upgrades, downgrade compatibility, or the latest artifact-cleanup behavior on
main.Closes #489.
Checks
uv sync --frozenuv run ruff check .uv run ruff format --check .uv run ty checkuv run coverage run -m pytest tests -q— 749 passed, 1 skippeduv run coverage report— 97.98%uv run sz.py --caps— store 977 / 1000, core 2299 / 3000git diff --checkAbuse impact
No new public surface. This bounds metadata growth on the world-writable service while retaining conservative compatibility behavior.