Files
gabrielvidalandClaude Opus 5.5 be24545e21 perf(indexer): copy only a grown transcript's new bytes into the archive
A live transcript is re-imported every couple of seconds and shutil.copy2
rewrote all of it each time (100 MB for one new line on the biggest). Every
writer of the source dirs appends, so tailcopy.sync appends the bytes past the
archive copy's end when the 4 KB before it still match, and falls back to a
full copy when the source shrank, was rewritten, or only its mtime moved. An
flock on the destination keeps the watcher, the indexer's sweep and a
blue-green standby (two backends share the archive) from duplicating a tail.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-26 23:03:24 +01:00

63 lines
2.5 KiB
Python

"""Bring an archived transcript level with its live source, appending.
A live transcript is re-imported every couple of seconds while its session
runs, and a whole-file ``shutil.copy2`` re-wrote all of it each time — 100 MB
for one new line on the biggest. Every writer of the source dirs appends
(Claude Code, the opencode / pi mirrors, the workers' FeedMirror), so when
the source only grew, only the bytes past the archive copy's end are copied.
Anything else — it shrank, it was rewritten at the same size, the bytes
before the copy's end no longer match — is a full copy, as before.
"""
import fcntl
import os
import shutil
# How much of the bytes just before the copy's end must match for the source
# to count as the same file grown (a rewrite almost never keeps them).
_CHECK = 4096
_CHUNK = 1 << 20
def _copy_range(sfd: int, dfd: int, start: int, end: int) -> None:
"""``src[start:end]`` → ``dst`` at ``start``."""
os.lseek(dfd, start, os.SEEK_SET)
off = start
while off < end:
try:
n = os.sendfile(dfd, sfd, off, min(_CHUNK, end - off))
except OSError: # no sendfile between these two: read + write
buf = os.pread(sfd, min(_CHUNK, end - off), off)
n = os.write(dfd, buf) if buf else 0
if n <= 0:
break # the source shrank under us: the next sync redoes it
off += n
def sync(src, dst) -> None:
"""Make ``dst`` a copy of ``src`` (bytes, then ``copystat`` — what
``shutil.copy2`` leaves), appending when ``src`` only grew.
Holds an ``flock`` on ``dst`` throughout: the watcher and the indexer's
sweep both import, and during a blue-green deploy two backends share the
archive — two appends that read the same end would duplicate the tail.
The end is re-read under the lock, so the second one copies only what is
still missing. Raises OSError like ``copy2``."""
fd = os.open(dst, os.O_RDWR | os.O_CREAT, 0o644)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
with open(src, "rb") as fin:
sfd = fin.fileno()
end = os.fstat(sfd).st_size
have = os.fstat(fd).st_size
if have:
n = min(_CHECK, have)
if have >= end or os.pread(sfd, n, have - n) != os.pread(fd, n, have - n):
have = 0
if have == 0:
os.ftruncate(fd, 0)
_copy_range(sfd, fd, have, end)
shutil.copystat(src, dst)
finally:
os.close(fd) # drops the lock