Skip to content

fix(daemon): operational safety — WAL checkpoint, pidfile, logging, GC leases (#771) - #789

Merged
Sinity merged 2 commits into
masterfrom
feature/fix/daemon-operational-safety
May 4, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/fix/daemon-operational-safety

Conversation

@Sinity

@Sinity Sinity commented May 4, 2026

Copy link
Copy Markdown
Owner

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

Sinity and others added 2 commits May 4, 2026 03:41
#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]>
Copilot AI review requested due to automatic review settings May 4, 2026 01:48
@coderabbitai

coderabbitai Bot commented May 4, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 7 minutes and 7 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 63a36760-ccb6-4dec-991f-2959b62cc07b

📥 Commits

Reviewing files that changed from the base of the PR and between 8e2788c and 8e0c306.

📒 Files selected for processing (23)
  • devtools/verify_connection_sites.py
  • docs/verification-catalog.md
  • polylogue/archive/write_effects.py
  • polylogue/archive/write_gateway.py
  • polylogue/cli/commands/reset.py
  • polylogue/cli/shell_completion_values.py
  • polylogue/daemon/cli.py
  • polylogue/daemon/events.py
  • polylogue/insights/storage.py
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/pipeline/tail_overlay.py
  • polylogue/schemas/sampling_db.py
  • polylogue/schemas/validation/corpus.py
  • polylogue/sources/live/cursor.py
  • polylogue/sources/live/watcher.py
  • polylogue/storage/blob_gc.py
  • polylogue/storage/repository/archive/repository_writes.py
  • polylogue/storage/search_providers/sqlite_vec_runtime.py
  • polylogue/storage/sqlite/connection_profile.py
  • polylogue/storage/sqlite/queries/conversations_identity.py
  • polylogue/storage/sqlite/schema.py
  • polylogue/storage/sqlite/schema_bootstrap.py
  • polylogue/storage/sqlite/schema_ddl.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/daemon-operational-safety

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.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 7 minutes and 7 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

@Sinity
Sinity merged commit e1dc21a into master May 4, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/daemon-operational-safety branch May 4, 2026 01:48

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread polylogue/daemon/cli.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +70 to +81
# 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
Comment thread polylogue/daemon/cli.py
Comment on lines +326 to 332
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]


Comment thread polylogue/daemon/cli.py
"""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)
Comment on lines +118 to +128
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
Comment on lines 147 to 165
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)

Comment on lines +67 to 79
# 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()
Comment on lines +586 to +587
if content_changed:
_write_identity_ledger(conn, cdata)
Comment thread polylogue/daemon/cli.py
Comment on lines +219 to +227
# 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)
Comment on lines 61 to 75
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)

Comment on lines +287 to +300
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,
),
Sinity added a commit that referenced this pull request May 7, 2026
…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]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 62.F026 / P1: fixed-already at the checked revision: Startup no longer unlinks an unverifiable pidfile: it acquires the existing path in place at polylogue/daemon/cli.py:2341, after archive ownership. The pidfile is registered for exit cleanup only after successful acquisition at line 2349, preventing a failed contender from replacing the live lock inode.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 75.F020 / P2: fixed-already at the checked revision: add_tag no longer writes JSON metadata at all; polylogue/storage/repository/archive/repository_writes.py:74 invokes only the normalized-tag helper. That helper wraps tag creation and session linking in one backend transaction at :27, removing the two-transaction divergence described by the finding.

Only the rows listed above are dispositioned. Held findings remain open.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants