The indexer's live states (`Indexer._live`) and the thread cache (`routes._detail_cache`) fed a ParserState from its last byte offset and reset only when the file shrank, so a rewrite that kept or grew the file was fed from the old offset: the new bytes on top of the old records. Each state now keeps a `conversations/rewrite.py` Mark: the (mtime, size) of the stat before its read and the hashes of the first 4 KB and of the 4 KB before its offset (tailcopy.sync's check). It resumes only while the file grew and both hashes match; a shrink, or a change without growth (same size, new mtime), starts over from byte 0, and the thread's next delta replaces the whole thread. A rewrite that lands during a read (the head moved under it) is read again from the top at once, since the kernel's ~4 ms mtime clock may not show it afterwards. Needed by the v1 converter (step 1c), which rewrites past pi / opencode / agy transcripts in place. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
122 lines
4.8 KiB
Python
122 lines
4.8 KiB
Python
"""Is a transcript still the file a resumable parse was fed from?
|
|
|
|
The indexer (``Indexer._live``) and the thread cache
|
|
(``conversations/routes._detail_cache``) keep a ``ParserState`` and the byte
|
|
offset it has read up to, and feed it only what was appended (CLAUDE.md →
|
|
Performance, rule 2): every writer appends. But a transcript is sometimes
|
|
rewritten in place — a converter moving a harness's past files to the v1
|
|
format, a hand fix of old records, the archive's full re-copy of either — and
|
|
one that left the file at least as long as that offset was fed from it: the
|
|
new bytes on top of the old records, counted twice. Only a shrink reset.
|
|
|
|
A :class:`Mark` is taken when a state reaches an offset: the file's
|
|
(mtime, size) at the stat before that read, the hash of its first 4 KB (a
|
|
format change rewrites the header) and the hash of the 4 KB just before the
|
|
offset (any edit that changes a length shifts them — the check
|
|
``tailcopy.sync`` makes before appending). A state resumes only while the
|
|
file grew and both hashes still match; a file that shrank, or changed without
|
|
growing (same size, new mtime: rewritten at the same length, or touched),
|
|
starts over from byte 0. A rewrite that lands *during* a read (the head moved
|
|
between before and after it) is read again from the top at once. Unseen: an
|
|
edit that keeps every length *and* misses both windows *and* comes with an
|
|
append — the state keeps the old bytes until it is evicted or the backend
|
|
restarts.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import os
|
|
import pathlib
|
|
from typing import Callable, NamedTuple
|
|
|
|
from conversations.parse import feed_lines
|
|
|
|
WINDOW = 4096
|
|
|
|
|
|
class Mark(NamedTuple):
|
|
mtime: float
|
|
size: int
|
|
head: bytes # hash of bytes [0, min(WINDOW, offset))
|
|
tail: bytes # hash of bytes [offset - WINDOW, offset)
|
|
|
|
|
|
def _digest(b: bytes) -> bytes:
|
|
return hashlib.blake2b(b, digest_size=8).digest()
|
|
|
|
|
|
def _windows(path: pathlib.Path, offset: int) -> tuple[bytes, bytes] | None:
|
|
try:
|
|
fd = os.open(path, os.O_RDONLY)
|
|
except OSError:
|
|
return None
|
|
try:
|
|
n = min(WINDOW, offset)
|
|
return (_digest(os.pread(fd, n, 0)),
|
|
_digest(os.pread(fd, n, offset - n)))
|
|
except OSError:
|
|
return None
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
def _head(path: pathlib.Path, size: int) -> bytes | None:
|
|
try:
|
|
with path.open("rb") as fh:
|
|
return _digest(fh.read(min(WINDOW, size)))
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
def take(path: pathlib.Path, offset: int, mtime: float, size: int) -> Mark | None:
|
|
"""The mark of a state fed to ``offset`` from the file as statted at
|
|
(``mtime``, ``size``) just before that read. None when unreadable."""
|
|
w = _windows(path, offset)
|
|
return None if w is None else Mark(mtime, size, *w)
|
|
|
|
|
|
def holds(mark: Mark | None, path: pathlib.Path, offset: int,
|
|
mtime: float, size: int) -> bool:
|
|
"""May a state fed to ``offset`` (and marked ``mark``) take the file as it
|
|
is now — (``mtime``, ``size``) — from ``offset`` on?"""
|
|
if mark is None or size < offset or size < mark.size:
|
|
return False # never marked, or shrank
|
|
if size == mark.size:
|
|
return mtime == mark.mtime # changed without growing: rewritten
|
|
return _windows(path, offset) == (mark.head, mark.tail)
|
|
|
|
|
|
def advance(path: pathlib.Path, state, offset: int, mark: Mark | None,
|
|
mtime: float, size: int, fresh: Callable[[], object]):
|
|
"""Bring a resumable parse up to the end of ``path``.
|
|
|
|
Feeds ``state`` what was appended since ``offset`` — or, when the file is
|
|
no longer the one it was fed from, a ``fresh()`` state from byte 0.
|
|
``mtime`` / ``size`` are the caller's stat, taken before this call. A file
|
|
rewritten *while* it is read (its head moved under the read) is read once
|
|
more from the top at once: its mtime may not even have moved (the kernel
|
|
stamps it from a ~4 ms clock), so nothing would say so later.
|
|
Returns ``(state, offset, mark, restarted)``; ``mark`` is None when even
|
|
that second read raced a rewrite (don't resume that state). None when the
|
|
file can't be read."""
|
|
restarted = offset > 0 and not holds(mark, path, offset, mtime, size)
|
|
if restarted:
|
|
state, offset = fresh(), 0
|
|
for last in (False, True):
|
|
before = _head(path, size)
|
|
new_off = feed_lines(state, path, offset)
|
|
if new_off is None or before is None:
|
|
return None
|
|
new_mark = take(path, new_off, mtime, size)
|
|
if new_mark is not None and _head(path, size) == before:
|
|
return state, new_off, new_mark, restarted
|
|
if last:
|
|
return state, new_off, None, restarted
|
|
try:
|
|
st = os.stat(path)
|
|
except OSError:
|
|
return None
|
|
state, offset, restarted = fresh(), 0, True
|
|
mtime, size = st.st_mtime, st.st_size
|