iai-personal-memory-engine icon indicating copy to clipboard operation
iai-personal-memory-engine copied to clipboard

[bug] `iter_record_columns` raises `disk I/O error` inside the daemon, blocking SCHEMA_MINE and the hippea cascade

Open farislmn opened this issue 3 months ago • 4 comments

Version: iai-pme 3.0.8 (pip, PyPI), iai CLI 3.0.8 Platform: Ubuntu LXC on Proxmox, Linux 6.14.11-9-bpo12-pve, Python 3.12, x86_64 (AVX2 available) Store: stdlib sqlite3 driver, schema_version=1, 2218 records, 11.8 MB First observed: 2026-08-17 05:19:55 UTC — the first day in the journal, i.e. since installation Frequency: ~2,800 occurrences per day, every day, unbroken


Summary

Every call into HippoStore.iter_record_columns() fails inside the daemon process with sqlite3.OperationalError: disk I/O error, raised on the first page of the keyset scan (last_id == ""). Because that method is the single seam for full-corpus column scans, both callers that depend on it die:

  • lilli/cycle/sleep_pipeline/_schema_mine.py:19 → induce_schemas_tier0() → the sleep pipeline aborts at SleepStep.SCHEMA_MINE, so no insight is ever minted;
  • daemon/_watchdog.py:186 → retrieve.build_runtime_graph() → the hippea cascade loop fails on every iteration.

iai-mcp doctor surfaces this only indirectly, as [FAIL] (bb) nightly insight mint — 3 consecutive nights without a minted insight. The underlying exception is not reported by any check, so on this machine the sleep pipeline appears to have never completed since install: .daemon-state.json still carries sleep_cycle_baseline_at = "2026-08-17T04:49:50.775855+00:00".

The key detail

The failure is specific to the daemon process. The identical scan succeeds from any other process on the same machine, against the same live store, while the daemon is running:

  • 40 consecutive full keyset scans (SELECT id, centrality FROM records WHERE id > ? ORDER BY id LIMIT 256, paged to exhaustion, 2218 rows each) from a separate process: 40/40 clean.
  • The same scan driven through the package's own connection seam (iai_mcp.hippo._raw_open.open_store_conn(path, read_only=True), which returns None here and falls through to _sqlite_stdlib.connect): clean, 2218 rows.
  • PRAGMA quick_check on brain.sqlite3: ok.

So the database is intact and the SQL is fine; something about the daemon's process state breaks read-only opens made within it.

Suspected cause (unconfirmed)

The daemon holds file descriptors to a deleted WAL and WAL-index while live ones exist on disk:

$ ls -l /proc/<daemon-pid>/fd
 9 -> /mnt/iai-cache/iai-mcp/hippo/brain.sqlite3-wal (deleted)
10 -> /mnt/iai-cache/iai-mcp/hippo/brain.sqlite3-shm (deleted)
17 -> /mnt/iai-cache/iai-mcp/hippo/brain.sqlite3

Both deleted fds were created within seconds of daemon startup, and the first disk I/O error appears 7 seconds after a clean start. SQLite shares one WAL-index mapping per inode per process, so if the daemon unlinks -wal/-shm during boot while its writer connection still holds them, every subsequent read-only open in that process inherits the dead mapping and returns SQLITE_IOERR. A fresh process gets a clean mapping, which is exactly the observed split.

I have not confirmed this, and I could not obtain the extended result code — the stdlib driver surfaces only "disk I/O error".

Contributing issue in the retry path

store/_store.py:2053 treats any OperationalError that is not a snapshot fence as fatal:

except _errors.OperationalError as exc:
    if not _is_snapshot_fence(exc):
        raise

_is_snapshot_fence (hippo/_ro_pool.py:65) matches only the literal string "read-only snapshot invalidated", so "disk I/O error" re-raises immediately. There is already a working streaming-reader fallback a few lines above (used when db_path is falsy), but nothing routes to it when the snapshot connection is unusable. Falling back there would keep SCHEMA_MINE and the cascade alive even on a store whose read-only snapshot path is broken.

Second, possibly related symptom

After the sleep pipeline failed three times on 2026-08-29 (02:00:05, 02:10:06, 02:20:07, each backing off 600s), it stopped attempting altogether. There are no sleep-cycle log entries at all on Aug 30 or Aug 31 in the 01:50–03:00 window, despite the default consolidation window being 02:00–06:00 local and iai-mcp doctor reporting (l) sleep cycle quarantine — no quarantine active. Lifecycle history for the last 24h shows only DROWSY=5, WAKE=5 — no sleep state is ever entered.

This machine is headless (LXC), so (n) HID idle source reports HIDIdleTime: unavailable, pmset: clean, available: none and L6 falls back to heartbeat-idle only. That may or may not be connected.

Reproduction

Not reliably reproducible on demand — it is continuous on this install and absent from every external process. On this machine:

  1. Start the daemon (systemctl --user start iai-mcp-daemon).
  2. Watch the journal: journalctl --user -u iai-mcp-daemon -f.
  3. Within ~10 seconds, hippea cascade loop iteration failed appears with the traceback below, and repeats every 60s (IAI_MCP_HIPPEA_MIN_INTERVAL_SEC default).
  4. In the 02:00–06:00 local window, sleep step SCHEMA_MINE failed: disk I/O error appears on the same seam.

Tracebacks

Sleep pipeline (the one that blocks insight minting):

sleep step SCHEMA_MINE failed: disk I/O error
Traceback (most recent call last):
  File ".../iai_mcp/_sqlite_stdlib.py", line 69, in _call
    return bound(*args, **kwargs)
sqlite3.OperationalError: disk I/O error

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File ".../iai_mcp/lilli/cycle/sleep_pipeline/__init__.py", line 540, in _run_internal
    done, payload = method(interrupt_check)
  File ".../iai_mcp/lilli/cycle/sleep_pipeline/_schema_mine.py", line 19, in step_schema_mine
    candidates = induce_schemas_tier0(self._store)
  File ".../iai_mcp/lilli/cycle/schema.py", line 72, in induce_schemas_tier0
    rows = list(store.iter_record_columns(["id", "tags_json"], batch_size=1024))
  File ".../iai_mcp/store/_store.py", line 2048, in iter_record_columns
    rows = conn.execute(page_sql, (last_id,)).fetchall()
  File ".../iai_mcp/_sqlite_stdlib.py", line 125, in execute
    _call(self._iai_stdlib_conn.execute, *args, **kwargs)
  File ".../iai_mcp/_sqlite_stdlib.py", line 73, in _call
    raise translated from exc
iai_mcp.errors.OperationalError: disk I/O error

sleep pipeline failed at SleepStep.SCHEMA_MINE — next attempt backed off 600s so awake clients are not
starved by the retry loop

Hippea cascade loop (same seam, different caller):

hippea cascade loop iteration failed
Traceback (most recent call last):
  File ".../iai_mcp/_sqlite_stdlib.py", line 69, in _call
    return bound(*args, **kwargs)
sqlite3.OperationalError: disk I/O error

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File ".../iai_mcp/daemon/_watchdog.py", line 186, in _hippea_cascade_loop
    _graph, assignment, _rc = await asyncio.to_thread(
  File ".../iai_mcp/retrieve.py", line 1112, in build_runtime_graph
    bundle = _build_runtime_graph_impl(store)
  File ".../iai_mcp/retrieve.py", line 1224, in _build_runtime_graph_impl
    for row in store.iter_record_columns(
  File ".../iai_mcp/store/_store.py", line 2048, in iter_record_columns
    rows = conn.execute(page_sql, (last_id,)).fetchall()
iai_mcp.errors.OperationalError: disk I/O error

Ruled out

Hypothesis Evidence against
Database corruption PRAGMA quick_check → ok; 2218 records readable
Disk full root 83% used, 4.9 GB free; store dataset 1% of 100 GB
ZFS backing store ~/.iai-mcp was symlinked to a ZFS dataset on Aug 30; errors start Aug 17
fd exhaustion daemon holds 20 fds against a soft limit of 8192
Bad SQL / missing column identical query succeeds from another process
Stale native extension iai_mcp_native imports cleanly; embedder encodes, backend=rust
Embedder / store identity drift (ii) store embed identity matches

Occurrence counts per day (journal, all retained)

2335  Aug 17     2878  Aug 23     2878  Aug 28
3285  Aug 18     2758  Aug 24     2968  Aug 29
2878  Aug 19     3787  Aug 25     2886  Aug 30
2378  Aug 20     2586  Aug 26     1423  Aug 31 (partial)
2826  Aug 21     2878  Aug 27
2489  Aug 22

What would help

  1. Log the SQLite extended result code on this path — "disk I/O error" alone is not diagnosable by a user.
  2. Have iter_record_columns degrade to the existing streaming reader when the snapshot connection is unusable and nothing has been yielded yet, instead of re-raising.
  3. Have iai-mcp doctor report the underlying exception behind (bb) rather than only the symptom.

Local workaround currently applied

A patch to store/_store.py (backed up as _store.py.bak.20260831) that catches the non-fence OperationalError when last_id == "" and falls back to the streaming reader. It will be overwritten by iai-mcp self-update.

farislmn avatar Aug 31 '26 13:08 farislmn

Update after six days on 3.0.8, with two findings that revise the original report and one that is new.

The short version: [PASS] (bb) nightly insight mint now reports a fresh insight on this machine, which looks like the de fect has cleared. It has not. The scan still fails on every daemon boot; what changed is that one caller no longer dies of it, while others still do.

1. The defect reproduces on every boot

Current daemon, PID 122442, started 2026-09-01 15:24:40. From journald a few hours later:

Sep 01 23:50:54 clawd iai-mcp-daemon[122442]: iter_record_columns: snapshot scan unusable (disk I/O error); falling back t
o the streaming reader
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]: hippea cascade loop iteration failed
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]: Traceback (most recent call last):
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:   File ".../iai_mcp/daemon/_watchdog.py", line 186, in _hippea_cascade_loop
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:   File ".../iai_mcp/retrieve.py", line 1112, in build_runtime_graph
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:   File ".../iai_mcp/retrieve.py", line 1224, in _build_runtime_graph_impl
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:     for row in store.iter_record_columns(
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:   File ".../iai_mcp/store/_store.py", line 2108, in iter_record_columns
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:   File ".../iai_mcp/hippo/_table.py", line 1241, in to_batches
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:     yield from self._drain_snapshot_with_fence_recovery(
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:   File ".../iai_mcp/hippo/_table.py", line 1272, in _drain_snapshot_with_fen
ce_recovery
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:   File ".../iai_mcp/hippo/_table.py", line 1333, in _drain_to_batches
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]:     cursor = (conn if conn is not None else self._conn).execute(sql)
Sep 01 23:50:54 clawd iai-mcp-daemon[122442]: iai_mcp.errors.OperationalError: disk I/O error

The deleted-descriptor pattern from the original report is present again on this boot. From /proc/122442/fd:

 9 -> /mnt/iai-cache/iai-mcp/hippo/brain.sqlite3-wal (deleted)    [opened at boot, 15:24]
10 -> /mnt/iai-cache/iai-mcp/hippo/brain.sqlite3-shm (deleted)    [opened at boot, 15:24]
 8,17,18,20,22 -> /mnt/iai-cache/iai-mcp/hippo/brain.sqlite3      [opened later, 23:09]

Both deleted descriptors date from daemon start, the healthy ones from later. At path level the live -wal (0 bytes, post -checkpoint) and -shm (32768 bytes) are fine, so the condition is confined to those two boot-time descriptors. A restart does not clear it, it only resets the clock.

2. The streaming-reader fallback inherits the same defect

I patched this install locally after filing the original report: store/_store.py now catches a non-fence OperationalErr or on the first page only (last_id == "") and degrades to the LanceDB streaming reader. That is why SCHEMA_MINE survi ves and insight minting passes. It is a workaround, not a fix, and it is narrower than it looks.

The fallback opens its own connection inside the same daemon process, so it is subject to the identical defect. When it fa ils there is no second fallback, and the exception is uncaught:

Sep 01 15:22:16 clawd iai-mcp-daemon[117228]: iter_record_columns: snapshot scan unusable (disk I/O error); falling back t
o the streaming reader
Sep 01 15:22:16 clawd iai-mcp-daemon[117228]: sqlite3.OperationalError: disk I/O error
Sep 01 15:22:16 clawd iai-mcp-daemon[117228]:   File ".../store/_store.py", line 2108, in iter_record_columns
Sep 01 15:22:16 clawd iai-mcp-daemon[117228]: iai_mcp.errors.OperationalError: disk I/O error
Sep 01 15:22:16 clawd iai-mcp-daemon[117228]: processed salience writer failed: disk I/O error

_drain_snapshot_with_fence_recovery (hippo/_table.py:1272-1297) matches on the string "read-only snapshot invalidated " and re-raises anything else, so a disk I/O error propagates into background loops that have no handler for it. Two di e this way in the logs above: _hippea_cascade_loop (daemon/_watchdog.py:186) and a processed-salience writer.

One detail that may help triage: the fallback cannot silently return a truncated or empty result set. It either yields cor rectly or raises. So this does not manifest as quiet data loss, only as killed loops.

I would be glad to open a PR that makes those two call sites degrade rather than die, if that is a direction you would acc ept. It treats a symptom and I would rather not send it without asking, since it may cut across whatever the real fix look s like.

3. New: graceful shutdown never completes, so every stop is a SIGKILL

This was not in the original report and may be the more useful thread.

The daemon registers shutdown handlers correctly. daemon/__init__.py:2055-2062 installs loop.add_signal_handler(sig, sh utdown.set) for SIGTERM, SIGINT and SIGHUP, and there is an earlier boot-window tracer at daemon/__init__.py:1745. The signal is received and shutdown begins. It then does not finish. Every stop in the journal follows the same pattern, sixty seconds apart to the second:

Sep 01 13:36:26 clawd systemd[263]: Stopping iai-mcp-daemon.service...
Sep 01 13:37:26 clawd systemd[263]: iai-mcp-daemon.service: State 'stop-sigterm' timed out. Killing.
Sep 01 13:37:26 clawd systemd[263]: iai-mcp-daemon.service: Killing process 117022 (iai lilli (iai_) with signal SIGKILL.
Sep 01 13:37:26 clawd systemd[263]: iai-mcp-daemon.service: Main process exited, code=killed, status=9/KILL

Same at 15:23:40 → 15:24:40. The unit ships TimeoutStopSec=60, so the daemon is given a full minute and uses all of it without exiting.

Two supporting details. The boot-window tracer wrote zero daemon_boot_window_signal lines to .daemon-watchdog.log, so the signals arrived after the boot window and reached the asyncio handler as intended. This is not a boot race. And .daem on-watchdog.log contains no shutdown, stopping, or closing lines at all, so whatever runs after shutdown.set() produces no trace before it hangs.

To be explicit about the limit of this: that shutdown hangs is confirmed. Where it hangs is not. I have not yet captured a stack at the moment of the hang.

Why 3 may bear on 1

A SIGKILLed process cannot checkpoint or cleanly close its WAL. If every stop on this machine is a hard kill, then every b oot opens a store left mid-flight by the previous one, which is a plausible route to boot-time descriptors pointing at unl inked -wal and -shm inodes.

Stated as a prediction rather than a conclusion, so it can be falsified: if the shutdown hang were fixed and the daemon ex ited cleanly, the next boot should not produce deleted -wal and -shm descriptors. I cannot test this, because no clean shutdown has occurred here to date. If the prediction fails, the two are independent and finding 1 needs its own root-cau se pass. I would not want this issue closed on a shutdown fix alone without checking that.

Next capture

main() registers faulthandler.register(signal.SIGUSR2, all_threads=True), described in its own comment as the sanction ed way to see where a live daemon is stuck. Next time I stop the daemon I will kill -USR2 during the sixty-second window and attach the all-threads stack. If there is something else you would rather have captured at the same moment, say so an d I will get both in one pass.

Also worth flagging, since it touches the same area: PR #126 is open against daemon boot and signal handling on Windows. I have not checked whether it overlaps finding 3.

Environment

Unchanged from the original report except as noted. Ubuntu LXC on Proxmox, Linux 6.14.11-9-bpo12-pve, Python 3.12, x86_64. Store now 2350 records, 13.2 MiB, on ZFS, mounted at /mnt/iai-cache since 2026-08-30, with ~/.iai-mcp a symlink to it (same inode confirmed by stat, not two stores).

Not memory pressure: memory.events reports oom_kill 0 at both the container and unit cgroup, MemoryMax=infinity, NR estarts=0. The SIGKILLs are stop-timeout escalation only.

farislmn avatar Sep 02 '26 02:09 farislmn

Root cause for the disk I/O error (finding 1). It is not the daemon, and it is not the sleep pipeline. iai-mcp doctor causes the fault it reports, and so does any other process that opens the store while the daemon is running.

This also falsifies the prediction I made in my previous comment. I suggested that fixing the shutdown hang (#160) might clear the stale -wal/-shm descriptors, on the theory that a SIGKILLed daemon could not checkpoint cleanly. It does not. The daemon exited cleanly, and the condition came back anyway. The two faults are independent.

Reproduction

Three commands. check counts the running daemon's orphaned WAL descriptors:

check() { ls -l /proc/$1/fd | grep -cE "(wal|shm) \(deleted\)"; }
systemctl --user restart iai-mcp-daemon && sleep 25
PID=$(systemctl --user show iai-mcp-daemon -p MainPID --value)

check $PID          # 0
iai-mcp doctor      # any run at all
check $PID          # 2

Clean before, orphaned after, same daemon and same PID. Every read-only open in that daemon afterwards fails with disk I/O error, because the WAL-index mapping it inherited is dead.

Isolating it

A plain external open reproduces it without doctor at all, and read-only opens do not:

External open, then close Daemon's orphaned fds
(baseline, nothing run) 0
sqlite3.connect("file:<db>?mode=ro", uri=True) 0
sqlite3.connect("<db>") 2
MemoryStore(access_mode=AccessMode.SHARED, read_only=True) 2

The last row is the important one. read_only=True behaves exactly like a read-write open.

Mechanism

HippoDB's read_only never reaches SQLite. _open_storage_connection (hippo/_db.py:472) connects with a bare path and takes no read_only parameter:

conn = _sqlite_stdlib.connect(
    db_path,
    check_same_thread=False,
    isolation_level=None,
    cached_statements=cached_statements,
)

read_only is applied afterwards, as a PRAGMA on that already-read-write connection (hippo/_db.py:580-581):

if read_only:
    self._conn.execute("PRAGMA query_only=ON")

query_only rejects write statements. It does not change how the file was opened. SQLite still counts the connection as read-write, so when it closes it checkpoints and unlinks -wal and -shm. A daemon holding those inodes is left with a mapping to deleted files, and every subsequent read-only open inside that process returns SQLITE_IOERR.

That explains the shape of the original report: identical scans succeed from a separate process (fresh mapping) and fail inside the daemon (dead mapping).

It also explains the frequency. The ~2,800 failures a day were never a timer. They track how often something opens the store, which on this machine means doctor runs and session starts. The first error after each daemon boot arrives when the first such open happens, not at a fixed offset.

Suggested direction

Thread read_only into _open_storage_connection and open with file:{path}?mode=ro (uri=True) rather than relying on query_only. A mode=ro open of this same store from an external process is confirmed above not to disturb the daemon.

I have not sent a PR for this one, deliberately. The read_only path is used widely (recall, export, doctor, the migration verifier), there is a second storage driver behind the same seam, and a read-only SQLite connection has real constraints around -shm creation that I cannot evaluate against your test matrix from outside. This is your design call, not a mechanical fix like #160. If you would like the patch, say what shape you would accept and I will write and test it.

A note on the doctor checks that read the store

Separately from the root cause: doctor/_storage_checks.py has three _sqlite_stdlib.connect(str(db_path), timeout=2.0) fallbacks (lines 405, 437, 593), each sitting under an open_store_conn(db_path, read_only=True) call and each running a SELECT-only query. They read as intended-read-only. I tried converting those three to mode=ro URIs first, and it did not fix the reproduction, because doctor also opens MemoryStore(..., read_only=True) in four places (_storage_checks.py:876, :957, :1045, doctor/__init__.py:181) and that is the opener that does the damage. Mentioning it only so you do not spend time on the same wrong lead. Those three still look worth tightening on their own merits.

Practical consequence meanwhile

On this machine, running iai-mcp doctor against a live daemon degrades that daemon until it is restarted. Anyone diagnosing a store problem is making it worse by looking, which is an unfortunate property for a health-check tool. Until this is fixed, the honest workaround is to restart the daemon after running doctor.

farislmn avatar Sep 02 '26 09:09 farislmn

thanks, solid report.

the disk I/O error is sqlite underneath, not the scan — on Proxmox LXC that's usually sqlite being fussy about locking on overlayfs or a bind-mount.

easiest fix: switch to the native engine, LILLI_STORAGE_DRIVER=lilli. it uses its own storage instead of sqlite, so it skips that path entirely (one-time migration of your store, and it's becoming the default next release anyway).

CodeAbra avatar Sep 02 '26 22:09 CodeAbra

Thank you. I applied it and the fix holds, though the mechanism looks different on my setup.

Result: iai-mcp doctor no longer orphans WAL descriptors. Counting deleted wal/shm fds on the daemon PID around a doctor run gives 2 after on the sqlite store and 0 after on the lilli store. Doctor now exits 0 with all checks passing.

Two points on the diagnosis:

  1. This box was never on overlayfs or a bind-mount. ~/.iai-mcp is a symlink to a dedicated ZFS dataset inside a Proxmox LXC. The locking friction may therefore be broader than the overlay and bind-mount cases, or the trigger may be something else.
  2. The lilli store still contains brain.sqlite3 and a -wal, so the driver does not use its own storage instead of sqlite. What changes is that it avoids the read_only=True path in hippo/_db.py (the one I reported above, where the connection opens read-write and PRAGMA query_only=ON is applied afterwards). Since sqlite-driver users still hit that path, it may be worth fixing directly rather than only routing around it.

Two notes on migrate-to-lilli, in case they help others:

  • It copies the hippo database only, not a store root. .crypto.key, config.json, lifecycle_state.json and user_model.json had to be copied across by hand. The key is mandatory, because migrated records keep their original ciphertext and a fresh key leaves the data unreadable.
  • Without the key present in the destination, the run emits graph_build_decrypt_failed once per record, then runtime_graph_cache_encrypt_failed. Verify still returned GREEN across counts, byte parity, decrypt parity, codec, and recall and temporal probes. A pre-flight check for the key, or a clearer error, would make that less alarming.

One behaviour change worth documenting: external readers now get store is locked: try_lock failed because the operation would block while the daemon holds the lock, reported by doctor under check (dd). That looks like the safer failure mode, however it differs from the sqlite driver, where concurrent external reads succeeded.

(written by Opus)

farislmn avatar Sep 03 '26 00:09 farislmn