Skip to content

Commit cd1b523

Browse files
committed
Cache event reads within a transaction
Parse the locked log once for attempt, ID, and state reads. Invalidate that snapshot after a fresh or uncertain append so later reads return to the durable log without maintaining parallel sequence state.
1 parent 786c513 commit cd1b523

3 files changed

Lines changed: 66 additions & 34 deletions

File tree

‎skills/leaf/scripts/leaf/event_log.py‎

Lines changed: 27 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import os
66
import secrets
77
import threading
8+
from copy import deepcopy
89
from datetime import datetime
910
from pathlib import Path
1011

@@ -94,50 +95,39 @@ def _attempt_payload(event: dict) -> dict:
9495
}
9596

9697

97-
def _matching_attempt(f, event: dict) -> dict | None:
98+
def _matching_attempt(events: list[dict], event: dict) -> dict | None:
9899
attempt = event.get("attempt")
99100
if not attempt:
100101
return None
101-
f.seek(0)
102-
for raw in f:
103-
try:
104-
existing = json.loads(raw)
105-
except (json.JSONDecodeError, UnicodeDecodeError):
106-
continue
102+
for existing in events:
107103
if existing.get("attempt") != attempt:
108104
continue
109105
if _attempt_payload(existing) != _attempt_payload(event):
110106
raise AttemptConflict(
111107
f"attempt {attempt!r} already belongs to another event"
112108
)
113-
return existing
109+
accepted = deepcopy(existing)
110+
accepted.pop("seq", None)
111+
return accepted
114112
return None
115113

116114

117-
def _event_id_exists(f, event_id: str) -> bool:
115+
def _event_id_exists(events: list[dict], event_id: str) -> bool:
118116
"""Whether this log already owns an event identity."""
119-
f.seek(0)
120-
for raw in f:
121-
try:
122-
existing = json.loads(raw)
123-
except (json.JSONDecodeError, UnicodeDecodeError):
124-
continue
125-
if existing.get("id") == event_id:
126-
return True
127-
return False
117+
return any(existing.get("id") == event_id for existing in events)
128118

129119

130-
def _append_event_unlocked(f, event: dict) -> dict:
120+
def _append_event_unlocked(f, event: dict, events: list[dict]) -> tuple[dict, bool]:
131121
"""Append while the caller holds this log file's exclusive lease."""
132122
# Attempt identity is checked under the log's append lock. Checking before
133123
# this point would leave two server threads free to observe absence together
134124
# and append together. Content and time deliberately play no part: an
135125
# intentional later identical message has a fresh attempt and is a second
136126
# event.
137-
if event.get("attempt") and (existing := _matching_attempt(f, event)):
138-
return existing
127+
if event.get("attempt") and (existing := _matching_attempt(events, event)):
128+
return existing, False
139129
if "id" in event:
140-
if _event_id_exists(f, event["id"]):
130+
if _event_id_exists(events, event["id"]):
141131
raise ValueError(f"event id {event['id']!r} already exists")
142132
else:
143133
# Event ids escape the page with host requests as durable idempotency and
@@ -146,7 +136,7 @@ def _append_event_unlocked(f, event: dict) -> dict:
146136
# probability as an invariant.
147137
while True:
148138
candidate = secrets.token_hex(16)
149-
if not _event_id_exists(f, candidate):
139+
if not _event_id_exists(events, candidate):
150140
event["id"] = candidate
151141
break
152142
event.setdefault("ts", now_iso())
@@ -165,7 +155,7 @@ def _append_event_unlocked(f, event: dict) -> dict:
165155
# and events are rare enough that a flush per append costs nothing.
166156
f.flush()
167157
os.fsync(f.fileno())
168-
return event
158+
return event, True
169159

170160

171161
def append_event(page_dir: Path, event: dict) -> dict:
@@ -174,13 +164,13 @@ def append_event(page_dir: Path, event: dict) -> dict:
174164
with open(log, "a", encoding="utf-8"):
175165
pass
176166
with flocked(log) as f:
177-
return _append_event_unlocked(f, event)
167+
f.seek(0)
168+
events = _parse_events(f.read())
169+
accepted, _appended = _append_event_unlocked(f, event, events)
170+
return accepted
178171

179172

180-
def read_events(page_dir: Path) -> list:
181-
path = page_dir / "comments.jsonl"
182-
if not path.exists():
183-
return []
173+
def _parse_events(data: bytes) -> list[dict]:
184174
events = []
185175
# The log's grammar is events joined by "\n" — the writer's own separator,
186176
# not splitlines()'s wider class, which once read a U+2028 inside a comment's
@@ -189,7 +179,7 @@ def read_events(page_dir: Path) -> list:
189179
# mid-line (ensure_ascii=False writes multi-byte UTF-8), and one strict
190180
# read_text of the file would raise on the tear before any line-level
191181
# tolerance could reach it.
192-
lines = path.read_bytes().split(b"\n")
182+
lines = data.split(b"\n")
193183
if lines and lines[-1] == b"":
194184
lines.pop()
195185
for i, line in enumerate(lines):
@@ -208,3 +198,10 @@ def read_events(page_dir: Path) -> list:
208198
event["seq"] = i + 1
209199
events.append(event)
210200
return events
201+
202+
203+
def read_events(page_dir: Path) -> list:
204+
path = page_dir / "comments.jsonl"
205+
if not path.exists():
206+
return []
207+
return _parse_events(path.read_bytes())

‎skills/leaf/scripts/leaf/service.py‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77
from leaf.event_log import (
88
_append_event_unlocked,
99
_matching_attempt,
10+
_parse_events,
1011
flocked,
1112
now_iso,
1213
read_cursor,
13-
read_events,
1414
)
1515
from leaf.files import read_json, write_json
1616
from leaf.host import (
@@ -61,8 +61,10 @@ def __init__(self, page_dir: Path):
6161
self.page_dir = page_dir.resolve()
6262
self._lock = None
6363
self._log = None
64+
self._events = None
6465

6566
def __enter__(self):
67+
self._events = None
6668
self._lock = flocked(self.page_dir / "comments.jsonl")
6769
self._log = self._lock.__enter__()
6870
return self
@@ -191,15 +193,25 @@ def set_status(
191193

192194
@property
193195
def events(self) -> list:
194-
return read_events(self.page_dir)
196+
if self._events is None:
197+
self._log.seek(0)
198+
self._events = _parse_events(self._log.read())
199+
return self._events
195200

196201
def matching_attempt(self, event: dict) -> dict | None:
197202
"""An accepted retry, read under this transaction's log lease."""
198-
return _matching_attempt(self._log, event)
203+
return _matching_attempt(self.events, event)
199204

200205
def append_event(self, event: dict) -> dict:
201206
"""Append under this transaction without re-entering its log lease."""
202-
return _append_event_unlocked(self._log, event)
207+
try:
208+
accepted, appended = _append_event_unlocked(self._log, event, self.events)
209+
except Exception:
210+
self._events = None
211+
raise
212+
if appended:
213+
self._events = None
214+
return accepted
203215

204216
@property
205217
def cursor(self) -> int:

‎tests/test_interact_server.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2375,6 +2375,29 @@ def test_a_torn_tail_is_isolated_and_the_log_keeps_reading(page_dir):
23752375
]
23762376

23772377

2378+
def test_a_transaction_reloads_after_an_append_fault_that_may_have_landed(
2379+
page_dir, monkeypatch
2380+
):
2381+
"""A writer can fail after durable bytes land; the transaction must read them."""
2382+
real_fsync = event_model.os.fsync
2383+
2384+
def sync_then_fail(fd):
2385+
real_fsync(fd)
2386+
raise OSError("failed after syncing")
2387+
2388+
with service_model.PageTransaction(page_dir) as page:
2389+
assert page.events == []
2390+
with monkeypatch.context() as patch:
2391+
patch.setattr(event_model.os, "fsync", sync_then_fail)
2392+
with pytest.raises(OSError, match="failed after syncing"):
2393+
page.append_event(
2394+
{"kind": "comment", "author": "user", "text": "landed"}
2395+
)
2396+
assert [(event["text"], event["seq"]) for event in page.events] == [
2397+
("landed", 1)
2398+
]
2399+
2400+
23782401
def test_a_reader_without_the_key_reads_and_writes_nothing(server, page_dir):
23792402
"""The page is served wherever the SSH session reached this machine, so the
23802403
port is open to whatever else is on that network. Reading is half of it: the

0 commit comments

Comments
 (0)