From 44713af8572dc9268a9579a9286466e126b90354 Mon Sep 17 00:00:00 2001 From: ShalyX Date: Fri, 2 Oct 2026 08:08:03 +0800 Subject: [PATCH 1/2] fix(store): preserve seq state across mixed-version splits Merge legacy and shard .seqstate entries by generation lifecycle and floor high-water mark instead of picking one whole entry from file age. A post-split stale map can no longer rewind a shard recreate (gen+floor). Same-gen independent reaps keep the higher floor. Net-zero packing keeps store.py under the 1030 cap (1026/1030). Closes #652. --- src/store.py | 107 ++++++++++++++++------------------- tests/unit/test_seq_state.py | 37 ++++++++++++ 2 files changed, 87 insertions(+), 57 deletions(-) diff --git a/src/store.py b/src/store.py index 67cd17b9d..60e80d6d4 100644 --- a/src/store.py +++ b/src/store.py @@ -739,11 +739,7 @@ def counters(root: Path, strict: bool = True) -> dict: data = {} if not isinstance(data, dict): data = {} - out = {} - for key in COUNTER_KEYS: - value = data.get(key, 0) - out[key] = value if isinstance(value, int) and value >= 0 else 0 - return out + return {k: (v if isinstance(v := data.get(k, 0), int) and v >= 0 else 0) for k in COUNTER_KEYS} # Deltas wait here between flushes, one bucket per store root. Fixed size whatever the write @@ -870,21 +866,19 @@ def _expired(rec: dict, cutoff: float) -> bool: and a record whose age cannot be established cannot honour that promise. Elsewhere `ts` stays what it always was — an opaque string nothing parses.""" ts = rec.get("ts") - if isinstance(ts, str): - for fmt in ("%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%dT%H:%M:%SZ"): - try: - return datetime.strptime(ts, fmt).replace(tzinfo=UTC).timestamp() < cutoff - except ValueError: - continue + if not isinstance(ts, str): + return True + for fmt in ("%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%dT%H:%M:%SZ"): + with suppress(ValueError): + return datetime.strptime(ts, fmt).replace(tzinfo=UTC).timestamp() < cutoff return True def _parse(line: bytes) -> dict | None: - try: + with suppress(ValueError, UnicodeDecodeError): rec = orjson.loads(line) - except (ValueError, UnicodeDecodeError): - return None # torn write at EOF, or hand-edited garbage - return rec if isinstance(rec, dict) and isinstance(rec.get("seq"), int) else None + if isinstance(rec, dict) and isinstance(rec.get("seq"), int): + return rec def read_messages( @@ -898,12 +892,11 @@ def read_messages( # the scan stops there. `last_seq` deliberately does NOT filter — seq must keep # advancing past records nobody can read any more, or an expired room would reuse seqs. cutoff = _cutoff(room) - out: list[dict] = [] # The room's head, where a cursor past it is clamped (#565): echoing it back printed a # `next:` that polls a dead cursor forever, and let a caller put a number of any width # into every JSON reply. The newest record on disk, expired or not, for the same reason # `last_seq` does not filter. - head_seq = 0 + out, head_seq = [], 0 with suppress(FileNotFoundError), path.open("rb") as f: for raw in reverse_lines(f): rec = _parse(raw) @@ -1075,6 +1068,10 @@ def _read_seq_state(path: Path) -> dict: return state if isinstance(state, dict) else {} +def _seq_value(entry: dict, key: str) -> int: + return v if isinstance(v := entry.get(key), int) and v >= 0 else 0 + + # Shard -> identity of the last copy verified to be in the writers' exact form. A verdict # about the file, never its data: every read still reads the bytes. See `_seq_entry`. _SEQ_CHECKED: dict[Path, tuple[int, int, int, int]] = {} @@ -1269,11 +1266,8 @@ def _engagement(nicks: Sequence[str]) -> dict: n = len(nicks) if not n: # no parsable record in the window: no data, which is not the same as zero return {"window": 0, "zero_response_share": None, "nick_diversity": None} - return { - "window": n, - "zero_response_share": round(_unanswered(nicks) / n, 4), - "nick_diversity": round(len(set(nicks)) / n, 4), - } + zrs, div = round(_unanswered(nicks) / n, 4), round(len(set(nicks)) / n, 4) + return {"window": n, "zero_response_share": zrs, "nick_diversity": div} def _rollup(windows: list[Sequence[str]]) -> dict: @@ -1282,25 +1276,23 @@ def _rollup(windows: list[Sequence[str]]) -> dict: Nicks are pooled globally too — one bot talking to itself in forty rooms should read as low diversity, not as forty separate healthy-looking rooms.""" total = sum(len(w) for w in windows) - if not total: - return { - "window_cap": WINDOW_MESSAGES, - "windowed_messages": 0, - "zero_response_share": None, - "nick_diversity": None, - } - distinct = len({nick for w in windows for nick in w}) - return { + base = { "window_cap": WINDOW_MESSAGES, - "windowed_messages": total, - "zero_response_share": round(sum(_unanswered(w) for w in windows) / total, 4), - "nick_diversity": round(distinct / total, 4), + "windowed_messages": total or 0, + "zero_response_share": None, + "nick_diversity": None, } + if not total: + return base + base["zero_response_share"] = round(sum(_unanswered(w) for w in windows) / total, 4) + base["nick_diversity"] = round(len({n for w in windows for n in w}) / total, 4) + return base def list_rooms(root: Path) -> list[str]: - names = (e.name[: -len(".jsonl")] for e in _walk(root / "rooms", ".jsonl")) - return sorted(n for n in names if _listable(n)) + return sorted( + n for e in _walk(root / "rooms", ".jsonl") if _listable(n := e.name[: -len(".jsonl")]) + ) def _time_bucket(now: float, ttl: float) -> int: @@ -1514,14 +1506,11 @@ def _stillborn(path: Path | str) -> bool: costs two lines and an unanswered one costs the few hundred bytes it is. An unreadable file is not stillborn: deleting what cannot be counted is how a reaper eats live data. """ - seen = 0 try: with open(path, "rb") as f: + seen = 0 for line in f: - if _parse(line) is None: - continue - seen += 1 - if seen > STILLBORN_MESSAGES: + if _parse(line) is not None and (seen := seen + 1) > STILLBORN_MESSAGES: return False except OSError: return False @@ -1675,18 +1664,12 @@ def _split_seq_state(root: Path) -> None: Grouped before any shard is opened, so this costs one pass over the map and one lock per *shard* rather than one per room. - Which side of the merge wins is decided by whether the backup already exists, and the two - cases are opposite for the same reason — the later write is the true one: - - - **The first split.** No backup yet, so every entry in the map predates this pass, and - anything already in a shard was put there by `_set_seq_entry` while this ran. The shard - wins. - - **A map that came back.** The backup exists, so this map was written *after* a split - had already consumed and renamed the original — which only an old worker still running - the pre-shard code does, during a rolling upgrade. Its entry is then the newer fact and - the shard's is stale, so the map wins. Getting this backwards silently drops that - worker's reap or create: the room's floor regresses and cursors past it miss messages, - or a generation bump is lost and a stateful reader is told nothing changed. + Fields merge independently by high-water mark. A rolling upgrade can have an old worker + update the legacy map while a new worker updates the shard, and those updates need not be + the same kind of transition: one may advance `floor` while the other bumps `gen`. Choosing + one whole entry based on which file exists can preserve one field while regressing the + other. Both fields are monotonic within a lifecycle, so maxima preserve every accepted + transition; a higher `gen` wins the whole entry so recreate clears floor with the bump. The recovered map is unlinked rather than renamed, so the backup keeps holding the *whole* pre-shard state. Overwriting it with the handful of entries a mixed-version window produced @@ -1712,7 +1695,19 @@ def _split_seq_state(root: Path) -> None: for path, entries in shards.items(): with _locked(path): shard = _read_seq_state(path) - merged = {**entries, **shard} if first else {**shard, **entries} + merged = dict(shard) + for room, entry in entries.items(): + cur = merged.get(room) + if not isinstance(cur, dict) or not isinstance(entry, dict): + merged[room] = entry + continue + # Higher gen owns the lifecycle (recreate clears floor); same gen max floor. + cg, ig = _seq_value(cur, "gen"), _seq_value(entry, "gen") + if ig != cg: + merged[room] = dict(entry if ig > cg else cur) + else: + fl = max(_seq_value(cur, "floor"), _seq_value(entry, "floor")) + merged[room] = {**cur, **entry, "floor": fl, "gen": cg} _replace(path, orjson.dumps(merged), fsync=config.FSYNC) legacy.replace(backup) if first else legacy.unlink() except OSError: @@ -2348,9 +2343,7 @@ def room_bytes_used(root: Path) -> int: def _ring_limit(root: Path) -> int: """How much ring a room may keep right now — the full ring, or its guaranteed floor once the service is over its total room-byte budget. See RESERVED_ROOM_BYTES.""" - if room_bytes_used(root) < MAX_TOTAL_ROOM_BYTES: - return MAX_ROOM_BYTES - return RESERVED_ROOM_BYTES + return MAX_ROOM_BYTES if room_bytes_used(root) < MAX_TOTAL_ROOM_BYTES else RESERVED_ROOM_BYTES def _check_room_capacity(root: Path, path: Path) -> None: diff --git a/tests/unit/test_seq_state.py b/tests/unit/test_seq_state.py index 25839435c..39bfd43e2 100644 --- a/tests/unit/test_seq_state.py +++ b/tests/unit/test_seq_state.py @@ -152,6 +152,43 @@ def test_a_map_written_after_the_split_wins_over_the_shard(tmp_path) -> None: assert kept == {"gone": {"floor": 5, "gen": 1}}, "the backup lost the original state" +def test_mixed_upgrade_does_not_let_stale_map_clobber_shard_recreate(tmp_path) -> None: + """A shard recreate must survive a post-split legacy map that still holds the old lifecycle. + + Whole-entry "map wins after backup exists" prefers the stale map and rewinds both gen and + floor. Field-wise merge keeps the higher gen as one lifecycle so the recreate's cleared + floor is not replaced by the prior conversation's high-water mark. + """ + import store + + _legacy(tmp_path, {"gone": {"floor": 500, "gen": 2}}) + _reap_now(tmp_path) + store._set_seq_entry(tmp_path, "gone", None) # new worker: gen advances, floor clears + assert store.last_seq(tmp_path, "gone") == 0 + gen_after = store.room_generation(tmp_path, "gone") + assert gen_after > 2 + + _legacy(tmp_path, {"gone": {"floor": 500, "gen": 2}}) # old worker rewrites the map + _reap_now(tmp_path) + + assert store.room_generation(tmp_path, "gone") == gen_after, "stale map rewound generation" + assert store.last_seq(tmp_path, "gone") == 0, "stale map restored the old conversation floor" + + +def test_mixed_upgrade_keeps_same_gen_floor_high_water(tmp_path) -> None: + """Same lifecycle: independent reaps must keep the higher floor across map and shard.""" + import store + + _legacy(tmp_path, {"gone": {"floor": 100, "gen": 4}}) + _reap_now(tmp_path) + store._set_seq_entry(tmp_path, "gone", 150) + _legacy(tmp_path, {"gone": {"floor": 300, "gen": 4}}) + _reap_now(tmp_path) + + assert store.last_seq(tmp_path, "gone") == 300 + assert store.room_generation(tmp_path, "gone") == 4 + + # --------------------------------------------------------------------------- reads From d960702d7966d36137e8ef3bb8330d4e57281c47 Mon Sep 17 00:00:00 2001 From: silvercat <38044896+almondous@users.noreply.github.com> Date: Fri, 2 Oct 2026 09:24:38 +0900 Subject: [PATCH 2/2] fix(store): retain valid state across malformed legacy migration Follow up on PR #708 rebuilt at d1c60f7. Preserve the valid dict when only one migration entry is structurally valid, without changing lifecycle merging or cap usage. Add symmetric first/recovered migration regressions, append/cursor checks, and a lifecycle state-machine rule. --- src/store.py | 2 +- tests/test_store_stateful.py | 13 ++++++++ tests/unit/test_seq_state.py | 61 ++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/src/store.py b/src/store.py index 60e80d6d4..abd778902 100644 --- a/src/store.py +++ b/src/store.py @@ -1699,7 +1699,7 @@ def _split_seq_state(root: Path) -> None: for room, entry in entries.items(): cur = merged.get(room) if not isinstance(cur, dict) or not isinstance(entry, dict): - merged[room] = entry + merged[room] = cur if isinstance(cur, dict) else entry continue # Higher gen owns the lifecycle (recreate clears floor); same gen max floor. cg, ig = _seq_value(cur, "gen"), _seq_value(entry, "gen") diff --git a/tests/test_store_stateful.py b/tests/test_store_stateful.py index 5800c320f..b2dacf35b 100644 --- a/tests/test_store_stateful.py +++ b/tests/test_store_stateful.py @@ -138,6 +138,19 @@ def teardown(self) -> None: setattr(store, name, value) shutil.rmtree(self.root, ignore_errors=True) + @rule(room=st.sampled_from(ROOMS), malformed=st.sampled_from([None, 7, "torn"])) + def migrate_malformed_legacy(self, room: str, malformed: object) -> None: + """A mixed-version migration must preserve the durable lifecycle through any sequence.""" + shard = store._read_seq_state(store._seq_state_path(self.root, room)) + if not isinstance(shard.get(room), dict): + return + floor = store._seq_field(self.root, room, "floor") + generation = store.room_generation(self.root, room) + (self.root / ".seqstate").write_text(json.dumps({room: malformed})) + store._split_seq_state(self.root) + assert store._seq_field(self.root, room, "floor") == floor + assert store.room_generation(self.root, room) == generation + # ------------------------------------------------------------------ the reaper, modelled # # "gone", "kept", or None — None when an age sits close enough to a threshold that the diff --git a/tests/unit/test_seq_state.py b/tests/unit/test_seq_state.py index 39bfd43e2..3ea018f8b 100644 --- a/tests/unit/test_seq_state.py +++ b/tests/unit/test_seq_state.py @@ -455,3 +455,64 @@ def test_seq_state_survives_a_read_only_store(tmp_path) -> None: store._set_seq_entry(tmp_path, "nope", 5) # must not raise assert store.last_seq(tmp_path, "nope") == 0 assert os.path.isdir(shard) + + +@pytest.mark.parametrize("recovered", [False, True], ids=["first", "recovered"]) +@pytest.mark.parametrize("bad", [None, [], 7, "torn"]) +@pytest.mark.parametrize("bad_legacy", [False, True], ids=["bad-shard", "bad-legacy"]) +def test_split_preserves_the_only_valid_lifecycle(tmp_path, recovered, bad, bad_legacy): + import store + + good = {"floor": 50, "gen": 3} + backup = tmp_path / ".seqstate.pre-shard" + if recovered: + backup.write_bytes(orjson.dumps({"original": {"floor": 1, "gen": 1}})) + before = backup.read_bytes() if recovered else None + legacy, shard = (bad, good) if bad_legacy else (good, bad) + _legacy(tmp_path, {"gone": legacy}) + store._seq_state_path(tmp_path, "gone").write_bytes(orjson.dumps({"gone": shard})) + + store._split_seq_state(tmp_path) + assert store.last_seq(tmp_path, "gone") == 50 + assert store.room_generation(tmp_path, "gone") == 3 + assert not (tmp_path / ".seqstate").exists() + assert backup.read_bytes() == (before if recovered else orjson.dumps({"gone": legacy})) + store._split_seq_state(tmp_path) + assert store.last_seq(tmp_path, "gone") == 50 + store._write_record(tmp_path, "gone", "bot", "back") + result = store.read_messages(tmp_path, "gone", since=50) + assert [message["seq"] for message in result["messages"]] == [51] + assert store.room_generation(tmp_path, "gone") == 4 + + +@pytest.mark.parametrize("recovered", [False, True], ids=["first", "recovered"]) +@pytest.mark.parametrize( + "legacy,shard,expected", + [ + ({"floor": 50, "gen": 3}, {"floor": 10, "gen": 3}, {"floor": 50, "gen": 3}), + ({"floor": 10, "gen": 3}, {"floor": 50, "gen": 3}, {"floor": 50, "gen": 3}), + ({"floor": 0, "gen": 9}, {"floor": 500, "gen": 2}, {"floor": 0, "gen": 9}), + ({"floor": 500, "gen": 2}, {"floor": 0, "gen": 9}, {"floor": 0, "gen": 9}), + ({"floor": -1, "gen": "bad"}, {"floor": 50, "gen": 0}, {"floor": 50, "gen": 0}), + ({"floor": 50, "gen": 0}, {"floor": [], "gen": -1}, {"floor": 50, "gen": 0}), + ], +) +def test_split_merges_lifecycle_in_both_directions(tmp_path, recovered, legacy, shard, expected): + import store + + backup = tmp_path / ".seqstate.pre-shard" + if recovered: + backup.write_bytes(orjson.dumps({"original": {"floor": 1, "gen": 1}})) + before = backup.read_bytes() if recovered else None + _legacy(tmp_path, {"gone": legacy}) + store._seq_state_path(tmp_path, "gone").write_bytes(orjson.dumps({"gone": shard})) + store._split_seq_state(tmp_path) + assert store.last_seq(tmp_path, "gone") == expected["floor"] + assert store.room_generation(tmp_path, "gone") == expected["gen"] + assert backup.read_bytes() == (before if recovered else orjson.dumps({"gone": legacy})) + store._split_seq_state(tmp_path) + assert store.last_seq(tmp_path, "gone") == expected["floor"] + store._write_record(tmp_path, "gone", "bot", "back") + result = store.read_messages(tmp_path, "gone", since=expected["floor"]) + assert [message["seq"] for message in result["messages"]] == [expected["floor"] + 1] + assert store.room_generation(tmp_path, "gone") == expected["gen"] + 1