Skip to content

Stale FTS index entries persist after reset --reindex and reindex --search #765

Closed

Description

@BunkerBuster73

Summary

After a sequence of write_note(overwrite=True) failures, manual filesystem recovery, and basic-memory reset --reindex, the FTS search index continues to return entries that no longer correspond to records in the entities table. search returns these phantoms, but read_note and fetch correctly report Document not found for the same identifiers. Re-running basic-memory reindex --search does not clean them up.

Environment

  • Basic Memory version: 0.20.3 (latest stable, installed via uv tool)
  • Python: 3.14.3
  • OS: macOS (Apple Silicon, M3)
  • MCP transport: stdio (default), launched via Claude Desktop
  • Config: env: test, semantic_search_enabled: true, semantic_embedding_model: bge-small-en-v1.5, two local projects (main and note), single shared SQLite DB at ~/.basic-memory/memory.db
  • Note: project had last_sync: null and ~332 unindexed files prior to the incident (preexisting tech debt)

Steps to reproduce (approximate — full repro not attempted)

The exact trigger sequence in our case:

  1. Database in a state where basic-memory status shows hundreds of +new files (sync never completed).
  2. From an MCP client, call write_note(directory="notes/ai", title="<TitleA>", overwrite=True) intending to update an existing note in notes/ai/.
  3. The tool succeeds but writes to a different existing file at notes/progetti/<unrelated-name>.md instead of the intended target. The previous content of that file is destroyed and replaced with <TitleA> content. (This is itself a possible secondary issue with permalink/title fuzzy resolution under unsynced state.)
  4. Restore the affected file from filesystem backup (Time Machine).
  5. Manually rm the originally-intended file (which had been created in the wrong location anyway).
  6. Run basic-memory reset --reindex (confirmed y). Output reports "Database reset complete" and "Rebuilding search index for 2 project(s)" with embedding model download.
  7. basic-memory status → No changes ✅
  8. Run basic-memory reindex --search for good measure. Reports "Full-text search index rebuilt" for both projects.

Expected behavior

After reset --reindex plus reindex --search, the FTS index should contain entries only for files that currently exist in the filesystem and are present in the entities table. Titles in search results should match the current frontmatter.title (or auto-derived title) of the underlying entity.

Actual behavior

search returns phantom entries:

  • A permalink for a file that was rm'd before reset still appears in search results, with its pre-incident title.
  • A permalink whose underlying file was restored from Time Machine appears in search results with the wrong title (the title of the unrelated content that briefly overwrote it earlier).

read_note and fetch on the same identifiers correctly return:

{"metadata": {"error": "Document not found"}}

…or, for the file that exists with restored content, return the correct content with the correct frontmatter title — but the search index continues to advertise the stale title.

So: entities table is consistent with filesystem, FTS index is not.

Diagnostic evidence

$ basic-memory --version
Basic Memory CLI, version 0.20.3

$ basic-memory status
note: Status
└── No changes

Search returns phantom — file does not exist on disk:

$ # via MCP: search("<query>") returns id
$ # "notes/ai/<file-A-permalink>"
$ # with title "<file-A old title>"

$ ls "/Users/<me>/note-basic-memory/notes/ai/" | grep -i <file-A-prefix>
<file-A-current>.md

Note: only the current file exists; the old permalink file was rm'd.

fetch on the phantom permalink:

$ # via MCP: fetch("notes/ai/<file-A-permalink>")
$ # returns: {"metadata": {"error": "Document not found"}}

But search still returns it.

Workarounds attempted (none successful for the FTS phantoms)

  1. basic-memory reset --reindex — phantoms persist
  2. basic-memory reindex --search — phantoms persist
  3. touch <file> on affected files to bump mtime — status reports No changes (sync seems to verify by content checksum, not mtime, so touch is a no-op)
  4. Killing zombie basic-memory mcp processes from prior Claude Desktop sessions (we had 10 accumulated; killed 7) — no effect on FTS state

We have not yet tried pkill -9 -f "basic-memory mcp" + Claude Desktop full restart, which would force a fresh MCP server. That might or might not clear it depending on whether the FTS phantoms are persisted to the SQLite DB or held in MCP server in-memory cache.

Hypotheses (offered tentatively)

  • The FTS rebuild may be reading from a snapshot/cache that wasn't invalidated by reset. Possibly the reset drops entities and FTS tables but leaves a parallel structure (vector store / embedding cache) that the search path consults first.
  • Alternatively, when write_note(overwrite=True) writes to an unintended target due to fuzzy permalink/title resolution under desynced state, it may insert FTS rows that are never linked to a proper entity row, and these orphan FTS rows survive entities-driven rebuilds.
  • The fact that v0.20.3 already includes fix(core): exclude stale entity rows from embedding coverage stats #675 ("exclude stale entity rows from embedding coverage stats") suggests the maintainer is already aware of related stale-row issues; this may be an adjacent edge case not yet covered.

Suggested next steps

If the maintainer can confirm whether reset is supposed to fully truncate the FTS virtual table (and any embedding tables), that would help narrow the hypothesis. A --vacuum or --full-rebuild flag for reset that also drops/recreates FTS5 virtual tables and embedding storage might be a useful escape hatch for users in this state.

Thank you for the great work on this project.

Activity

  1. phernandez commented on Apr 29, 2026

    @phernandez
    Member

    Thanks for the detailed report. I traced this through the code and I think the most likely explanation is the zombie MCP processes you flagged but did not kill — not stale state inside the database.

    What reset --reindex actually does

    src/basic_memory/cli/commands/db.py:104-130 — reset unlinks the SQLite files outright:

    for suffix in ["", "-shm", "-wal"]:
        path = db_path.parent / f"{db_path.name}{suffix}"
        if path.exists():
            path.unlink()

    Then it runs migrations to create a brand new, empty memory.db. After this point, there is no entities row, no FTS row, and no embedding row anywhere in the file. The subsequent _reindex_projects call uses sync_service.sync(...), which sees an empty DB so every file on disk is treated as "new" and inserted from scratch. There's no path I can find where a "stale" FTS row could survive a true reset.

    Why the phantoms can still appear

    On macOS / Linux, unlink only removes the directory entry. Any process that already has the file open keeps reading and writing the original inode until it closes its handles. So if a zombie basic-memory mcp process is alive when reset runs:

    • That process keeps its connection to the old memory.db inode (now unlinked but not freed).
    • A new, empty memory.db is created at the same path for the CLI to use.
    • Newly-spawned MCP processes (e.g. from a fresh Claude Desktop session) attach to the new file.
    • But any tool call that gets routed to a zombie MCP process queries the old inode and returns the pre-reset FTS rows — including the phantom titles you saw.

    That matches your observation that read_note / fetch correctly say "Document not found" while search keeps returning phantoms: those calls almost certainly landed in different MCP processes, one on the new DB, one on the old inode.

    It also explains why reindex --search did nothing — it ran against the new file, which never had the phantoms in the first place.

    Suggested next step before we treat this as a code bug

    Before doing anything else, please:

    1. Quit Claude Desktop fully.
    2. pkill -9 -f "basic-memory mcp" until pgrep -f "basic-memory mcp" returns nothing.
    3. Re-launch Claude Desktop.
    4. Re-run a search.

    If the phantoms are gone, we have our answer (zombie process holding the old DB inode) and we can think about whether reset should warn / refuse to run while MCP processes are alive. If the phantoms persist after step 4, please reopen with the new repro and I'll dig in further — at that point it would imply the phantoms are actually present in the on-disk DB after the reset, which would be a different bug.

    Leaving this open for your follow-up.

  2. phernandez commented on Apr 29, 2026

    @phernandez
    Member

    @BunkerBuster73 please see the comment above and see if you can reproduce locally

  3. BunkerBuster73 commented on Apr 29, 2026

    @BunkerBuster73
    Author

    Confirmed — your diagnosis is correct. The phantoms were coming from zombie MCP processes holding the old memory.db inode, not from on-disk state.

    Verification

    Before: 16 live basic-memory mcp processes accumulated across prior Claude Desktop sessions (none of them killed by my earlier partial cleanup).

    Clean repro per your instructions:

    1. Fully quit Claude Desktop (Cmd+Q, verified gone from Dock).
    2. pkill -9 -f "basic-memory mcp" → pgrep -f "basic-memory mcp" returned 0.
    3. Relaunched Claude Desktop. 8 fresh processes spawned (3 process chains, all <2 min old per ps -o etime).
    4. Re-ran the same search query that previously returned phantoms.

    Result:

    Before (with zombies) After clean restart
    search permalink notes/ai/notebooklm-py-installazione-disinstallazione-mac (deleted file) notes/ai/notebooklm-py-installazione-disinstallazione-mac-pipx (current file) ✅
    search title "... (Conda)" (pre-incident, stale) "... (Pipx)" (current frontmatter) ✅
    fetch on bare -mac permalink Document not found Document not found ✅

    The original asymmetry (search returning a permalink that fetch couldn't resolve) is gone — both APIs now agree. No phantoms.

    So: nothing wrong with reset --reindex itself. The new DB was always clean; tool calls were just being routed to zombie MCP processes still reading from the old inode.

    Suggestion for follow-up

    Your idea of having reset warn or refuse when MCP processes are alive would prevent this exact footgun. A few shapes that might work:

    • reset aborts with RuntimeError: N basic-memory mcp processes are still alive (PIDs: ...). Quit your MCP clients first, or pass --force.
    • A basic-memory doctor command (non-destructive) that lists live MCP PIDs, warns about zombies, and suggests the kill command. Useful as a general diagnostic, not just pre-reset.
    • Optionally, reset could os.kill(pid, SIGTERM) known MCP children itself when --force is passed, but that's more invasive and may surprise users running multiple clients.

    Happy to close this issue, or leave it open if you want to track the warn/refuse work against it. Whichever you prefer.

    Thanks for the fast and precise diagnosis — the inode-after-unlink explanation is the kind of thing that's obvious in hindsight but easy to miss when you're staring at "but I ran reset".

  4. phernandez commented on Apr 29, 2026

    @phernandez
    Member

    Thanks @BunkerBuster73 — your repro and the precise verification (16 zombies → pkill -9 → 0 zombies → phantoms gone) made this trivial to ship.

    Landed in #776 / 2fccc74a: bm reset now scans for live basic-memory mcp / bm mcp processes via psutil before unlinking memory.db. If any are found, it aborts with the PIDs and a platform-appropriate cleanup hint (pgrep -fa 'basic-memory mcp' on POSIX, Get-CimInstance Win32_Process on Windows). No auto-killing — the user is in control. --force is the documented escape hatch for scripted/CI workflows that have already verified no clients are attached.

    Closing this out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingneeds investigationIssue needs further investigation and/or refinement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions