* fix(lancedb): reclaim stale versions via write-locked prune The storage soak (48h, sustained churn + fuzz) proved the bundled lock-free `optimize(cleanup_older_than=...)` loses its commit-conflict race against concurrent writes — cleanup ran only 16 of ~250 times, so old dataset versions / FTS orphans piled up and the index dir grew to the 40G disk guardrail and never reclaimed under load. main still had that bundled call. Split the maintenance path: - `LanceRepoBase.optimize()` is now compact-only and lock-free (a commit conflict here is benign — the next beat retries, so it must not stall writers). - `LanceRepoBase.prune(older_than)` runs `cleanup_older_than + delete_unverified=True` **under the per-table write lock**, so no writer is in flight: the Rewrite has the manifest to itself (cleanup completes every beat) and aggressive deletion is safe. It also removes the empty `_indices/<uuid>/` husks cleanup leaves behind (soak: 13061 dirs, 98% empty), offloaded to a thread. - The cascade worker's heavy beat calls `prune()`; the light beat calls `optimize()`. A benign light-beat commit conflict is logged at debug and does not count toward the failure streak or trigger a rebuild. - Prune's retention window (`cleanup_older_than`) is decoupled from the prune cadence and defaulted short (60s). It runs under the write lock, so the window only needs to outlive an in-flight read; keeping it = cadence (300s) left ~2 cadences of superseded full-table copies on disk between beats (soak: transient ~15G/table peaks). 60s reclaims all but the last minute each beat — same live floor (~625MB/table), far lower transient footprint. Result on the re-run soak: disk sawtooths and reclaims to live-data size (~1.3G total) under active load — vs run1 stuck at 40G until writes stopped — with 0 crashes / 0 OOM / 0 stuck cleanups over 48h. Cascade projection health is now observable: - `CascadeOrchestrator.health()` -> `CascadeHealth`, combining the worker's in-memory signals (drain-loop failures, unrecoverable count, optimize streak, prune staleness) with the SQLite queue summary. - `GET /health` gains a typed `cascade` readiness block. `healthy` reflects operational health only (drain / optimize / prune); `failed_permanent` (files awaiting `cascade fix`) is a data-quality backlog reported as an informational count that does NOT flip `healthy` — otherwise the signal would sit red permanently. The scanner-side retry cap and the `_MAX_TOTAL_RETRIES` budget already on main handle re-enqueue storms, so no duplicate is added here. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(deps): pin lancedb to >=0.34.0,<0.35.0 The previous open-ended `>=0.13.0` let any environment float to an untested release, including 0.32-0.34 which carry a compaction offset-overflow regression (lance-format/lance#7653) that stalls version cleanup and grows the index dir without bound. - Floor 0.34.0: the current resolved version; runs safely thanks to the with_position=False FTS workaround shipped in #336. Verified that data written by lancedb 0.32.0 (lance v6) reads correctly under 0.34.0 (lance v8), so existing deployments upgrade cleanly. Never widen the floor below 0.34 -- older lance cannot read v8-format data. - Ceiling <0.35.0: 0.35 embeds lance-rust v9 (large encoding jump, not yet stable-released); it must pass the soak harness before we allow it. Resolved version is unchanged (still 0.34.0); this only tightens the declared constraint. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> (cherry picked from commit 94f9aa67d11a07c93c7d59d6b134e80858b60316) * fix(search): bridge agent-kind metadata into the agentic doc contract The agent AGENTIC path (`agent_case` / `agent_skill`) fed recall candidates straight into `aagentic_retrieve`, whose `_format_docs` (LLM sufficiency / multi-query prompt) reads `metadata["episode"]` as a `{subject, content}` dict plus a ms-epoch `timestamp`. Agent-kind rows carry their body in the recaller's `text_field` and time as a datetime, so `_format_docs` raised `TypeError: Candidate ... has no episode dict` and `POST /api/v*/memory/search` returned 500 for any `owner_type=agent` + `method=agentic` request. Mirror the episode path's bridge: reshape agent candidate metadata into the everalgo doc contract before `aagentic_retrieve`, and revert it before DTO shaping so the agent shapers still see a datetime timestamp. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> (cherry picked from commit bb9a3a585e044643d3852b9d2810b42c05a7a47c) * test(search): regenerate search seed to current linkage + migrate e2e The committed `search_seed` fixture and several search e2e tests were written for the pre-1.5 memcell fact-linkage model. Current extraction links atomic_facts to episodes via `parent_id == episode.entry_id` (parent_type="episode"), and user_memory clusters store episode entry_id members — so the stale fixture made VECTOR/AGENTIC recall and the cluster-narrowing path find nothing, and stale assertions checked an old error code. - Regenerate `search_seed/*` from a fresh corpus in the current entry_id format; facts now bridge across multiple episodes (richer agentic / hierarchical-eviction coverage). - Fix `_dump_search_seed.py` sampling: pick episodes that host facts first and keep facts by episode entry_id, so re-dumps stay coherent. - Migrate e2e tests to the entry_id model (hierarchical-eviction, session/timestamp filters, cluster seeding helper) and update the filter-error assertion to the current `INVALID_INPUT` code. - Provision `ome.toml` in the full-app pipeline fixture (the OME config reloader requires it; strategies are code-registered so the packaged default suffices), unblocking corpus regeneration. Full search e2e suite now green (49/49). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> (cherry picked from commit 44cd9cecc07775cb9270104a5804f36e32cd788d) * fix(lancedb): detect schema type drift and add cascade rebuild recovery verify_business_schemas only compared column names, so a column whose on-disk Arrow type had drifted (name unchanged) slipped through and detonated later inside merge_insert as an opaque LanceError(IO) "Spill has sent an error" (#337). Now compare each shared column's Arrow type against schema.to_arrow_schema() — the exact schema get_table builds tables from, so a healthy table never false-positives. Reproduced #337 byte-identically: an episode.subject_vector column left as string or null by an older build, plus a real 1024-d vector on upsert, yields the exact crash. No lancedb version (0.13-0.34) renders Optional[Vector] as a non-vector type, so the startup guard is what should catch it — not the runtime. Add `everos cascade rebuild` as the safe recovery: it drops the business LanceDB tables and re-indexes from markdown, skipping the verify guard (which the drift would otherwise trip on startup). Unlike removing only .index/lancedb it re-populates already-done entries (reset_all clears the cascade queue); unlike removing all of .index it preserves unprocessed_buffer (messages not yet extracted). Fixes #337. * docs(cascade): document cascade rebuild and correct recovery guidance Add the `everos cascade rebuild` command to the runbook, CLI, and how-memory-works docs. Correct the old recovery guidance: a bare `rm -rf .index/lancedb` leaves md_change_state marked `done`, so the scanner skips those files and the index comes back empty — the runbook previously claimed a full repopulation that does not happen. `cascade rebuild` is the safe path (re-populates done entries, preserves unprocessed_buffer). Also document that verify now checks column types. * chore(rebase): adapt #354 integration test to soft-embedding main CascadeOrchestrator dropped the embedder param when embedding became a soft dependency (main); fold the schema-drift integration test onto it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(cascade): freeze monotonic clock in prune-staleness health tests Both prune-staleness health tests fabricated `_started_at = time.monotonic() - (ALERT + 100)`, assuming monotonic() is a large value. On a fresh CI runner monotonic() is only ~100-180s, so the subtraction went negative, the source clamped the baseline to 0, and staleness read back as ~130s < 900s — failing on CI while passing on long-lived dev boxes where monotonic() is huge. Freeze the monotonic clock via monkeypatch so staleness is deterministic regardless of the runner's boot uptime. Source logic is unchanged; only the tests are made hermetic. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(cascade): wait for stable terminal state in rename scenarios `_wait_path_done` reached a terminal status, slept a 0.1s settle window, then asserted the status was still terminal — which contradicted its own docstring ("absorb any last-second re-enqueue"). A rename's delete event or an atomic-replace echo can flip a done row back to `processing` inside that window, so on a slow CI runner the assert fired ("flipped back to processing after reaching done"), failing test_rename_cross_owner_keeps_frontmatter_owner intermittently (seen on the 3.13 job). `make integration` runs without `--reruns`, so a single flake fails the whole job. Wait for a terminal state that *survives* the settle window instead: absorb a transient re-enqueue by waiting for terminal again, still bounded by `deadline` so a row that never settles surfaces as a timeout. Pre- existing flake on main, unrelated to the prune change; the scenario's real assertions (row counts, frontmatter owner) are untouched. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(cascade): cross-process prune safety + backfill reclaim fix Review of #379 found two P0s plus P1/P2s, all verified against the code: - P0-1: cascade backfill still called the removed optimize(cleanup_older_than=…) kwarg → TypeError swallowed by the best-effort try/except → backfill silently skipped all compaction + reclaim (the exact bloat this PR fixes). CI stayed green because the test double kept the stale signature. Fix: call optimize() + prune(0) at the call site; make the fake mirror the real signature so the drift can't hide again; pin prune in the backfill tests. - P0-2: prune ran delete_unverified=True guarded only by an in-process asyncio lock, but the runbook promises `cascade sync` is safe alongside a live server — and the CLI's first optimize beat does prune, in a separate process. It could delete files the daemon is mid-commit on. Fix: switch prune to delete_unverified=False. Measured to reclaim identically on churned tables (both collapse superseded versions ~97%); True only additionally deletes in-flight/dangling files — exactly the corruption vector. No cross-process lock needed; the write-lock/commit fix (the real reclaim win) is unchanged. - P1-3: /health called orch.health() (6 SQLite aggregates) with no guard → a locked/full/migrating DB would 500 the liveness probe and restart the container. Wrap it: unhealthy readiness + reason, HTTP stays 200. - P1-4: rebuild drops + recreates tables; a live daemon holds cached handles pointing at the dropped dataset. Runbook now says stop the server first — the one cascade command unsafe alongside a live server. - P2: narrow _is_benign_commit_conflict to the "commit conflict" phrase (a bare "retryable" swallowed unrelated recoverable errors); add a timeout around the prune cleanup so a hung lance call can't wedge the write lock; correct two stale docstrings. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs: fix schema-recovery guidance + drop dead internal doc refs Follow-up to the review; two doc issues neither the review nor the fix commit caught: - The schema-drift startup error's docstrings (verify_business_schemas and LanceDBLifespanProvider) still described the recovery as `rm -rf ~/.everos/.index/lancedb` — which the runbook explicitly calls the WRONG recovery (it leaves the cascade queue `done`, so nothing re-indexes and the index comes back empty). The raised error already points to `everos cascade rebuild`; align the docstrings to match. - 15 dangling references to an internal numbered design-doc set (12_/13_/16_/17_*.md) that was never shipped to this repo. Point the schema-recovery ones at docs/cascade_runbook.md; drop the rest (pure provenance in table/component docstrings) while keeping the substance. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs: align maintenance docstrings with split optimize/prune API Two docstring residuals from the #379 review's P2 list: - _run_optimize_once still described the pre-split bundled heavy beat ("same work plus cleanup_older_than ... older than one cadence"); the heavy beat now calls prune() under the write lock and the retention window is decoupled from the cadence (DEFAULT_OPTIMIZE_PRUNE_RETENTION_SECONDS). - _restore_shaper_metadata converts any numeric timestamp, wider than an exact inverse of the bridge; document that this is deliberate (the shaper contract requires a datetime either way). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * style(e2e): hoist fixture-body imports to conftest module top shutil / importlib.resources.files were imported inside the core_pipeline_runtime fixture body; move them to the module top to match the repo import style (#379 review P2). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(cascade): back off a hung prune via a separate attempt clock (N1) The write-lock timeout on prune (review P2) didn't achieve its goal: it was 300s — equal to the prune cadence — and `last_prune_at` only advanced on success. So a hung lance cleanup timed out after 300s, `should_prune` was still true (clock never moved), and the next beat re-pruned ~10s later — pinning the per-table write lock ~97% of the time, the exact write-starvation the timeout was meant to prevent. A real cleanup is milliseconds even on a heavily churned table (measured ~40ms at 320k writes / 100 versions), so the timeout is a pure hang-catcher: lower it to 60s (~1500x headroom, never fires normally, well below the 300s cadence). Split the prune clock so a failed prune backs off without masking the health signal: - last_prune_attempt_at (new) gates scheduling, advanced before the call whether it succeeds or times out → a hung prune waits a full cadence before retrying (light lock-free compaction runs meanwhile), so the lock is held at most ~timeout/cadence ≈ 17% in the worst case. - last_prune_at advances only on success and still drives the prune-staleness health signal, so a persistently failing prune surfaces as degraded instead of being hidden by an advanced schedule clock. Regression test: a raising prune advances the attempt clock (next beat is light, no immediate re-prune) but not the success clock. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: zhanghui <zhanghui@shanda.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
733 lines
27 KiB
Python
733 lines
27 KiB
Python
"""End-to-end cascade scenarios beyond the happy-path append.
|
|
|
|
Each test boots the full cascade (writer → watchdog → md_change_state →
|
|
worker → LanceDB) against a tmp memory_root and asserts md/LanceDB
|
|
convergence after a specific perturbation. Scanner interval is held
|
|
at 60s here so the watcher path is the one being exercised — the
|
|
scanner-fallback variants live in :mod:`test_cascade_scanner_fallback`.
|
|
|
|
Coverage targets
|
|
----------------
|
|
* Rename: in-bucket / out-of-glob / cross-owner ``mv`` of a real md
|
|
file (not the atomic-replace one — that one's covered by
|
|
:mod:`test_cascade_fsevents_repro`).
|
|
* Content edits: re-writing an existing entry's body must flip
|
|
``content_sha256`` and trigger LanceDB re-upsert (not skip).
|
|
* Isolation: concurrent writes to N different owners must not bleed
|
|
across each other's md_paths in LanceDB.
|
|
* Lap race: ``writer.append`` calls overlapping a worker's
|
|
in-flight handler must all converge once drained, no entries lost.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import datetime as _dt
|
|
import shutil
|
|
from collections.abc import AsyncIterator
|
|
from pathlib import Path
|
|
|
|
import anyio
|
|
import pytest
|
|
from sqlmodel import SQLModel
|
|
|
|
from everos.component.embedding import EmbeddingProvider
|
|
from everos.component.tokenizer import build_tokenizer
|
|
from everos.core.persistence import MarkdownReader, MarkdownWriter, MemoryRoot
|
|
from everos.infra.persistence.lancedb import (
|
|
atomic_fact_repo,
|
|
dispose_connection,
|
|
ensure_business_indexes,
|
|
)
|
|
from everos.infra.persistence.lancedb.lancedb_manager import get_table
|
|
from everos.infra.persistence.lancedb.tables.atomic_fact import AtomicFact
|
|
from everos.infra.persistence.markdown import AtomicFactWriter
|
|
from everos.infra.persistence.sqlite import (
|
|
dispose_engine,
|
|
get_engine,
|
|
md_change_state_repo,
|
|
)
|
|
from everos.memory.cascade import CascadeConfig, CascadeOrchestrator
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset_lancedb_write_locks() -> None:
|
|
"""Drop the per-table write-lock pool between tests.
|
|
|
|
``LanceRepoBase`` stashes ``asyncio.Lock`` objects in a ClassVar dict
|
|
keyed by table name; without a reset the lock outlives pytest-
|
|
asyncio's function-scoped loop and the next test fails with "Lock
|
|
bound to a different event loop". Mirrors the unit-test fixture in
|
|
test_repository.py.
|
|
"""
|
|
from everos.core.persistence.lancedb.repository import LanceRepoBase
|
|
|
|
LanceRepoBase._reset_locks_for_tests()
|
|
|
|
|
|
class _StubEmbedder(EmbeddingProvider):
|
|
dim = 1024
|
|
|
|
async def embed(self, text: str) -> list[float]:
|
|
return [0.0] * self.dim
|
|
|
|
async def embed_batch(self, texts): # type: ignore[no-untyped-def]
|
|
return [[0.0] * self.dim for _ in texts]
|
|
|
|
|
|
@pytest.fixture
|
|
async def cascade_runtime(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> AsyncIterator[MemoryRoot]:
|
|
monkeypatch.setenv("EVEROS_ROOT", str(tmp_path))
|
|
monkeypatch.setenv("EVEROS_EMBEDDING__MODEL", "stub-model")
|
|
monkeypatch.setenv("EVEROS_EMBEDDING__BASE_URL", "http://stub.invalid/v1")
|
|
monkeypatch.setenv("EVEROS_EMBEDDING__API_KEY", "stub-key")
|
|
# Handlers fetch the embedder lazily via ``get_embedding_capability()``
|
|
# rather than through ``CascadeOrchestrator`` — patch the process-wide
|
|
# singleton so cascade never hits the fake network target above.
|
|
# ``test_lap_append_during_handler_no_loss`` re-patches with a slow
|
|
# variant to force a handler-in-flight race.
|
|
_patch_embedding_capability(monkeypatch, _StubEmbedder())
|
|
|
|
await dispose_connection()
|
|
await dispose_engine()
|
|
|
|
engine = get_engine()
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(SQLModel.metadata.create_all)
|
|
await ensure_business_indexes()
|
|
(tmp_path / "ome.toml").write_text("# test\n")
|
|
|
|
yield MemoryRoot.resolve()
|
|
|
|
await dispose_connection()
|
|
await dispose_engine()
|
|
|
|
|
|
def _patch_embedding_capability(
|
|
monkeypatch: pytest.MonkeyPatch, embedder: EmbeddingProvider
|
|
) -> None:
|
|
"""Patch the process-wide embedding capability singleton to *embedder*."""
|
|
import everos.component.embedding.accessor as acc
|
|
from everos.component.embedding import EmbeddingCapability
|
|
|
|
monkeypatch.setattr(acc, "_capability", EmbeddingCapability(provider=embedder))
|
|
|
|
|
|
def _build_orchestrator(
|
|
memory_root: MemoryRoot, *, scan_interval: float = 60.0
|
|
) -> CascadeOrchestrator:
|
|
return CascadeOrchestrator(
|
|
memory_root=memory_root,
|
|
tokenizer=build_tokenizer(),
|
|
config=CascadeConfig(
|
|
scan_interval_seconds=scan_interval,
|
|
worker_batch_size=20,
|
|
worker_max_retry=1,
|
|
worker_poll_interval_seconds=0.05,
|
|
worker_retry_backoff_seconds=0.0,
|
|
),
|
|
)
|
|
|
|
|
|
async def _wait_path_done(md_path: str, *, deadline: float = 15.0) -> None:
|
|
"""Wait until ``md_path`` lands in state AND *stably* reaches a terminal
|
|
status (``done``/``failed``).
|
|
|
|
Bare ``_wait_drain`` returns immediately when the queue is empty, which
|
|
is exactly the case right after a single ``append_entries`` fires once
|
|
but the watcher hasn't yet enqueued anything. This helper polls for the
|
|
row first (i.e. watcher has noticed), then waits for a terminal state
|
|
that *survives* a short settle window: a last-second re-enqueue (an
|
|
atomic-replace echo, or a rename's delete event) flips the row back to
|
|
``processing``, so we absorb it by waiting for terminal again rather
|
|
than treating the transient flip as a failure. Bounded by ``deadline``,
|
|
so a row that never settles still surfaces as a timeout.
|
|
"""
|
|
async with asyncio.timeout(deadline):
|
|
while True:
|
|
if await md_change_state_repo.get_by_id(md_path) is not None:
|
|
break
|
|
await asyncio.sleep(0.05)
|
|
while True:
|
|
row = await md_change_state_repo.get_by_id(md_path)
|
|
if row is not None and row.status in ("done", "failed"):
|
|
await asyncio.sleep(0.1) # settle
|
|
row = await md_change_state_repo.get_by_id(md_path)
|
|
if row is not None and row.status in ("done", "failed"):
|
|
return # stably terminal
|
|
# flipped back to processing (re-enqueue) — keep waiting
|
|
await asyncio.sleep(0.05)
|
|
|
|
|
|
async def _wait_paths_done(*md_paths: str, deadline: float = 15.0) -> None:
|
|
await asyncio.gather(*[_wait_path_done(p, deadline=deadline) for p in md_paths])
|
|
|
|
|
|
async def _wait_drain(deadline: float = 15.0) -> None:
|
|
"""Wait for the *whole* queue to settle. Use only when you've already
|
|
confirmed at least one path is in flight (via _wait_path_done first)."""
|
|
async with asyncio.timeout(deadline):
|
|
while True:
|
|
summary = await md_change_state_repo.queue_summary()
|
|
if summary.pending == 0:
|
|
return
|
|
await asyncio.sleep(0.05)
|
|
|
|
|
|
async def _count_lance_rows_md(md_path: str) -> int:
|
|
table = await get_table(AtomicFact.TABLE_NAME, AtomicFact)
|
|
return await table.count_rows(filter=f"md_path = '{md_path}'")
|
|
|
|
|
|
async def _count_md_entries(absolute: Path) -> int:
|
|
if not await anyio.Path(absolute).is_file():
|
|
return 0
|
|
parsed = await MarkdownReader.read(absolute)
|
|
return len(parsed.entries)
|
|
|
|
|
|
def _atomic_fact_md_path(owner_id: str, bucket: _dt.date) -> str:
|
|
return (
|
|
f"default_app/default_project/users/{owner_id}/.atomic_facts/"
|
|
f"atomic_fact-{bucket.isoformat()}.md"
|
|
)
|
|
|
|
|
|
async def _seed_atomic_facts(
|
|
writer: AtomicFactWriter,
|
|
*,
|
|
owner_id: str,
|
|
bucket: _dt.date,
|
|
n_items: int,
|
|
text_prefix: str = "seed fact",
|
|
) -> None:
|
|
items = [
|
|
(
|
|
{
|
|
"owner_id": owner_id,
|
|
"session_id": f"s_{j}",
|
|
"timestamp": "2026-05-19T07:04:26+00:00",
|
|
"parent_id": f"mc_{j}",
|
|
"sender_ids": [owner_id],
|
|
},
|
|
{"Fact": f"{text_prefix} {j}"},
|
|
)
|
|
for j in range(n_items)
|
|
]
|
|
await writer.append_entries(owner_id, items, date=bucket)
|
|
|
|
|
|
# ===== A. Rename scenarios =====
|
|
|
|
|
|
async def test_rename_same_owner_kind_in_bucket(
|
|
cascade_runtime: MemoryRoot,
|
|
) -> None:
|
|
"""``mv atomic_fact-D1.md atomic_fact-D2.md`` inside the same owner+kind.
|
|
|
|
Both paths match the kind glob. Expected: src lancedb rows cleared,
|
|
dest md_path becomes the new home for the (entry_id, content) pairs.
|
|
"""
|
|
memory_root = cascade_runtime
|
|
orchestrator = _build_orchestrator(memory_root)
|
|
await orchestrator.start()
|
|
await asyncio.sleep(0.3)
|
|
|
|
try:
|
|
writer = AtomicFactWriter(root=memory_root)
|
|
owner_id = "u_rename_a"
|
|
bucket_src = _dt.date(2026, 5, 18)
|
|
bucket_dest = _dt.date(2026, 5, 20)
|
|
await _seed_atomic_facts(
|
|
writer, owner_id=owner_id, bucket=bucket_src, n_items=5
|
|
)
|
|
src_md_path = _atomic_fact_md_path(owner_id, bucket_src)
|
|
dest_md_path = _atomic_fact_md_path(owner_id, bucket_dest)
|
|
src_absolute = memory_root.root / src_md_path
|
|
dest_absolute = memory_root.root / dest_md_path
|
|
|
|
await _wait_path_done(src_md_path)
|
|
|
|
# Sanity: cascade has indexed the seed.
|
|
assert await _count_lance_rows_md(src_md_path) == 5
|
|
assert await _count_lance_rows_md(dest_md_path) == 0
|
|
|
|
# Real rename — no tmp/atomic-replace involvement.
|
|
await anyio.to_thread.run_sync(
|
|
shutil.move, str(src_absolute), str(dest_absolute)
|
|
)
|
|
await _wait_paths_done(src_md_path, dest_md_path)
|
|
|
|
assert await _count_lance_rows_md(src_md_path) == 0, "src not cleared"
|
|
assert await _count_lance_rows_md(dest_md_path) == 5, "dest not reindexed"
|
|
|
|
# md_change_state should reflect both sides finally settled.
|
|
src_row = await md_change_state_repo.get_by_id(src_md_path)
|
|
dest_row = await md_change_state_repo.get_by_id(dest_md_path)
|
|
assert src_row is not None and src_row.status == "done"
|
|
assert dest_row is not None and dest_row.status == "done"
|
|
finally:
|
|
await orchestrator.stop()
|
|
|
|
|
|
async def test_rename_out_of_kind_glob_degrades_to_delete(
|
|
cascade_runtime: MemoryRoot,
|
|
) -> None:
|
|
"""``mv`` from inside the kind glob to a path outside it.
|
|
|
|
Expected: src lancedb cleared (treated as deletion); dest path is
|
|
silently ignored because ``match_kind`` rejects it.
|
|
"""
|
|
memory_root = cascade_runtime
|
|
orchestrator = _build_orchestrator(memory_root)
|
|
await orchestrator.start()
|
|
await asyncio.sleep(0.3)
|
|
|
|
try:
|
|
writer = AtomicFactWriter(root=memory_root)
|
|
owner_id = "u_rename_oob"
|
|
bucket = _dt.date(2026, 5, 18)
|
|
await _seed_atomic_facts(writer, owner_id=owner_id, bucket=bucket, n_items=4)
|
|
src_md_path = _atomic_fact_md_path(owner_id, bucket)
|
|
src_absolute = memory_root.root / src_md_path
|
|
# An obviously-out-of-glob target: hide it under a plain dir
|
|
# that no kind spec registers.
|
|
dest_absolute = memory_root.root / "out_of_scope" / "random.md"
|
|
await anyio.Path(dest_absolute.parent).mkdir(parents=True, exist_ok=True)
|
|
|
|
await _wait_path_done(src_md_path)
|
|
assert await _count_lance_rows_md(src_md_path) == 4
|
|
|
|
await anyio.to_thread.run_sync(
|
|
shutil.move, str(src_absolute), str(dest_absolute)
|
|
)
|
|
# Wait for the src deletion to settle. The dest path is outside
|
|
# the glob so it never enters md_change_state — can't wait on it.
|
|
# Re-poll src until row reflects the rename.
|
|
await asyncio.sleep(0.5)
|
|
await _wait_drain()
|
|
|
|
assert await _count_lance_rows_md(src_md_path) == 0
|
|
# No row should appear for the out-of-glob target.
|
|
src_row = await md_change_state_repo.get_by_id(src_md_path)
|
|
assert src_row is not None and src_row.status == "done"
|
|
# The dest path was never registered with any kind spec, so no
|
|
# md_change_state row should exist for it.
|
|
all_rows = await md_change_state_repo.queue_summary()
|
|
# Spot check: pending should be 0; total rows present (done)
|
|
# come only from the src side.
|
|
assert all_rows.pending == 0
|
|
finally:
|
|
await orchestrator.stop()
|
|
|
|
|
|
async def test_rename_cross_owner_keeps_frontmatter_owner(
|
|
cascade_runtime: MemoryRoot,
|
|
) -> None:
|
|
"""``mv users/u_a/.atomic_facts/X.md users/u_b/.atomic_facts/X.md``.
|
|
|
|
Frontmatter ``user_id`` stays as ``u_a`` (rename doesn't rewrite the
|
|
file). resolve_owner pulls owner_id from frontmatter, so dest
|
|
LanceDB rows carry ``owner_id='u_a'`` even though md_path is under
|
|
``users/u_b/``. This reflects current design (frontmatter is the
|
|
truth source) — surface it as a regression anchor.
|
|
"""
|
|
memory_root = cascade_runtime
|
|
orchestrator = _build_orchestrator(memory_root)
|
|
await orchestrator.start()
|
|
await asyncio.sleep(0.3)
|
|
|
|
try:
|
|
writer = AtomicFactWriter(root=memory_root)
|
|
bucket = _dt.date(2026, 5, 18)
|
|
owner_a = "u_a"
|
|
owner_b = "u_b"
|
|
await _seed_atomic_facts(writer, owner_id=owner_a, bucket=bucket, n_items=3)
|
|
src_md_path = _atomic_fact_md_path(owner_a, bucket)
|
|
dest_md_path = _atomic_fact_md_path(owner_b, bucket)
|
|
src_absolute = memory_root.root / src_md_path
|
|
dest_absolute = memory_root.root / dest_md_path
|
|
await anyio.Path(dest_absolute.parent).mkdir(parents=True, exist_ok=True)
|
|
|
|
await _wait_path_done(src_md_path)
|
|
assert await _count_lance_rows_md(src_md_path) == 3
|
|
|
|
await anyio.to_thread.run_sync(
|
|
shutil.move, str(src_absolute), str(dest_absolute)
|
|
)
|
|
await _wait_paths_done(src_md_path, dest_md_path)
|
|
|
|
assert await _count_lance_rows_md(src_md_path) == 0
|
|
assert await _count_lance_rows_md(dest_md_path) == 3
|
|
|
|
# Inspect a row from dest to confirm owner_id stays as u_a
|
|
# (current design: frontmatter wins over md_path for owner_id).
|
|
rows = await atomic_fact_repo.find_where(
|
|
f"md_path = '{dest_md_path}'", limit=10
|
|
)
|
|
assert rows, "dest md_path has no rows"
|
|
assert all(r.owner_id == owner_a for r in rows), (
|
|
f"expected owner_id={owner_a} from frontmatter, "
|
|
f"got {[r.owner_id for r in rows]}"
|
|
)
|
|
finally:
|
|
await orchestrator.stop()
|
|
|
|
|
|
# ===== B. Write-pattern scenarios =====
|
|
|
|
|
|
async def test_modify_existing_entry_content_reindexes(
|
|
cascade_runtime: MemoryRoot,
|
|
) -> None:
|
|
"""Rewriting an entry's body (same entry_id, new text) must flip
|
|
content_sha256 and trigger re-upsert (not skip)."""
|
|
memory_root = cascade_runtime
|
|
orchestrator = _build_orchestrator(memory_root)
|
|
await orchestrator.start()
|
|
await asyncio.sleep(0.3)
|
|
|
|
try:
|
|
writer = AtomicFactWriter(root=memory_root)
|
|
owner_id = "u_modify"
|
|
bucket = _dt.date(2026, 5, 18)
|
|
await _seed_atomic_facts(
|
|
writer,
|
|
owner_id=owner_id,
|
|
bucket=bucket,
|
|
n_items=3,
|
|
text_prefix="ORIGINAL",
|
|
)
|
|
md_path = _atomic_fact_md_path(owner_id, bucket)
|
|
absolute = memory_root.root / md_path
|
|
await _wait_path_done(md_path)
|
|
rows_before = await atomic_fact_repo.find_where(
|
|
f"md_path = '{md_path}'", limit=10
|
|
)
|
|
assert len(rows_before) == 3
|
|
sha_before = {r.entry_id: r.content_sha256 for r in rows_before}
|
|
fact_before = {r.entry_id: r.fact for r in rows_before}
|
|
|
|
# Read, replace body text, atomic-write back through writer.write()
|
|
text = await anyio.Path(absolute).read_text(encoding="utf-8")
|
|
new_text = text.replace("ORIGINAL", "EDITED")
|
|
assert new_text != text
|
|
mw = MarkdownWriter(memory_root)
|
|
await mw.write(absolute, new_text)
|
|
# The edit reuses md_path; watcher enqueue can lag behind the write,
|
|
# so queue-empty is not a sufficient barrier. Poll for the externally
|
|
# visible condition this scenario cares about: LanceDB rows reflect the
|
|
# rewritten entry bodies.
|
|
async with asyncio.timeout(15.0):
|
|
while True:
|
|
await _wait_drain()
|
|
rows_after = await atomic_fact_repo.find_where(
|
|
f"md_path = '{md_path}'", limit=10
|
|
)
|
|
if len(rows_after) == 3 and all(
|
|
r.content_sha256 != sha_before.get(r.entry_id)
|
|
and "EDITED" in r.fact
|
|
and "ORIGINAL" not in r.fact
|
|
for r in rows_after
|
|
):
|
|
break
|
|
await asyncio.sleep(0.05)
|
|
|
|
assert len(rows_after) == 3
|
|
sha_after = {r.entry_id: r.content_sha256 for r in rows_after}
|
|
fact_after = {r.entry_id: r.fact for r in rows_after}
|
|
|
|
# Every entry_id present in both, every content_sha256 changed,
|
|
# every fact text now reflects EDITED.
|
|
assert set(sha_after) == set(sha_before)
|
|
for eid, sha in sha_after.items():
|
|
assert sha != sha_before[eid], (
|
|
f"content_sha256 did not change for {eid}: stayed {sha}"
|
|
)
|
|
assert "EDITED" in fact_after[eid], (
|
|
f"fact text not updated for {eid}: {fact_after[eid]!r}"
|
|
)
|
|
assert "ORIGINAL" not in fact_after[eid]
|
|
assert "ORIGINAL" in fact_before[eid]
|
|
finally:
|
|
await orchestrator.stop()
|
|
|
|
|
|
async def test_concurrent_writes_different_owners_no_bleed(
|
|
cascade_runtime: MemoryRoot,
|
|
) -> None:
|
|
"""N owners writing in parallel must converge with per-md_path
|
|
isolation: each md_path holds exactly its owner's entries."""
|
|
memory_root = cascade_runtime
|
|
orchestrator = _build_orchestrator(memory_root)
|
|
await orchestrator.start()
|
|
await asyncio.sleep(0.3)
|
|
|
|
try:
|
|
writer = AtomicFactWriter(root=memory_root)
|
|
bucket = _dt.date(2026, 5, 18)
|
|
owners = [f"u_concur_{i}" for i in range(5)]
|
|
per_owner = 4
|
|
|
|
await asyncio.gather(
|
|
*[
|
|
_seed_atomic_facts(
|
|
writer,
|
|
owner_id=oid,
|
|
bucket=bucket,
|
|
n_items=per_owner,
|
|
text_prefix=f"by-{oid}",
|
|
)
|
|
for oid in owners
|
|
]
|
|
)
|
|
md_paths = [_atomic_fact_md_path(oid, bucket) for oid in owners]
|
|
await _wait_paths_done(*md_paths)
|
|
|
|
for oid in owners:
|
|
md_path = _atomic_fact_md_path(oid, bucket)
|
|
rows = await atomic_fact_repo.find_where(f"md_path = '{md_path}'", limit=10)
|
|
assert len(rows) == per_owner, (
|
|
f"{oid}: expected {per_owner} rows, got {len(rows)}"
|
|
)
|
|
# Every row in this md_path must belong to this owner —
|
|
# no bleed from another concurrent owner's writes.
|
|
assert all(r.owner_id == oid for r in rows)
|
|
assert all(f"by-{oid}" in r.fact for r in rows)
|
|
finally:
|
|
await orchestrator.stop()
|
|
|
|
|
|
async def test_lap_append_during_handler_no_loss(
|
|
cascade_runtime: MemoryRoot,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""Writer keeps appending while worker is mid-handler.
|
|
|
|
Slow the embedder so a handler invocation overlaps later appends.
|
|
On drain, lance_rows must equal md entries — the lap is absorbed
|
|
by the worker's status='processing' guard + re-claim.
|
|
"""
|
|
memory_root = cascade_runtime
|
|
|
|
class _SlowEmbedder(_StubEmbedder):
|
|
async def embed(self, text: str) -> list[float]:
|
|
await asyncio.sleep(0.05) # handler takes ~0.05*N entries
|
|
return [0.0] * self.dim
|
|
|
|
# Override the fixture's default stub — this test needs latency to
|
|
# force a handler invocation to overlap later writer appends.
|
|
_patch_embedding_capability(monkeypatch, _SlowEmbedder())
|
|
|
|
orchestrator = CascadeOrchestrator(
|
|
memory_root=memory_root,
|
|
tokenizer=build_tokenizer(),
|
|
config=CascadeConfig(
|
|
scan_interval_seconds=60.0,
|
|
worker_batch_size=20,
|
|
worker_max_retry=1,
|
|
worker_poll_interval_seconds=0.05,
|
|
worker_retry_backoff_seconds=0.0,
|
|
),
|
|
)
|
|
await orchestrator.start()
|
|
await asyncio.sleep(0.3)
|
|
|
|
try:
|
|
writer = AtomicFactWriter(root=memory_root)
|
|
owner_id = "u_lap"
|
|
bucket = _dt.date(2026, 5, 18)
|
|
total = 30
|
|
for i in range(total):
|
|
await writer.append_entries(
|
|
owner_id,
|
|
[
|
|
(
|
|
{
|
|
"owner_id": owner_id,
|
|
"session_id": f"s_{i}",
|
|
"timestamp": "2026-05-19T07:04:26+00:00",
|
|
"parent_id": f"mc_{i}",
|
|
"sender_ids": [owner_id],
|
|
},
|
|
{"Fact": f"fact body {i}"},
|
|
)
|
|
],
|
|
date=bucket,
|
|
)
|
|
# Pace just slow enough that some writes land during a
|
|
# handler invocation (~50ms per embed), but fast enough
|
|
# that multiple writes accumulate during one handler.
|
|
await asyncio.sleep(0.02)
|
|
|
|
md_path = _atomic_fact_md_path(owner_id, bucket)
|
|
absolute = memory_root.root / md_path
|
|
await _wait_path_done(md_path, deadline=30.0)
|
|
|
|
md_entries = await _count_md_entries(absolute)
|
|
lance_rows = await _count_lance_rows_md(md_path)
|
|
assert md_entries == total, (
|
|
f"writer self-check: expected {total} md entries, got {md_entries}"
|
|
)
|
|
assert lance_rows == md_entries, f"LAP LOSS: md={md_entries} lance={lance_rows}"
|
|
finally:
|
|
await orchestrator.stop()
|
|
|
|
|
|
# ===== C. Scanner fallback scenarios =====
|
|
|
|
|
|
def _build_orchestrator_fast_scanner(memory_root: MemoryRoot) -> CascadeOrchestrator:
|
|
"""Same as :func:`_build_orchestrator` but with a 2s scanner so tests
|
|
don't wait 30s for the fallback path."""
|
|
return CascadeOrchestrator(
|
|
memory_root=memory_root,
|
|
tokenizer=build_tokenizer(),
|
|
config=CascadeConfig(
|
|
scan_interval_seconds=2.0,
|
|
worker_batch_size=20,
|
|
worker_max_retry=1,
|
|
worker_poll_interval_seconds=0.05,
|
|
worker_retry_backoff_seconds=0.0,
|
|
),
|
|
)
|
|
|
|
|
|
def _silence_handler_method(monkeypatch: pytest.MonkeyPatch, name: str) -> None:
|
|
"""Replace ``watcher._Handler.<name>`` with a no-op for the duration
|
|
of the test. Simulates fseventsd missing that event class entirely.
|
|
"""
|
|
from everos.memory.cascade import watcher as watcher_module
|
|
|
|
monkeypatch.setattr(
|
|
watcher_module._Handler,
|
|
name,
|
|
lambda self, event: None,
|
|
)
|
|
|
|
|
|
async def test_scanner_recovers_missed_delete(
|
|
cascade_runtime: MemoryRoot,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""Watcher's ``on_deleted`` is silenced → unlink no longer enqueues
|
|
via the watcher. The scanner sweep should still notice the path
|
|
missing on disk and enqueue a 'deleted' on its own."""
|
|
memory_root = cascade_runtime
|
|
orchestrator = _build_orchestrator_fast_scanner(memory_root)
|
|
await orchestrator.start()
|
|
await asyncio.sleep(0.3)
|
|
|
|
try:
|
|
writer = AtomicFactWriter(root=memory_root)
|
|
owner_id = "u_scan_del"
|
|
bucket = _dt.date(2026, 5, 18)
|
|
await _seed_atomic_facts(writer, owner_id=owner_id, bucket=bucket, n_items=3)
|
|
md_path = _atomic_fact_md_path(owner_id, bucket)
|
|
absolute = memory_root.root / md_path
|
|
await _wait_path_done(md_path)
|
|
assert await _count_lance_rows_md(md_path) == 3
|
|
|
|
# From here on, watcher ignores deletions.
|
|
_silence_handler_method(monkeypatch, "on_deleted")
|
|
|
|
absolute.unlink()
|
|
# Watcher won't enqueue; scanner sweeps every 2s and should
|
|
# spot mtime/existence inconsistency, then enqueue 'deleted'.
|
|
await asyncio.sleep(0.2)
|
|
|
|
async def _lance_cleared() -> bool:
|
|
return await _count_lance_rows_md(md_path) == 0
|
|
|
|
async with asyncio.timeout(10.0):
|
|
while not await _lance_cleared(): # noqa: ASYNC110 - polling cascade state
|
|
await asyncio.sleep(0.1)
|
|
|
|
async with asyncio.timeout(5.0):
|
|
while True:
|
|
row = await md_change_state_repo.get_by_id(md_path)
|
|
if row is not None and row.status == "done":
|
|
break
|
|
await asyncio.sleep(0.1)
|
|
assert row.change_type == "deleted"
|
|
finally:
|
|
await orchestrator.stop()
|
|
|
|
|
|
async def test_scanner_indexes_preexisting_md(
|
|
cascade_runtime: MemoryRoot,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""An md file written BEFORE cascade starts (or by an editor while
|
|
cascade is offline). watchdog ignores files that exist at schedule
|
|
time — only the scanner can pick it up. Simulate by silencing
|
|
on_created and writing the file before orchestrator.start()."""
|
|
memory_root = cascade_runtime
|
|
|
|
# Pre-seed: write the md directly to disk before any cascade is up.
|
|
owner_id = "u_scan_pre"
|
|
bucket = _dt.date(2026, 5, 18)
|
|
writer = AtomicFactWriter(root=memory_root)
|
|
await _seed_atomic_facts(writer, owner_id=owner_id, bucket=bucket, n_items=2)
|
|
md_path = _atomic_fact_md_path(owner_id, bucket)
|
|
assert (memory_root.root / md_path).is_file()
|
|
|
|
# Now start cascade with the file already on disk. Belt-and-
|
|
# suspenders: silence all watcher events so the only path to
|
|
# discovery is the scanner.
|
|
orchestrator = _build_orchestrator_fast_scanner(memory_root)
|
|
for name in ("on_created", "on_modified", "on_moved", "on_deleted"):
|
|
_silence_handler_method(monkeypatch, name)
|
|
await orchestrator.start()
|
|
|
|
try:
|
|
|
|
async def _lance_filled() -> bool:
|
|
return await _count_lance_rows_md(md_path) == 2
|
|
|
|
async with asyncio.timeout(10.0):
|
|
while not await _lance_filled(): # noqa: ASYNC110 - polling cascade state
|
|
await asyncio.sleep(0.1)
|
|
finally:
|
|
await orchestrator.stop()
|
|
|
|
|
|
async def test_scanner_recovers_missed_modify(
|
|
cascade_runtime: MemoryRoot,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""All non-deletion watcher events silenced. writer.append produces
|
|
an atomic-replace whose events are all dropped by the watcher.
|
|
Scanner should still notice the new file and enqueue 'added'."""
|
|
memory_root = cascade_runtime
|
|
orchestrator = _build_orchestrator_fast_scanner(memory_root)
|
|
|
|
# Silence everything BEFORE start() so the initial schedule doesn't
|
|
# see any add/create events either.
|
|
for name in ("on_created", "on_modified", "on_moved"):
|
|
_silence_handler_method(monkeypatch, name)
|
|
|
|
await orchestrator.start()
|
|
await asyncio.sleep(0.3)
|
|
|
|
try:
|
|
writer = AtomicFactWriter(root=memory_root)
|
|
owner_id = "u_scan_mod"
|
|
bucket = _dt.date(2026, 5, 18)
|
|
await _seed_atomic_facts(writer, owner_id=owner_id, bucket=bucket, n_items=3)
|
|
md_path = _atomic_fact_md_path(owner_id, bucket)
|
|
|
|
async def _lance_filled() -> bool:
|
|
return await _count_lance_rows_md(md_path) == 3
|
|
|
|
async with asyncio.timeout(10.0):
|
|
while not await _lance_filled(): # noqa: ASYNC110 - polling cascade state
|
|
await asyncio.sleep(0.1)
|
|
|
|
row = await md_change_state_repo.get_by_id(md_path)
|
|
assert row is not None and row.status == "done"
|
|
finally:
|
|
await orchestrator.stop()
|