EverOS icon indicating copy to clipboard operation
EverOS copied to clipboard

[Bug]: cascade claims carry no fence; a slow drainer's stale write lands over a newer one and the row stays done

Open gloryfromca opened this issue 1 month ago • 1 comments

Area

src/everos

What happened?

A cascade claim carries no token or lease, and the terminal writes only check status='processing' (src/everos/infra/persistence/sqlite/repos/md_change_state.py:299-323 mark_done, :325-370 mark_failed). That guard protects the row's status, not the index writes that precede it. With two drainers on one md_change_state table — the service's worker loop plus drain_fully from POST /cascade/quiesce, or cascade sync during the startup window orchestrator.py:80-86, or the startup recover_orphan_processing (:374-390) handing a live claim to the new worker (item 3 of #542) — this sequence loses the newer write:

  1. A claims the row (claim_pending_batch) and its handler reads v1 of the file (handlers/_daily_log_base.py:103-116); the embedding call is slow.
  2. The file changes to v2; the watcher resets the row to pending with mtime m2.
  3. B claims the row, writes v2 into the index, mark_done → done / m2.
  4. A's handler writes v1's rows over B's (_apply_lance_changes, :221-231); A's mark_done is the intended no-op.

The row says done at v2's mtime while the index holds v1's content, and nothing rescans it: the reconciler skips a done row whose mtime matches the file. Only a later edit (new mtime) repairs it. Item 2 of #542, now replayed.

Expected: a stale claim's index writes must not take effect. Either the claim carries a fence (token or lsn) that the handler's index writes and the terminal write both check, or the worker re-reads the row before writing and re-enqueues instead of writing when it was reset. Alternatively the second drainer is simply excluded: claim_pending_batch is written for sibling workers racing on the same prefix ("each row lands in exactly one batch"), but that only serializes the claim, not the writes behind it.

Steps to reproduce

Replay on the real components: two CascadeWorkers with real EpisodeHandlers on one real md_change_state repository and one LanceDB table. A's handler gets an index proxy that pauses before its first index write (the slow embedding call in production); everything else is real.

  1. v0 (alpha0) written, scanned, drained → done, index e1 = alpha0.
  2. File edited to alpha1 (mtime m1), watcher-equivalent upsert modified m1; worker_a.drain_once() started as a task; it claims the row and reads v1, then blocks before writing: row=processing mtime=m1.
  3. File edited to alpha2 + a second entry appended (mtime m2), upsert modified m2; worker_b.drain_once() → row=done mtime=m2, index e1='alpha2', entries=2.
  4. A released → cascade_worker_processed ... upserted=1; row=done mtime=m2, index e1='alpha1' while the file says alpha2.
  5. scan_once() + drain_once() → no change, index e1='alpha1'.
  6. Control: os.utime(m2 + 60), scan + drain → index e1='alpha2'.
replay test (~2 s, real scanner / worker / EpisodeHandler / SQLite / LanceDB; run with uv run pytest <file> -q -s)
"""Replay of #542 item 2: claims carry no token or lease, and the terminal
writes only check ``status='processing'``.

Two drainers share one ``md_change_state`` (the service's worker loop plus
``drain_fully`` from ``POST /cascade/quiesce``, or ``cascade sync`` during the
startup window). A claims the row and its handler has already read v1 of the
file when the file changes to v2; the watcher resets the row to ``pending``
(md_change_state.py upsert), B claims it, writes v2 into the index and
``mark_done``s. A then writes v1's rows over B's; A's ``mark_done`` is a no-op
(row is ``done``, not ``processing``). The row says ``done`` at v2's mtime while
the index holds v1: nothing rescans it. Control: a later edit repairs it.

A's handler is the real EpisodeHandler; the only stand-in is an index proxy that
pauses A between its read and its first index write (that gap is the slow
embedding call in production).

Run: uv run pytest .work_context/replay_542/test_replay_2_two_drainers_stale_claim.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 (
    MarkdownReader,
    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
M0, M1, M2 = 1_700_000_000.0, 1_700_000_100.0, 1_700_000_200.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]


class _GatingIndex:
    """The real index repo, but the first write waits for ``go``."""

    def __init__(self, inner: Any) -> None:
        self._inner = inner
        self.reached = asyncio.Event()
        self.go = asyncio.Event()

    def __getattr__(self, name: str) -> Any:
        return getattr(self._inner, name)

    async def _gate(self) -> None:
        self.reached.set()
        await self.go.wait()

    async def upsert(self, rows: Any) -> Any:
        await self._gate()
        return await self._inner.upsert(rows)

    async def delete(self, pred: Any) -> Any:
        await self._gate()
        return await self._inner.delete(pred)


def _entry(owner: str, n: int, content: str) -> 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": content},
    )


def _rewrite(path: Path, old: str, new: str, mtime: float) -> None:
    text = path.read_text(encoding="utf-8")
    assert text.count(old) == 1, old
    path.write_text(text.replace(old, new), encoding="utf-8")
    os.utime(path, (mtime, mtime))


async def _replay() -> None:
    tmp = Path(tempfile.mkdtemp(prefix="replay542_2_"))
    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)
        deps = HandlerDeps(memory_root=root, tokenizer=_Tokenizer())
        handler_a = EpisodeHandler(deps)
        gate = _GatingIndex(index)
        handler_a.index_repo = gate  # instance attribute shadows the ClassVar
        handler_b = EpisodeHandler(deps)
        kw = dict(
            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,
        )
        worker_a = CascadeWorker({"episode": handler_a}, **kw)
        worker_b = CascadeWorker({"episode": handler_b}, **kw)
        date = dt.date(2026, 5, 14)
        rel = f"default_app/default_project/users/u1/episodes/episode-{date.isoformat()}.md"
        path = root.root / rel

        async def row() -> Any:
            return next(r for r in await state_repo.list_all() if r.md_path == rel)

        async def index_text() -> dict[str, str]:
            return {
                r.entry_id: r.episode
                for r in await index.find_where(eq("md_path", rel), limit=100)
            }

        # v0 indexed and done
        await writer.append_entries("u1", [_entry("u1", 1, "alpha0")], date=date)
        os.utime(path, (M0, M0))
        await scanner.scan_once()
        await worker_b.drain_once()
        e1 = (await MarkdownReader.read(path)).entries[0].id
        assert (await row()).status == "done" and "alpha0" in (await index_text())[e1]

        # v1: the user edits the entry; the watcher re-enqueues; A claims and reads v1
        _rewrite(path, "alpha0", "alpha1", M1)
        await state_repo.upsert(rel, kind="episode", change_type="modified", mtime=M1)
        task_a = asyncio.create_task(worker_a.drain_once())
        await asyncio.wait_for(gate.reached.wait(), timeout=10)
        r = await row()
        print(f"  A claimed and read v1: row={r.status} mtime={r.mtime:.0f}")
        assert r.status == "processing"

        # v2 lands while A is still working: watcher resets to pending; B claims, writes v2, mark_done
        _rewrite(path, "alpha1", "alpha2", M2)
        await writer.append_entries("u1", [_entry("u1", 2, "beta")], date=date)
        os.utime(path, (M2, M2))
        await state_repo.upsert(rel, kind="episode", change_type="modified", mtime=M2)
        n = await worker_b.drain_once()
        r = await row()
        idx = await index_text()
        print(
            f"  B drained {n} row: row={r.status} mtime={r.mtime:.0f}, index e1={idx[e1]!r:.40}, entries={len(idx)}"
        )
        assert n == 1 and r.status == "done" and "alpha2" in idx[e1] and len(idx) == 2

        # A wakes up and writes v1's rows; its mark_done is a no-op
        gate.go.set()
        await asyncio.wait_for(task_a, timeout=10)
        r = await row()
        idx = await index_text()
        print(
            f"  A finished: row={r.status} mtime={r.mtime:.0f}, index e1={idx[e1]!r:.40}, file has alpha2={'alpha2' in path.read_text()}"
        )
        assert r.status == "done" and abs(r.mtime - M2) < 1e-6
        assert "alpha1" in idx[e1], "index holds A's stale v1 content"

        # nothing rescans it: file mtime == row mtime and the row is done
        await scanner.scan_once()
        await worker_b.drain_once()
        idx = await index_text()
        print(f"  after scan + drain: index e1={idx[e1]!r:.40}")
        assert "alpha1" in idx[e1]

        # control: a real edit repairs it
        os.utime(path, (M2 + 60, M2 + 60))
        await scanner.scan_once()
        await worker_b.drain_once()
        idx = await index_text()
        print(f"  control, after touch + scan + drain: index e1={idx[e1]!r:.40}")
        assert "alpha2" in idx[e1]
    finally:
        for p in patches:
            p.stop()
        await engine.dispose()
        shutil.rmtree(tmp, ignore_errors=True)


def test_stale_claim_overwrites_newer_write_and_nothing_rescans() -> None:
    asyncio.run(_replay())

Relation to other issues

#542 items 2 and 3 (item 3, startup orphan recovery reclaiming a live claim, feeds the same unfenced write path 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)

  1. Fence the claim: claim_pending_batch returns the row's lsn as a token; the handler's index writes and mark_done / mark_failed carry it, a write with a stale token is dropped and the row re-enqueued.
  2. Cheaper: re-read the row right before _apply_lance_changes and abandon the write (leave the row pending) when its lsn or mtime changed since the claim.
  3. Startup recovery should not reset a row claimed by a live process (a lease on last_attempt_at, or the single-process assumption enforced by the OME lock before the worker starts; today the worker starts at lifespan order 12, the lock is taken at 50).

gloryfromca avatar Oct 30 '26 09:10 gloryfromca

I'd like to take this. I'm going with the re-read/re-enqueue option you listed: after the handler, re-read the row. If it is pending or owned by a newer processor, drop the stale verdict; if it already reached done/failed, re-enqueue it as modified so the next drain rewrites from md. A full claim fence can be a follow-up.

chuiwenwei avatar Nov 05 '26 09:11 chuiwenwei