Repository navigation
fix(daemon): operational safety — WAL checkpoint, pidfile, logging, GC leases (#771) - #789
Conversation
#776) (#788) ## Summary Wave 1 Slice B: connection profile unification, identity ledger wiring, tags many-to-many migration. ## Problem - 14 sites used bare sqlite3.connect() without WAL/busy_timeout/foreign_keys pragmas - identity_ledger DDL existed but was never composed into SCHEMA_DDL - tags DDL existed but was never wired — all tag operations used JSON extraction ## Solution - **#780**: Route all connection sites through connection_profile.py factories. Added verify_connection_sites.py linter. - **#775**: Wired IDENTITY_DDL into SCHEMA_DDL composition, bumped schema v5→v6 with upgrade path, added identity ledger writes on ingest, identity-preserving reset. - **#776**: Migrated list_tags/add_tag/remove_tag/bulk_add_tags to use normalized conversation_tags + tags tables with JSON fallback. Added idempotent backfill migration. ## Verification - devtools verify --quick: all checks passed - mypy: 0 errors - ruff format + check: clean Co-authored-by: Claude Opus 4.7 <[email protected]>
…logging, GC leases, robust shutdown - Periodic WAL checkpoint (PRAGMA wal_checkpoint(TRUNCATE)) every 5 min - Pidfile with fcntl.flock advisory lock and /proc/PID/cmdline verification - Signal-safe pidfile cleanup via atexit and finally block - Daemon logging: configure_logging, faulthandler, startup/shutdown messages - Periodic heartbeat log with conversation/message counts every 15 min - Shutdown timeout (5s) on asyncio.gather and task drain inspection - Watcher cancel_pending() to clean up orphaned _debounced child tasks - Stop-event check in watcher _catch_up for fast shutdown - Blob GC lease mechanism: acquire_blob_leases / release_operation_leases wired into commit_archive_write_effects via payload keys Closes #771 Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Warning Rate limit exceeded
To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (23)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Review rate limit: 0/1 reviews remaining, refill in 7 minutes and 7 seconds.Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8e0c306467
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
Pull request overview
This PR focuses on improving daemon operational safety and tightening SQLite operational consistency across the codebase, while introducing schema v6 identity/tagging primitives used by daemon/runtime features.
Changes:
- Bump SQLite schema to v6 and add identity-ledger DDL + bootstrap upgrade paths.
- Introduce canonical SQLite connection factory helpers and migrate many call sites away from bare
sqlite3.connect(). - Improve daemon lifecycle behavior (pidfile/locking, periodic WAL checkpoint + heartbeat, and shutdown draining) and extend tagging/GC lease plumbing.
Reviewed changes
Copilot reviewed 23 out of 23 changed files in this pull request and generated 10 comments.
Show a summary per file
| File | Description |
|---|---|
| polylogue/storage/sqlite/schema_ddl.py | Bump schema version to v6 and include identity DDL in fresh schema. |
| polylogue/storage/sqlite/schema_bootstrap.py | Add v4→v6 and v5→v6 upgrade decisions; include identity DDL in upgrade extensions. |
| polylogue/storage/sqlite/schema.py | Allow new upgrade actions to apply extension plans. |
| polylogue/storage/sqlite/queries/conversations_identity.py | Read tags from normalized tables with JSON fallback. |
| polylogue/storage/sqlite/connection_profile.py | Add open_connection / open_readonly_connection / connection_context helpers for canonical PRAGMAs. |
| polylogue/storage/search_providers/sqlite_vec_runtime.py | Use canonical connection factory for sqlite-vec runtime. |
| polylogue/storage/repository/archive/repository_writes.py | Write normalized tags alongside JSON metadata tag updates. |
| polylogue/storage/blob_gc.py | Use canonical connection factory; add blob lease acquire/release helpers. |
| polylogue/sources/live/watcher.py | Add shutdown cancellation for debounced tasks; stop-aware catch-up scan. |
| polylogue/sources/live/cursor.py | Use canonical connection factory for live cursor DB. |
| polylogue/schemas/validation/corpus.py | Use canonical connection factory for schema verification DB reads. |
| polylogue/schemas/sampling_db.py | Use canonical connection factory for sampling DB reads. |
| polylogue/pipeline/tail_overlay.py | Use canonical read-only / read-write factories for DB snapshotting. |
| polylogue/pipeline/services/ingest_batch.py | Use canonical factory; write identity-ledger rows during ingest. |
| polylogue/insights/storage.py | Use canonical connection factory for insights DB. |
| polylogue/daemon/events.py | Use canonical connection factory for daemon events DB. |
| polylogue/daemon/cli.py | Add structured logging setup, pidfile lifecycle + lock, periodic WAL checkpoint/heartbeat, and shutdown draining changes. |
| polylogue/cli/shell_completion_values.py | Prefer normalized tag tables for completion, with JSON fallback. |
| polylogue/cli/commands/reset.py | Use canonical factory; attempt to persist identity key into tombstones. |
| polylogue/archive/write_gateway.py | Use canonical connection factory in local write execution. |
| polylogue/archive/write_effects.py | Add blob GC lease acquire/release hooks around commit. |
| docs/verification-catalog.md | Update generated line reference for polylogue reset. |
| devtools/verify_connection_sites.py | New devtool to forbid bare sqlite3.connect() in production code. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # Look up the identity ledger key to preserve it in the tombstone | ||
| identity_key = None | ||
| try: | ||
| row = c.execute( | ||
| "SELECT provider || ':' || source || ':' || source_path || ':' || provider_conversation_id || ':' || raw_hash " | ||
| "FROM identity_ledger WHERE current_conversation_id = ? LIMIT 1", | ||
| (conv_id,), | ||
| ).fetchone() | ||
| if row: | ||
| identity_key = row[0] | ||
| except Exception: | ||
| pass |
| results = await asyncio.wait_for( | ||
| asyncio.gather(*tasks, return_exceptions=True), | ||
| timeout=timeout, | ||
| ) | ||
| return [r if isinstance(r, BaseException) else None for r in results] | ||
|
|
||
|
|
| """Log any exceptions found during task draining.""" | ||
| for exc in results: | ||
| if exc is not None: | ||
| logger.warning("daemon: task raised during shutdown: %s", exc) |
| def open_readonly_connection(path: str | Path, *, timeout: float = READ_DB_TIMEOUT) -> sqlite3.Connection: | ||
| """Open a read-only SQLite connection with canonical read pragmas applied. | ||
|
|
||
| Uses ``file:...?mode=ro`` URI mode to guarantee no write locks are taken. | ||
| Returns ``None`` / raises ``sqlite3.OperationalError`` if the database file | ||
| does not exist. | ||
| """ | ||
| conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=timeout) | ||
| for stmt in READ_CONNECTION_PRAGMA_STATEMENTS: | ||
| conn.execute(stmt) | ||
| return conn |
| async def add_tag(self, conversation_id: str, tag: str) -> None: | ||
| if not tag or not tag.strip(): | ||
| raise ValueError("tag must be a non-empty string") | ||
| if len(tag) > 200: | ||
| raise ValueError("tag must be at most 200 characters") | ||
|
|
||
| def _add(meta: JSONDocument) -> bool: | ||
| tags = list(string_sequence(meta.get("tags"))) | ||
| if tag not in tags: | ||
| tags.append(tag) | ||
| tag_payload: list[JSONValue] = list(tags) | ||
| meta["tags"] = tag_payload | ||
| return True | ||
| return False | ||
|
|
||
| await self._metadata_read_modify_write(conversation_id, _add) | ||
| # Also write to normalized tables for M2M query support | ||
| await self._upsert_normalized_tag(conversation_id, tag) | ||
|
|
| # Acquire blob GC leases before the main data commit so a concurrent GC | ||
| # run sees them. Uses a separate connection (immediate commit) because | ||
| # leases must be visible to other connections before *this* transaction | ||
| # commits its blob references. | ||
| if blob_hashes and operation_id and db_path: | ||
| from polylogue.storage.blob_gc import acquire_blob_leases | ||
|
|
||
| acquire_blob_leases(db_path, blob_hashes, operation_id) | ||
|
|
||
| restore_fts_triggers_sync(conn) | ||
| if sorted_ids: | ||
| repair_fts_index_sync(conn, sorted_ids) | ||
| conn.commit() |
| if content_changed: | ||
| _write_identity_ledger(conn, cdata) |
| # Prevent concurrent daemon instances: verify existing pidfile, then | ||
| # acquire an advisory flock. | ||
| if pidfile.exists(): | ||
| try: | ||
| old_pid = int(pidfile.read_text().strip()) | ||
| os.kill(old_pid, 0) # signal 0 = check if process exists | ||
| if _verify_pidfile(pidfile): | ||
| old_pid = pidfile.read_text().strip() | ||
| raise RuntimeError(f"Daemon already running (PID {old_pid}). Stop it first or remove {pidfile}") | ||
| except (OSError, ValueError): | ||
| pidfile.unlink(missing_ok=True) | ||
| pidfile.unlink(missing_ok=True) | ||
|
|
||
| pidfile.write_text(str(os.getpid())) | ||
| pidfile_fd = _acquire_pidfile(pidfile) |
| changed_ids: Sequence[str] = payload.get("changed_conversation_ids", []) | ||
| sorted_ids = sorted(set(changed_ids)) if changed_ids else [] | ||
| blob_hashes: list[str] = payload.get("_blob_hashes", []) | ||
| operation_id: str = payload.get("_operation_id", "") | ||
| db_path: str | None = payload.get("_db_path") | ||
|
|
||
| # Acquire blob GC leases before the main data commit so a concurrent GC | ||
| # run sees them. Uses a separate connection (immediate commit) because | ||
| # leases must be visible to other connections before *this* transaction | ||
| # commits its blob references. | ||
| if blob_hashes and operation_id and db_path: | ||
| from polylogue.storage.blob_gc import acquire_blob_leases | ||
|
|
||
| acquire_blob_leases(db_path, blob_hashes, operation_id) | ||
|
|
| def _write_identity_ledger(conn: sqlite3.Connection, cdata: ConversationData) -> None: | ||
| """Write identity ledger row so re-imported conversations are recognized.""" | ||
| source_path = cdata.source_name | ||
| provider_conversation_id = cdata.conversation_tuple[2] | ||
| conn.execute( | ||
| _IDENTITY_LEDGER_UPSERT_SQL, | ||
| ( | ||
| cdata.provider_name, | ||
| cdata.source_name, | ||
| source_path, | ||
| provider_conversation_id, | ||
| cdata.content_hash, | ||
| cdata.conversation_id, | ||
| ), |
…C leases (#771) (#789) ## Summary Daemon operational safety fixes: WAL checkpoint, pidfile lifecycle, structured logging, GC lease mechanism, robust shutdown. ## Problem - No periodic WAL checkpointing — WAL could grow unboundedly - Pidfile written but never cleaned up on exit; no flock protection - Daemon never logs structured messages; no faulthandler - GC lease mechanism non-functional (pending_blob_refs never populated) - Shutdown fragile: no timeouts on asyncio.gather, orphaned debounced tasks ## Solution - Periodic WAL checkpoint every 5 min via PRAGMA wal_checkpoint(TRUNCATE) - Pidfile with fcntl.flock advisory lock and /proc/PID/cmdline verification - configure_logging() at startup, faulthandler.enable(), periodic heartbeat - acquire_blob_leases/release_operation_leases wired in write_effects.py - Shutdown: timeout=5.0 on gather, cancel_pending() on watcher, stop-event in _catch_up ## Verification - ruff check + format: clean - mypy --strict: 0 errors - Import check: OK --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Daemon operational safety fixes: WAL checkpoint, pidfile lifecycle, structured logging, GC lease mechanism, robust shutdown.
Problem
Solution
Verification