Skip to content

fix(daemon): operational safety — WAL checkpoint, pending eviction, cursor pruning, periodic rescan #771

Closed

Description

@Sinity

Problem

The daemon operates without essential safety mechanisms. Without periodic WAL checkpointing, WAL could grow. Without pending-dict eviction, the watcher leaks memory. Without cursor pruning, old file rows remain forever. Without periodic rescan, inotify misses are never reconciled. Worker timeouts for stuck parse jobs. Bounded _pending dict with eviction.

Deep audit (2026-05-03, ~65 subagents) found concrete file:line evidence for all of these and additional gaps.

Connection profile bypasses (14 sites)

Every bare sqlite3.connect() without WRITE_CONNECTION_PRAGMA_STATEMENTS (WAL, busy_timeout=30s, foreign_keys=ON, cache_size=128MiB, mmap=1GiB, synchronous=NORMAL):

Severe (read-write on main archive, all pragmas missing):

  • write_gateway.py:120 — dead code (ArchiveWriteGateway never instantiated), but severe if wired
  • reset.py:44,62,145 — 3 sites in reset command
  • blob_gc.py:141 — GC operations without busy_timeout
  • sampling_db.py:163,274 — schema sampling
  • corpus.py:229 — validation with conditional writes
  • sqlite_vec_runtime.py:24 — missing 7 of 9 pragmas
  • daemon/cli.py:39 — FTS startup check, no busy_timeout

WAL checkpoint

  • Only wal_autocheckpoint=10000 (~40 MiB). No periodic/forced checkpoint.
  • One manual PRAGMA wal_checkpoint(TRUNCATE) in repair.py:915, never called automatically.
  • No checkpoint on connection close — unclean shutdown leaves up to 40 MiB in WAL.

GC lease mechanism non-functional

blob_gc.py:47 queries pending_blob_refs for lease safety but NO code inserts into this table. _has_active_lease() always returns False. GC could delete blobs mid-ingest. MIN_AGE_S=60 and generation tracking are defense-in-depth but the primary mechanism is non-functional.

Pidfile lifecycle

  • daemon/cli.py:53-64: pidfile written, never cleaned up on ANY exit path (no finally, no atexit, no SIGTERM handler)
  • No flock/advisory lock — TOCTOU race on simultaneous starts
  • No process identity verification — only os.kill(pid, 0), any process with that PID blocks daemon start
  • Status command never reads pidfile — cannot report daemon liveness

Daemon silence

  • Zero logger.info() calls in entire polylogue/daemon/ directory
  • HTTP access logs explicitly suppressed (daemon/http.py:41-42, no-op log_message)
  • configure_logging() never called at daemon startup
  • faulthandler not installed at any entry point
  • No periodic heartbeat or progress reporting during watcher catch-up scan

Daemon shutdown fragility

  • _drain_tasks() (cli.py:119-121): asyncio.gather(return_exceptions=True) results never inspected
  • asyncio.gather() at cli.py:99,101 has no timeout — fully dependent on SIGINT→CancelledError
  • awatch can enter tight loop preventing cancellation
  • _catch_up() has no stop-event check — startup/shutdown latency proportional to file count
  • Orphaned _debounced child tasks (watcher.py:110) not cancelled at shutdown, access closed DB
  • ThreadingHTTPServer uses non-daemon threads — stuck request blocks process exit

Acceptance criteria

  • All 14 connection sites route through connection_profile.py factories. Linter rejects bare sqlite3.connect() in production code.
  • Periodic WAL checkpoint in daemon loop (every 5 min or after N writes). WAL checkpoint on daemon shutdown.
  • GC lease populated: pending_blob_refs inserted before ingest, removed after success.
  • Pidfile cleaned on exit. Advisory flock. Process identity verified via /proc/PID/cmdline.
  • Daemon logs startup, shutdown, periodic health. faulthandler installed.
  • _drain_tasks inspects results. gather has timeout. _catch_up checks stop event.
  • _debounced child tasks tracked and cancelled at shutdown. Non-daemon threads avoided or timed out.
  • Cursor pruning: old source_file_cursor rows cleaned up.
  • Pending dict bounded with eviction.
  • Worker timeouts for stuck parse jobs.

Ref: deep audit C2, C4, P3-7, 3a, 3b, 4b. Ref #730, #778 (closed, consolidated here).

Activity

  1. Sinity commented on May 3, 2026

    @Sinity
    OwnerAuthor

    Concrete findings from deep audit (2026-05-03)

    15 subagents analyzed connection profiles, WAL behavior, and daemon operational safety. Key additions to this issue:

    Connection profile bypasses (14 sites)

    Every bare sqlite3.connect() site without WRITE_CONNECTION_PRAGMA_STATEMENTS:

    • write_gateway.py:120 — dead code (never instantiated), but would be severe if wired
    • reset.py:44,62,145 — 3 sites, all zero-pragma
    • blob_gc.py:141 — GC operations without busy_timeout
    • sampling_db.py:163,274 — schema sampling, no busy_timeout
    • corpus.py:229 — validation, no pragmas
    • sqlite_vec_runtime.py:24 — vector operations, missing 7 of 9 pragmas
    • daemon/cli.py:39 — FTS startup check, no busy_timeout
    • insights/storage.py:77, daemon/events.py:44, live/cursor.py:73 — separate DBs, minimal pragmas
    • tail_overlay.py:33-34 — transient, acceptable

    WAL checkpoint

    • Only wal_autocheckpoint=10000 (40 MiB) — no periodic/forced checkpoint
    • One manual PRAGMA wal_checkpoint(TRUNCATE) in repair.py:915, never called automatically
    • No checkpoint on connection close — unclean shutdown leaves up to 40 MiB unmerged
    • Read-heavy workloads: WAL grows to 40 MiB and stays there; never truncated

    Busy timeout gaps

    • Properly configured: write 30s, read 1s
    • All bypass sites: 0s (immediate SQLITE_BUSY, no retry)
    • 1s read timeout risks failure during bulk writes

    Specific fix targets

    • connection_profile.py has the canonical profiles — route ALL connections through them
    • Add a periodic WAL checkpoint to the daemon loop (every 5 min or after N writes)
    • Add WAL checkpoint on daemon shutdown
  2. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor

    Resolved by PR #789. WAL checkpoint, pidfile with flock+cleanup, structured logging, faulthandler, GC leases populated, drain timeout 5.0s.

  3. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor

    Post-close check (2026-05-04)

    Re-verified the daemon code against the features claimed in this issue:

    Confirmed present:

    • WAL checkpoint — _periodic_wal_checkpoint() in cli.py, runs every 5 min ✓
    • Pidfile — _acquire_pidfile() + _verify_pidfile() via fcntl.flock ✓
    • Task drain with timeout — _drain_tasks() with 5s timeout ✓

    Not found in current daemon code:

    • Cursor pruning — no periodic cleanup of old live_cursor rows
    • Pending dict eviction — no bounded _pending dict or LRU eviction in watcher
    • Periodic rescan — no scheduled full directory rescan to catch inotify misses
    • Worker timeouts — no timeout on stuck parse jobs

    If these were implemented differently than expected (e.g., cursor pruning happens implicitly, rescan isn't needed because inotify is reliable on this filesystem), a brief note on the implementation choice would help future readers.

    Ref: #830 (daemon ops — remaining hardening items)

  4. reopened this on May 8, 2026
  5. Sinity commented on May 8, 2026

    @Sinity
    OwnerAuthor

    Reopened during the closed-issue audit.

    The post-close check on this issue explicitly found missing operational-safety items after the original "resolved" comment: cursor pruning, bounded pending-path eviction, periodic rescan for missed filesystem events, and worker timeouts for stuck parse jobs. Current grep still shows an unbounded _pending_paths set in the live watcher and no obvious pruning/rescan owner.

    WAL checkpoint, pidfile locking, and drain timeout can remain marked done; keep this issue open for the remaining daemon operational-safety items unless they are split into narrower issues.

  6. Sinity commented on May 8, 2026

    @Sinity
    OwnerAuthor

    Closing: core implementation landed. Remaining edges are incremental.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions