MemTrace: deleted memories stay in the trace export; full scan per request when enabled

Abierto
#629 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
18/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
python

Línea de trabajo

Start with the delete and purge paths in src/everos/service/memory, which never call the tracker, and with the full-scan _sync_files in src/everos/infra/memtrace/tracker.py. The retention probe in the issue reproduces the leak: done means both markers stop appearing in the graph JSON after md deletion. The rest (per-request cost, graph growth, multiple workers) needs a design decision from the maintainer before any code change.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug

MemTrace (#612) is off by default and turned on per process with EVEROS_MEMTRACE_ENABLED=1. With it on, the problems below remain. They are listed as caveats in docs/memtrace-graphs.md, "Enabling tracing", but nothing tracks a fix.

@gdshjzm, you wrote the tracker, so you are best placed to fix these. Could you take them on?

Everything below was measured on main @ f4768362 with fake data and no model calls (macOS laptop). The probe scripts are at the end.

1. Deleted memories stay in the trace export (most important)

/memory/delete and purge never touch the export directory (<memory root>/memtrace/ or EVEROS_MEMTRACE_DIR). The delete paths in service/memory do not call the tracker at all.

To reproduce:

  1. Record an add whose message holds one marker.
  2. Write an episode that holds another marker, then search.
  3. Remove the episode md file, which is what delete and purge do to the md store, and search again.

Both markers are still in the graph JSON:

after add+extract  MSG hits: ['alice-522b276a__sess_alice-b0aa9171.json']
after add+extract  EP  hits: ['alice-522b276a__sess_alice-b0aa9171.json']
after md deleted   MSG hits: ['alice-522b276a__sess_alice-b0aa9171.json']
after md deleted   EP  hits: ['alice-522b276a__sess_alice-b0aa9171.json']

So when a user deletes or purges memories while tracing is on, their raw messages and episode text stay on disk. Expected: delete removes or redacts the matching nodes, and purge removes the owner's graphs.

2. Every add and search pays for a full scan, one request at a time

on_search and on_memorize are awaited before the response returns (service/memory/init.py L186, L507). Each one runs _sync_files (tracker.py L2444-L2462). Under one process-wide asyncio.Lock, it walks and stats every file under the memory root, applies the changes and rewrites the graph JSON. The cost grows with the number of md files, and concurrent requests queue behind the lock:

md files under the root first request after start steady, per search 20 concurrent searches, wall time
200 340 ms 17 ms 325 ms
1,000 1.2 s 60 ms 1.2 s
5,000 6.3 s 270 ms 5.4 s
20,000 22.9 s 1.08 s 22.4 s

The last column is about 20 times the steady cost: the 20 searches run one after another.

Suggested direction: drive tracing from the change signals EverOS already produces, instead of diffing the whole root on each request. Those are the cascade watcher (infra/cascade/watcher.py) with its MdChangeStateRepo ledger, and the extraction events in memory/events.py (EpisodeExtracted, AtomicFactsExtracted, ...). The export should also move off the response path.

3. Graph files grow without bound

One graph per owner and session is rewritten after every request and never trimmed. Long sessions therefore make both the files and each rewrite larger.

4. Several workers

Each process keeps its own in-memory graphs. Today the docs say to run a single writer or give each worker its own EVEROS_MEMTRACE_DIR. Merging per-worker output, or a single writer, would remove that caveat.

5. English version of the instrumentation guide

docs/memtrace-instrumentation.zh-CN.md has no English original. The language policy keeps docs in English and allows CJK only in locale mirrors, so please add docs/memtrace-instrumentation.md and keep the zh-CN file as its mirror. (The other Chinese file from #612, memtrace-attribution-review.zh-CN.md, is removed in a separate PR because it was a working review log.)

Probe: retention after delete

Run it from a checkout with uv sync --frozen: uv run python probe_retention.py <empty dir>

"""Probe PR #612 MemTraceTracker: (1) raw text retention, (2) per-search cost.

Run with the PR worktree's venv. Fake data only, no model calls.
"""

from __future__ import annotations

import asyncio
import os
import sys
import tempfile
import time
from pathlib import Path

EP = """---
user_id: {owner}
---
<!-- entry:{eid} -->
**owner_id**: {owner}
**session_id**: sess_{owner}
**timestamp**: 2026-01-01T00:00:00+00:00
**sender_ids**: [{owner}]
### Content
{body}
<!-- /entry:{eid} -->
"""


def write_ep(root: Path, owner: str, eid: str, body: str) -> Path:
    p = root / "default" / "default" / "users" / owner / "episodes" / f"{eid}.md"
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(EP.format(owner=owner, eid=eid, body=body), encoding="utf-8")
    return p


def grep(dirpath: Path, needle: str) -> list[str]:
    hits = []
    for f in dirpath.rglob("*.json"):
        if needle in f.read_text(encoding="utf-8"):
            hits.append(f.name)
    return hits


def fresh_tracker(root: Path):
    os.environ["EVEROS_ROOT"] = str(root)
    os.environ.pop("EVEROS_MEMTRACE_DIR", None)
    os.environ["EVEROS_MEMTRACE_ENABLED"] = "1"
    from everos.infra.memtrace import MemTraceTracker

    t = MemTraceTracker()
    assert t.enabled, "tracker not enabled"
    return t


def req(owner: str):
    from everos.memory.search.dto import SearchMethod, SearchRequest

    return SearchRequest(user_id=owner, query="q", method=SearchMethod.HYBRID, top_k=5)


def resp():
    from everos.memory.search.dto import SearchData, SearchResponse

    return SearchResponse(request_id="r" * 32, data=SearchData())


async def retention(base: Path) -> None:
    root = base / "root_retention"
    root.mkdir()
    t = fresh_tracker(root)
    payload = {
        "session_id": "sess_alice",
        "app_id": "default",
        "project_id": "default",
        "messages": [
            {
                "sender_id": "alice",
                "role": "user",
                "content": "MSG-MARKER-7f3a hello",
                "timestamp": "2026-01-01T00:00:00+00:00",
            }
        ],
    }
    await t.on_memorize(payload, is_final=False, defer_extraction=True, result=None)
    md = write_ep(root, "alice", "ep_1", "EP-MARKER-9c1d alice likes tea")
    await t.on_search(req("alice"), resp())
    print("after add+extract  MSG hits:", grep(t.out_dir, "MSG-MARKER-7f3a"))
    print("after add+extract  EP  hits:", grep(t.out_dir, "EP-MARKER-9c1d"))
    # Simulate what /memory/delete and purge do to the md store: the file goes.
    md.unlink()
    await t.on_search(req("alice"), resp())
    print("after md deleted   MSG hits:", grep(t.out_dir, "MSG-MARKER-7f3a"))
    print("after md deleted   EP  hits:", grep(t.out_dir, "EP-MARKER-9c1d"))


async def cost(base: Path, n_files: int, owners: int = 50) -> None:
    root = base / f"root_{n_files}"
    root.mkdir()
    for i in range(n_files):
        write_ep(root, f"u{i % owners}", f"ep_{i}", f"body {i}")
    t = fresh_tracker(root)
    t0 = time.perf_counter()
    await t.on_search(req("u0"), resp())
    first = time.perf_counter() - t0
    samples = []
    for _ in range(10):
        t0 = time.perf_counter()
        await t.on_search(req("u0"), resp())
        samples.append(time.perf_counter() - t0)
    steady = sorted(samples)[len(samples) // 2]
    # 20 concurrent searches for 20 different users.
    t0 = time.perf_counter()
    await asyncio.gather(*(t.on_search(req(f"u{i}"), resp()) for i in range(1, 21)))
    conc = time.perf_counter() - t0
    print(
        f"N={n_files:>6} md files | first search {first*1000:8.0f} ms | "
        f"steady per search {steady*1000:6.1f} ms | 20 concurrent wall {conc*1000:7.0f} ms"
    )


async def growth(base: Path, rounds: int) -> None:
    root = base / "root_growth"
    root.mkdir()
    write_ep(root, "alice", "ep_1", "x")
    t = fresh_tracker(root)
    times = []
    for _ in range(rounds):
        t0 = time.perf_counter()
        await t.on_search(req("alice"), resp())
        times.append(time.perf_counter() - t0)
    files = list(t.out_dir.glob("*.json"))
    size = sum(f.stat().st_size for f in files)
    first10 = sum(times[:10]) / 10 * 1000
    last10 = sum(times[-10:]) / 10 * 1000
    print(
        f"{rounds} searches by one user: graph json {size/1024:.0f} KiB in {len(files)} file(s); "
        f"avg per search first10 {first10:.1f} ms -> last10 {last10:.1f} ms"
    )


async def main() -> None:
    with tempfile.TemporaryDirectory(dir=sys.argv[1]) as d:
        base = Path(d)
        print("== retention ==")
        await retention(base)


asyncio.run(main())
Probe: per-request cost and queueing

uv run python probe_cost.py <empty dir>. It chdirs into the directory so that the root's path depth matches ~/.everos.

"""Per-request MemTrace cost at a realistic path depth.

Real roots look like /Users/admin/.everos/<app>/<project>/users/<owner>/...
(3 components above the root's contents). The scratchpad is ~9 deep, which
inflates pathlib costs, so this probe chdirs into the scratchpad and points
the tracker at a relative root ``h/a/r`` (also 3 components).
"""

from __future__ import annotations

import asyncio
import os
import shutil
import sys
import time
from pathlib import Path

EP = """---
user_id: {owner}
---
<!-- entry:{eid} -->
**owner_id**: {owner}
**session_id**: sess_{owner}
**timestamp**: 2026-01-01T00:00:00+00:00
**sender_ids**: [{owner}]
### Content
{body}
<!-- /entry:{eid} -->
"""


def build_root(root: Path, n: int, owners: int = 50) -> None:
    for i in range(n):
        p = root / "default_app" / "default_project" / "users" / f"u{i % owners}"
        p = p / "episodes" / f"ep_{i}.md"
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(EP.format(owner=f"u{i % owners}", eid=f"ep_{i}", body=f"b{i}"))


def tracker_for(root: Path):
    os.environ["EVEROS_MEMTRACE_ENABLED"] = "1"
    from everos.infra.memtrace import MemTraceTracker

    t = MemTraceTracker()
    t._root = root  # relative: keeps pathlib depth like ~/.everos
    t._out_dir = root / "memtrace"
    assert t.enabled
    return t


def req(owner: str):
    from everos.memory.search.dto import SearchMethod, SearchRequest

    return SearchRequest(user_id=owner, query="q", method=SearchMethod.HYBRID, top_k=5)


def resp():
    from everos.memory.search.dto import SearchData, SearchResponse

    return SearchResponse(request_id="r" * 32, data=SearchData())


async def one(n: int) -> None:
    root = Path("h/a/r")
    shutil.rmtree("h", ignore_errors=True)
    build_root(root, n)
    t = tracker_for(root)
    t0 = time.perf_counter()
    await t.on_search(req("u0"), resp())
    first = time.perf_counter() - t0
    samples = []
    for _ in range(9):
        t0 = time.perf_counter()
        await t.on_search(req("u0"), resp())
        samples.append(time.perf_counter() - t0)
    steady = sorted(samples)[len(samples) // 2]
    t0 = time.perf_counter()
    await asyncio.gather(*(t.on_search(req(f"u{i}"), resp()) for i in range(1, 21)))
    conc = time.perf_counter() - t0
    print(
        f"N={n:>6} | first {first * 1000:7.0f} ms | steady {steady * 1000:6.1f} ms"
        f" | 20 concurrent wall {conc * 1000:6.0f} ms"
        f" (= {conc / steady:4.1f} x steady)"
    )
    shutil.rmtree("h", ignore_errors=True)


async def main() -> None:
    os.chdir(sys.argv[1])
    for n in (200, 1_000, 5_000, 20_000):
        await one(n)


asyncio.run(main())

🤖 Generated with Claude Code

Lenguaje dominante
Python
Estrellas
13.3k
Forks
926
Merge medio
1 d 10 h
PR fusionados (30 d)
57

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de EverMind-AI/EverOS

Todos los issues de EverMind-AI/EverOS

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.