Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 36 additions & 38 deletions src/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -889,19 +889,18 @@ def read_messages(
# advancing past records nobody can read any more, or an expired room would reuse seqs.
cutoff = _cutoff(room)
out: list[dict] = []
if path.exists():
with path.open("rb") as f:
for raw in reverse_lines(f):
rec = _parse(raw)
if rec is None:
continue
if since is not None and rec["seq"] <= since:
break
if cutoff is not None and _expired(rec, cutoff):
break
out.append(rec)
if len(out) >= limit:
break
with suppress(FileNotFoundError), path.open("rb") as f:
for raw in reverse_lines(f):
rec = _parse(raw)
if rec is None:
continue
if since is not None and rec["seq"] <= since:
break
if cutoff is not None and _expired(rec, cutoff):
break
out.append(rec)
if len(out) >= limit:
break
out.reverse()
return {
"room": room,
Expand Down Expand Up @@ -1161,18 +1160,17 @@ def _set_seq_entry(root: Path, room: str, floor: int | None) -> None:

def last_seq(root: Path, room: str) -> int:
path = room_path(root, room)
if path.exists():
with path.open("rb") as f:
# chunk_size 4 KiB, not the 64 KiB default: this runs under the room lock on
# every append and wants exactly one record — the newest. A typical record is
# ~120 B, so 4 KiB holds ~34 of them and the first read almost always answers.
# reverse_lines loops until it has a complete line, so a room of long records
# simply reads again; nothing is lost, and the common case stops reading 60 KiB
# it only ever split and threw away.
for raw in reverse_lines(f, chunk_size=4096, max_bytes=65536):
rec = _parse(raw)
if rec is not None:
return rec["seq"]
with suppress(FileNotFoundError), path.open("rb") as f:
# chunk_size 4 KiB, not the 64 KiB default: this runs under the room lock on
# every append and wants exactly one record — the newest. A typical record is
# ~120 B, so 4 KiB holds ~34 of them and the first read almost always answers.
# reverse_lines loops until it has a complete line, so a room of long records
# simply reads again; nothing is lost, and the common case stops reading 60 KiB
# it only ever split and threw away.
for raw in reverse_lines(f, chunk_size=4096, max_bytes=65536):
rec = _parse(raw)
if rec is not None:
return rec["seq"]
return 0
# The room file is gone (reaped). A recreated room carries the previous generation's
# high-water mark in a root-level floor map so cursors from the old generation keep
Expand Down Expand Up @@ -1220,17 +1218,16 @@ def room_window(root: Path, room: str) -> tuple[int, list[str]]:
nicks: list[str] = []
top = 0
path = room_path(root, room)
if path.exists():
with path.open("rb") as f:
for raw in reverse_lines(f, max_bytes=WINDOW_BYTES):
rec = _parse(raw)
if rec is None:
continue
if not nicks:
top = rec["seq"]
nicks.append(str(rec.get("from", "")))
if len(nicks) >= WINDOW_MESSAGES:
break
with suppress(FileNotFoundError), path.open("rb") as f:
for raw in reverse_lines(f, max_bytes=WINDOW_BYTES):
rec = _parse(raw)
if rec is None:
continue
if not nicks:
top = rec["seq"]
nicks.append(str(rec.get("from", "")))
if len(nicks) >= WINDOW_MESSAGES:
break
return top, nicks


Expand Down Expand Up @@ -2784,8 +2781,9 @@ def note_set(


def note_get(root: Path, ns: str, key: str) -> str | None:
path = note_path(root, ns, key)
return path.read_text(encoding="utf-8") if path.exists() else None
with suppress(FileNotFoundError):
return note_path(root, ns, key).read_text(encoding="utf-8")
return None


def topic(root: Path, room: str) -> str | None:
Expand Down
21 changes: 21 additions & 0 deletions tests/test_store_stateful.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import tempfile
from datetime import UTC, datetime, timedelta
from pathlib import Path
from unittest.mock import patch

from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
Expand Down Expand Up @@ -299,6 +300,26 @@ def last_seq_never_goes_backwards(self, room: str) -> None:
record is not that, which is why `_compact` keeps the newest one regardless."""
assert store.last_seq(self.root, room) == self.seq[room]

@rule(room=st.sampled_from(ROOMS))
def read_seq_during_reap(self, room: str) -> None:
"""Reaping between path resolution and open must preserve the sequence floor."""
target = store.room_path(self.root, room)
if not target.exists():
return
real_open = Path.open
fired = False

def open_after_reap(path, *args, **kwargs):
nonlocal fired
if path == target and not fired:
fired = True
self.reap()
return real_open(path, *args, **kwargs)

with patch.object(Path, "open", open_after_reap):
self.last_seq_never_goes_backwards(room)
assert fired

@rule(key=st.sampled_from(NOTES), value=SAFE_TEXT)
def write_note(self, key: tuple[str, str], value: str) -> None:
self._reap_model()
Expand Down
121 changes: 121 additions & 0 deletions tests/unit/test_reap_reader_review.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""PR #126 review: real reap at the open boundary, plus HTTP and error controls."""

import os
import time
from pathlib import Path

import pytest
from starlette.testclient import TestClient

import app
import config
import store


def _prepare(root, kind):
if kind == "note":
store.note_set(root, "plans", "gone", "synthetic note")
target = store.note_path(root, "plans", "gone")
else:
store.append(root, "gone", "bot", "synthetic message")
target = store.room_path(root, "gone")
old = time.time() - store.IDLE_SECONDS - 60
os.utime(target, (old, old))
return target


def _reap_just_before_open(root, target, monkeypatch):
real_open = Path.open
fired = []

def open_after_reap(path, *args, **kwargs):
if path == target and not fired:
fired.append(True)
(root / ".reaped").unlink(missing_ok=True)
store._reap(root)
assert not target.exists(), "the real reaper must remove the idle target"
return real_open(path, *args, **kwargs)

monkeypatch.setattr(Path, "open", open_after_reap)
return fired


@pytest.mark.parametrize("reader", ["messages", "last-seq", "window", "note", "export"])
def test_real_reap_during_read(tmp_path, monkeypatch, reader):
target = _prepare(tmp_path, "note" if reader == "note" else "room")
fired = _reap_just_before_open(tmp_path, target, monkeypatch)
if reader == "messages":
value = store.read_messages(tmp_path, "gone")
assert value["messages"] == []
assert value["generation"] == 1
elif reader == "last-seq":
assert store.last_seq(tmp_path, "gone") == 1, "preserve the reaper's retained floor"
elif reader == "window":
assert store.room_window(tmp_path, "gone") == (0, [])
elif reader == "note":
assert store.note_get(tmp_path, "plans", "gone") is None
else:
generation, chunks = store.export_room(tmp_path, "gone")
assert generation == 1 and b"".join(chunks) == b""
assert fired == [True]


@pytest.mark.parametrize("kind", ["room", "note"])
def test_http_read_while_reaper_removes_target(tmp_path, monkeypatch, kind):
target = _prepare(tmp_path, kind)
fired = _reap_just_before_open(tmp_path, target, monkeypatch)
with (
config.override(ROOT=tmp_path),
TestClient(app.app, raise_server_exceptions=False) as client,
):
url = "/r/gone?format=json" if kind == "room" else "/kv/plans/gone"
response = client.get(url)
assert fired == [True]
assert response.status_code == (200 if kind == "room" else 404)
if kind == "room":
assert response.json()["messages"] == []


@pytest.mark.parametrize("reader", ["messages", "last-seq", "window", "note", "export"])
def test_permission_error_does_not_become_an_empty_result(tmp_path, monkeypatch, reader):
target = _prepare(tmp_path, "note" if reader == "note" else "room")
real_open = Path.open

def forbidden(path, *args, **kwargs):
if path == target:
raise PermissionError("synthetic denial")
return real_open(path, *args, **kwargs)

monkeypatch.setattr(Path, "open", forbidden)
with pytest.raises(PermissionError, match="synthetic denial"):
if reader == "messages":
store.read_messages(tmp_path, "gone")
elif reader == "last-seq":
store.last_seq(tmp_path, "gone")
elif reader == "window":
store.room_window(tmp_path, "gone")
elif reader == "note":
store.note_get(tmp_path, "plans", "gone")
else:
store.export_room(tmp_path, "gone")


def test_a_held_descriptor_keeps_its_original_snapshot(tmp_path, monkeypatch):
"""A reap after open must not invalidate an already-held room descriptor."""
target = _prepare(tmp_path, "room")
real_open = Path.open
fired = []

def open_before_reap(path, *args, **kwargs):
handle = real_open(path, *args, **kwargs)
if path == target and not fired:
fired.append(True)
(tmp_path / ".reaped").unlink(missing_ok=True)
store._reap(tmp_path)
assert not target.exists()
return handle

monkeypatch.setattr(Path, "open", open_before_reap)
view = store.read_messages(tmp_path, "gone")
assert fired == [True]
assert [message["text"] for message in view["messages"]] == ["synthetic message"]
37 changes: 37 additions & 0 deletions tests/unit/test_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,43 @@ def test_torn_final_line_costs_only_that_record(tmp_path):
assert store.read_messages(tmp_path, "crash", limit=1)["messages"][0]["text"] == "after"


@pytest.mark.parametrize(
("kind", "reader", "empty"),
(
("room", lambda store, root: store.read_messages(root, "gone")["messages"], []),
("room", lambda store, root: store.last_seq(root, "gone"), 0),
("room", lambda store, root: store.room_window(root, "gone"), (0, [])),
("note", lambda store, root: store.note_get(root, "plans", "gone"), None),
),
)
def test_readers_tolerate_a_reap_between_path_resolution_and_open(
tmp_path, monkeypatch, kind, reader, empty
):
"""A concurrent reaper may unlink after a reader chose the path but before open().

That state is externally indistinguishable from an already-absent room or note, so it
must return the ordinary empty result instead of turning an idle cleanup into a 500.
"""
import store

if kind == "room":
store.append(tmp_path, "gone", "bot", "hi")
target = store.room_path(tmp_path, "gone")
else:
store.note_set(tmp_path, "plans", "gone", "hi")
target = store.note_path(tmp_path, "plans", "gone")
path_type = type(target)
real_open = path_type.open

def open_after_reap(self, *args, **kwargs):
if self == target:
target.unlink(missing_ok=True)
return real_open(self, *args, **kwargs)

monkeypatch.setattr(path_type, "open", open_after_reap)
assert reader(store, tmp_path) == empty


def test_concurrent_appends_never_duplicate_a_seq(tmp_path):
import threading

Expand Down
Loading