[Bug]: cascade scanner walking during a rename gap writes a tombstone with the file's real mtime; the file is never indexed again
Area
src/everos
What happened?
CascadeScanner.scan_once() walks the tree first and reads the md_change_state snapshot after (src/everos/memory/cascade/scanner.py:90-93). When a path is absent for the duration of the walk (an editor or sync tool that replaces the file by rename, mv out and back) and the watcher's upsert for the landed file reaches the table before the snapshot read, the reconciler sees "in state, not on disk" and emits deleted carrying prior.mtime (reconciler.py:130), which is the landed file's real mtime. The worker then wipes the index rows of an already-indexed file (nothing to wipe for a new one) and mark_done leaves the row as done / deleted / mtime = m2. Every later scan finds the file on disk with that same mtime and a done row and skips it: reconciler.py:96-102 compares mtime and status only, never change_type. The file is on disk, the index has nothing for it, cascade status is clean. Only a real edit (new mtime) repairs it.
Same root cause as #541 (a tombstone that carries the file's real mtime, trusted forever by the reconciler), different entry point: there the worker folded a missing file into a deletion, here the scanner does. Item 1 of #542, now replayed.
Expected (test_cascade_projection_stateful: after a sync the index equals the files): a present file is indexed after a scan, and an indexed file's rows are not removed while the file exists.
Scope: the walk is Path.glob over the whole root inside asyncio.to_thread, so it takes seconds on a large root, and the watcher's upsert is processed on the event loop while that thread runs. Rename-replacing editors, rsync, and mv-based restores produce the gap routinely.
Steps to reproduce
Replay on the real components (temp memory root, real md_change_state repository, real CascadeScanner / CascadeWorker / EpisodeHandler on a temp LanceDB table, fixed-vector embedder). Two files: old already indexed, new not yet.
oldis written, scanned and drained: rowdone / added, index rows 1.- Both files are replaced (new content, mtime
m2). The scan runs with_collect_scan_inputswrapped so both paths are renamed away for the walk and back afterwards, and_load_state_snapshotwrapped so the watcher's two upserts (old: modified m2,new: added m2) land before the snapshot is read. Decisions:[('old', 'deleted', m2), ('new', 'deleted', m2)]. drain_once()→cascade_worker_processed change_type=deleted deleted=1forold,deleted=0fornew; both rowsdone / deleted / mtime = m2; index rows 0 for both.- Two more plain
scan_once()+drain_once()passes: no decisions for either path; index rows stay 0 while both files are on disk. - Control:
os.utime(old, m2 + 60), scan + drain →modified, index rows 2.
replay test (~2 s, real scanner / worker / EpisodeHandler / SQLite / LanceDB; run with uv run pytest <file> -q -s)
"""Replay of #542 item 1: the scanner walks the tree while a file is briefly
absent (editor replaces it by rename), the watcher's upsert for the new file
lands before the scanner reads its state snapshot, and the reconciler turns the
"in state, not on disk" row into a ``deleted`` decision that carries the real
mtime (reconciler.py:130 copies ``prior.mtime``). The worker wipes the index
rows and ``mark_done`` leaves ``done / deleted / m2``; from then on every scan
sees the file on disk with the same mtime and a ``done`` row and skips it
(reconciler.py:96-102 looks at mtime and status only).
Two files: ``new`` (never indexed before the gap) and ``old`` (already indexed;
its index rows are wiped). Control: a later edit (new mtime) is picked up.
Run: uv run pytest .work_context/replay_542/test_replay_1_scan_during_rename_gap.py -q -s
"""
from __future__ import annotations
import asyncio
import datetime as dt
import os
import shutil
import tempfile
from pathlib import Path
from typing import Any
from unittest import mock
from sqlmodel import SQLModel
import everos.component.embedding.accessor as acc
from everos.component.embedding import EmbeddingCapability, EmbeddingProvider
from everos.component.tokenizer import Tokenizer
from everos.config import LanceDBSettings, SqliteSettings
from everos.core.persistence import (
MemoryRoot,
create_session_factory,
create_system_engine,
)
from everos.core.persistence.lancedb import LanceRepoBase, open_lancedb_connection
from everos.infra.persistence.index import Episode
from everos.infra.persistence.lancedb.repos.episode import _EpisodeRepo
from everos.infra.persistence.markdown import EpisodeWriter
from everos.infra.persistence.predicate import eq
from everos.infra.persistence.sqlite.repos.md_change_state import _MdChangeStateRepo
from everos.memory.cascade import scanner as scanner_mod
from everos.memory.cascade import worker as worker_mod
from everos.memory.cascade.handlers import HandlerDeps
from everos.memory.cascade.handlers.episode import EpisodeHandler
from everos.memory.cascade.scanner import CascadeScanner
from everos.memory.cascade.worker import CascadeWorker
DIM = 1024
M_OLD = 1_700_000_000.0
M_NEW = 1_700_000_100.0
class _Tokenizer(Tokenizer):
def tokenize(self, text: str) -> list[str]:
return [t for t in text.split() if t]
def tokenize_batch(self, texts: Any) -> list[list[str]]:
return [self.tokenize(t) for t in texts]
class _Embedder(EmbeddingProvider):
dim = DIM
async def embed(self, text: str) -> list[float]:
return [0.1] * DIM
async def embed_batch(self, texts: Any) -> list[list[float]]:
return [await self.embed(t) for t in texts]
def _entry(owner: str, n: int) -> tuple[dict[str, Any], dict[str, Any]]:
return (
{
"owner_id": owner,
"session_id": "s1",
"timestamp": "2026-05-14T10:00:00+00:00",
"parent_type": "memcell",
"parent_id": f"mc_{n}",
"sender_ids": [owner],
},
{"Subject": "T", "Summary": "S", "Content": f"content {n}"},
)
async def _replay() -> None:
tmp = Path(tempfile.mkdtemp(prefix="replay542_1_"))
root = MemoryRoot(tmp / "root")
root.ensure()
engine = create_system_engine(root.system_db, SqliteSettings())
factory = create_session_factory(engine)
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
state_repo = _MdChangeStateRepo(session_factory=factory)
LanceRepoBase._reset_locks_for_tests()
conn = await open_lancedb_connection(root.lancedb_dir, LanceDBSettings())
table = await conn.create_table(Episode.TABLE_NAME, schema=Episode)
index = _EpisodeRepo(table=table)
acc._capability = EmbeddingCapability(provider=_Embedder())
patches = [
mock.patch.object(scanner_mod, "md_change_state_repo", state_repo),
mock.patch.object(scanner_mod, "get_session_factory", lambda: factory),
mock.patch.object(worker_mod, "md_change_state_repo", state_repo),
mock.patch.object(EpisodeHandler, "index_repo", index),
]
for p in patches:
p.start()
try:
writer = EpisodeWriter(root)
scanner = CascadeScanner(root, scan_interval_seconds=3600.0)
handler = EpisodeHandler(HandlerDeps(memory_root=root, tokenizer=_Tokenizer()))
worker = CascadeWorker(
{"episode": handler},
batch_size=10,
handler_concurrency=1,
max_retry=0,
retry_backoff_seconds=0.0,
poll_interval_seconds=3600.0,
optimize_min_interval_seconds=0.0,
optimize_heartbeat_seconds=3600.0,
optimize_rebuild_interval_seconds=3600.0,
)
date = dt.date(2026, 5, 14)
rel_old = f"default_app/default_project/users/old/episodes/episode-{date.isoformat()}.md"
rel_new = f"default_app/default_project/users/new/episodes/episode-{date.isoformat()}.md"
path_old, path_new = root.root / rel_old, root.root / rel_new
async def row(rel: str) -> Any:
return next(
(r for r in await state_repo.list_all() if r.md_path == rel), None
)
async def indexed(rel: str) -> int:
return len(await index.find_where(eq("md_path", rel)))
# ``old`` exists and is indexed; ``new`` does not exist yet
await writer.append_entries("old", [_entry("old", 1)], date=date)
os.utime(path_old, (M_OLD, M_OLD))
await scanner.scan_once()
await worker.drain_once()
r = await row(rel_old)
assert (r.status, r.change_type) == ("done", "added") and (
await indexed(rel_old)
) == 1
# the editor replaces both files by rename: for a moment neither path exists.
# old gets new content + mtime M_NEW; new is created with mtime M_NEW
await writer.append_entries("new", [_entry("new", 2)], date=date)
await writer.append_entries("old", [_entry("old", 3)], date=date)
os.utime(path_old, (M_NEW, M_NEW))
os.utime(path_new, (M_NEW, M_NEW))
real_walk = scanner_mod._collect_scan_inputs
real_snapshot = scanner_mod._load_state_snapshot
def walk_during_gap(root_dir: Path, kinds: Any = None) -> Any:
# the walk happens while both paths are absent
parked = [
(p, tmp / f"parked_{i}.md") for i, p in enumerate((path_old, path_new))
]
for p, q in parked:
os.rename(p, q)
try:
return real_walk(root_dir, kinds)
finally:
for p, q in parked:
os.rename(q, p)
async def snapshot_after_watcher() -> Any:
# the watcher's events for the landed files are processed on the loop
# while the walk thread is still running -> they reach the table before
# the scanner reads its snapshot (scanner.py:90-93 walks first, reads after)
await state_repo.upsert(
rel_old, kind="episode", change_type="modified", mtime=M_NEW
)
await state_repo.upsert(
rel_new, kind="episode", change_type="added", mtime=M_NEW
)
return await real_snapshot()
with (
mock.patch.object(scanner_mod, "_collect_scan_inputs", walk_during_gap),
mock.patch.object(
scanner_mod, "_load_state_snapshot", snapshot_after_watcher
),
):
decisions = await scanner.scan_once()
print(
" scan decisions:",
[(d.md_path.split("/")[3], d.change_type, int(d.mtime)) for d in decisions],
)
assert path_old.exists() and path_new.exists()
assert {(d.md_path, d.change_type) for d in decisions} >= {
(rel_old, "deleted"),
(rel_new, "deleted"),
}
await worker.drain_once()
for rel in (rel_old, rel_new):
r = await row(rel)
print(
f" after drain: {rel.split('/')[3]} row={r.status}/{r.change_type} mtime={r.mtime:.0f} index rows={await indexed(rel)}"
)
assert (r.status, r.change_type) == ("done", "deleted") and abs(
r.mtime - M_NEW
) < 1e-6
assert (await indexed(rel_old)) == 0, "the indexed file's rows were wiped"
# later normal scans: both files on disk, mtime == row mtime, row done -> skipped forever
for _ in range(2):
d = await scanner.scan_once()
assert not [x for x in d if x.md_path in (rel_old, rel_new)]
await worker.drain_once()
print(
f" after two normal scans: old index rows={await indexed(rel_old)}, new index rows={await indexed(rel_new)}"
)
assert (await indexed(rel_old)) == 0 and (await indexed(rel_new)) == 0
# control: a real edit (new mtime) is picked up again
os.utime(path_old, (M_NEW + 60, M_NEW + 60))
await scanner.scan_once()
await worker.drain_once()
print(
f" control, after touch + scan + drain: old index rows={await indexed(rel_old)}"
)
assert (await indexed(rel_old)) == 2
finally:
for p in patches:
p.stop()
await engine.dispose()
shutil.rmtree(tmp, ignore_errors=True)
def test_scan_during_rename_gap_writes_tombstone_with_real_mtime() -> None:
asyncio.run(_replay())
Relation to other issues
#541 (same root cause, worker side), #542 (item 1; item 7, an unreadable subtree reconciled as deletion, goes through the same reconciler.py:130 tombstone and is not replayed separately).
Environment
OS: macOS 15 (Darwin 24.6.0)
Python: 3.12
Commit: 5b0979b (v1.5.1)
Possible fixes (not decided)
- Read the state snapshot before the walk (or only emit
deletedfor rows that were already in a pre-walk snapshot), so an upsert that lands during the walk cannot be turned into a tombstone. - Same as #541: a tombstone should not carry the file's real mtime, and the reconciler should re-enqueue a present file whose row is
done + deletedasaddedregardless of mtime.
I'd like to take this. I can reproduce the rename-gap tombstone with the replay in the issue. I'll make the scanner re-stat a would-be deletion at decision time: present -> modified with the current mtime, absent -> deleted, keeping the all-or-nothing OSError rule.