Skip to content

feat(daemon): add tiered health checks, config-driven notifications, maintenance docs - #920

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/health-ops-830
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/health-ops-830

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026

Copy link
Copy Markdown
Owner

Summary

Completes the remaining work in #830: four new health checks across all three tiers, config-driven notification backend selection, and daemon vs. operator maintenance documentation.

Problem

issue #830 specified tiered health, backup, alerts, and maintenance. PRs #898 and #903 landed the health infrastructure (typed DaemonHealth, fast/medium/expensive tiers, WAL checkpointing, pidfile locking). Four health checks, config-driven notifications, and maintenance docs remained.

Solution

New health checks (health.py)

  • FAST: _check_source_availability_fast() — verifies each watch root from default_sources() exists and is readable
  • MEDIUM: _check_insight_freshness_medium() — session profile coverage vs. total conversations; warns at >10% gap
  • MEDIUM: _check_repeated_stage_failures_medium() — recent ingest attempt failure rate from live_ingest_attempt table; samples latest error for context
  • EXPENSIVE: _check_blob_integrity_expensive() — bounded BlobStore.verify_all(max_failures=5) content verification
  • EXPENSIVE: _check_embedding_coverage_expensive() — coverage percentage + failure count when embedding is enabled; OK when disabled

Config-driven notifications (notifications.py + config.py)

  • Added _resolve_backend(backend_name) factory — currently supports "log" only, ready for future backends
  • send_notifications() now resolves backend from config when none is explicitly passed
  • PolylogueConfig gains notification_backend, health_check_interval_s, health_check_tiers properties with env var overrides (POLYLOGUE_NOTIFICATION_BACKEND, POLYLOGUE_HEALTH_CHECK_INTERVAL_S, POLYLOGUE_HEALTH_CHECK_TIERS)
  • TOML sections [notifications] and [health] are parsed and rendered

Daemon wiring (cli.py)

_periodic_health_check() now loads PolylogueConfig to determine health check interval and tier set. Notifications go through the configured backend.

Maintenance docs (docs/daemon.md)

Added clear split between daemon-owned tasks (WAL checkpoint, heartbeat, FTS convergence, health checks) and operator-owned tasks (database backup, blob store backup, vacuum, Litestream replication). Includes Litestream and restic integration guidance.

What was done

  • _check_source_availability_fast() — wired into fast checks
  • _check_insight_freshness_medium() — wired into medium checks
  • _check_repeated_stage_failures_medium() — wired into medium checks
  • _check_blob_integrity_expensive() — wired into expensive checks
  • _check_embedding_coverage_expensive() — wired into expensive checks
  • Config-driven notification backend selection with _resolve_backend()
  • PolylogueConfig properties for notification/health config
  • _periodic_health_check() uses config for tiers and interval
  • Maintenance docs with daemon vs. operator split

What's the gap

  • Notification backends beyond "log" (email, Slack, webhook) are not implemented — the _resolve_backend() factory is structured to accept them
  • Litestream/restic are documentation-only (guidance in docs/daemon.md, no automation)
  • No new notification backends added (non-goal per issue)
  • No tests for the new health checks yet (these are daemon-side checks that query DB/filesystem state; testing would require a seeded test DB)
  • Pre-push hook fails on pre-existing mypy errors in files not touched by this PR (56 errors in 13 files) — these are from commit 0f19458 and prior

Verification

ruff check polylogue/daemon/health.py polylogue/daemon/notifications.py polylogue/daemon/cli.py polylogue/config.py
# All checks passed!

mypy --strict polylogue/daemon/health.py polylogue/daemon/notifications.py polylogue/daemon/cli.py polylogue/config.py
# Success: no issues found in 4 source files

Ref #830

Co-Authored-By: Claude Opus 4.7 [email protected]

…maintenance docs

Add four new health checks across all three tiers:
- FAST: source availability (watch root existence and readability)
- MEDIUM: insight freshness (session profile gap detection), repeated
  stage failures (recent ingest attempt failure rate)
- EXPENSIVE: blob integrity (bounded BlobStore content verification),
  embedding coverage (coverage + failure count when enabled)

Make notification backend selection config-driven via
PolylogueConfig.notification_backend ("log" only for now, with
_resolve_backend() ready for future backends). Add health check
interval and tier config keys with env var overrides.

Document daemon-owned vs operator-owned maintenance task split in
docs/daemon.md, including Litestream/restic integration guidance.

Ref #830

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 7, 2026 15:47
@coderabbitai

coderabbitai Bot commented May 7, 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 8 minutes and 5 seconds before requesting another review.

To continue reviewing without waiting, purchase usage credits in the billing tab.

⌛ 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: 147d7a4a-f23a-48d4-8189-a7f75b304240

📥 Commits

Reviewing files that changed from the base of the PR and between 0f19458 and ddd8d5d.

📒 Files selected for processing (6)
  • docs/daemon.md
  • polylogue/config.py
  • polylogue/daemon/cli.py
  • polylogue/daemon/health.py
  • polylogue/daemon/notifications.py
  • tests/unit/storage/test_backend.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/health-ops-830

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

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

@Sinity
Sinity merged commit 537a01f into master May 7, 2026
6 checks passed
@Sinity
Sinity deleted the feature/feat/health-ops-830 branch May 7, 2026 15:49

@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: ddd8d5d79c

ℹ️ 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 on lines +515 to +519
"SELECT COUNT(*) FROM ("
"SELECT 1 FROM live_ingest_attempt "
"WHERE status = 'failed' "
"ORDER BY started_at DESC LIMIT 20"
")"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Count failures within the same recent-attempt window

failed_recent is computed from the latest 20 failed rows overall, not from the latest 20 attempts overall, so old failures can trigger warnings/errors even when the most recent attempts are healthy. This makes the repeated_stage_failures health check report incorrect failure rates (and can even produce impossible ratios) because it compares two different populations.

Useful? React with 👍 / 👎.

Comment thread polylogue/config.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 completes remaining #830 scope by expanding the daemon’s tiered health checks, making notification delivery backend configurable via runtime config, wiring periodic health-check scheduling to config, and documenting daemon vs. operator maintenance responsibilities.

Changes:

  • Add new FAST/MEDIUM/EXPENSIVE health checks (source availability, insight freshness, repeated stage failures, blob integrity, embedding coverage).
  • Add config-driven notification backend selection and new health/notification config keys (TOML + env overrides).
  • Update daemon periodic health loop to use configured tiers/interval and document operational maintenance guidance.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
tests/unit/storage/test_backend.py Removes stray merge-artifact lines in a storage test (but leaves a problematic duplicate block).
polylogue/daemon/notifications.py Adds backend factory resolution and config-based default backend selection.
polylogue/daemon/health.py Implements additional tiered health checks and wires them into tier runners.
polylogue/daemon/cli.py Makes periodic health-check tiers/interval and notification routing config-driven.
polylogue/config.py Adds new config keys, TOML parsing, env overrides, and TOML rendering for notifications/health.
docs/daemon.md Documents health tiers, notification backend config, and daemon-owned vs operator-owned maintenance tasks.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 1642 to 1646
# FTS should have both messages (the original m1 via repair,
# and m2 via active trigger after restore)
||||||| parent of e895ccf5 (refactor(storage): remove 4 unused session profile FTS tables and 12 triggers (#817))
"""FTS triggers must be active even after an exception during ingest (#817)."""
import sqlite3

from polylogue.storage.sqlite.schema_ddl_actions import ACTION_EVENT_DDL
Comment on lines +245 to +253
elif missing and not unreadable:
severity = HealthSeverity.WARNING
message = f"{available}/{len(sources)} source(s) available, missing: {', '.join(missing)}"
elif unreadable:
severity = HealthSeverity.ERROR
message = f"{available}/{len(sources)} source(s) available, unreadable: {', '.join(unreadable)}"
else:
severity = HealthSeverity.WARNING
message = f"{available}/{len(sources)} source(s) available"
consecutive_failures=_record_failure("repeated_stage_failures", False),
)
try:
conn = sqlite3.connect(str(dbf))
Comment on lines +516 to +519
"SELECT 1 FROM live_ingest_attempt "
"WHERE status = 'failed' "
"ORDER BY started_at DESC LIMIT 20"
")"
Comment thread polylogue/daemon/cli.py
if not tiers:
tiers = {HealthTier.FAST, HealthTier.MEDIUM}

await asyncio.sleep(interval)
Sinity added a commit that referenced this pull request May 7, 2026
First production-grade hardening slice for #830 on top of the
existing daemon/status substrate. Three new modules and
modifications to status and CLI; PR #920 / #903 land the
remaining checks and config wiring on top of this.

- `polylogue/daemon/health.py`: `HealthTier` enum (FAST /
  MEDIUM / EXPENSIVE), `HealthAlert` typed model with severity
  and consecutive-failure tracking, `DaemonHealth`
  aggregation, and `check_health()` runner. Fast checks cover
  liveness/disk/WAL; medium covers FTS readiness, raw failure
  counts, and stale ingest attempts; expensive runs PRAGMA
  integrity_check.
- `polylogue/daemon/backup.py`: `backup_archive()` using
  `VACUUM INTO` with a file-copy fallback; `--check` dry-run;
  optional blob-store backup via `--include-blobs`.
- `polylogue/daemon/notifications.py`: `NotificationBackend`
  protocol with `LogNotificationBackend` routing alerts
  through the structured logger by severity.
- `polylogue/daemon/status.py`: `DaemonStatus` gains
  `health: DaemonHealth`, populated by `build_daemon_status()`
  and exposed in the JSON payload and text formatter.
- `polylogue/daemon/cli.py`: `polylogued health` subcommand
  with tier selection (`--tier`, `--expensive`), JSON output,
  and deterministic exit codes (1 on error/critical).
- `polylogue/cli/commands/backup.py` + registration:
  `polylogue backup` with `--output-dir`, `--check`,
  `--include-blobs`.

Closes #830 on the substrate axis; remaining health-check
additions land in PR #920.

Refs #830
Sinity added a commit that referenced this pull request May 7, 2026
Completes #830 on top of the health/backup substrate from PRs
#898 / #903: four new health checks across the FAST/MEDIUM/
EXPENSIVE tiers, config-driven notification backend selection,
and operator vs. daemon maintenance documentation.

- `polylogue/daemon/health.py`:
  - FAST: `_check_source_availability_fast()` verifies each
    watch root from `default_sources()` exists and is readable.
  - MEDIUM: `_check_insight_freshness_medium()` flags >10% gap
    between session-profile coverage and total conversations.
  - MEDIUM: `_check_repeated_stage_failures_medium()` reads
    `live_ingest_attempt` for recent failure rates and samples
    the latest error.
  - EXPENSIVE: `_check_blob_integrity_expensive()` runs a
    bounded `BlobStore.verify_all(max_failures=5)` content check.
  - EXPENSIVE: `_check_embedding_coverage_expensive()` reports
    coverage and failure count when embeddings are enabled.
- `polylogue/daemon/notifications.py` + `config.py`: backend
  factory `_resolve_backend(backend_name)` (currently log-only),
  resolved from `PolylogueConfig` so tier set, interval, and
  backend can be set via TOML or the matching env vars.
- `polylogue/daemon/cli.py`: `_periodic_health_check()` reads
  config to pick the tier set and backend.
- `docs/daemon.md`: separates daemon-owned and operator-owned
  maintenance tasks.

Refs #830
Sinity added a commit that referenced this pull request May 7, 2026
First production-grade hardening slice for #830 on top of the
existing daemon/status substrate. Three new modules and
modifications to status and CLI; PR #920 / #903 land the
remaining checks and config wiring on top of this.

- `polylogue/daemon/health.py`: `HealthTier` enum (FAST /
  MEDIUM / EXPENSIVE), `HealthAlert` typed model with severity
  and consecutive-failure tracking, `DaemonHealth`
  aggregation, and `check_health()` runner. Fast checks cover
  liveness/disk/WAL; medium covers FTS readiness, raw failure
  counts, and stale ingest attempts; expensive runs PRAGMA
  integrity_check.
- `polylogue/daemon/backup.py`: `backup_archive()` using
  `VACUUM INTO` with a file-copy fallback; `--check` dry-run;
  optional blob-store backup via `--include-blobs`.
- `polylogue/daemon/notifications.py`: `NotificationBackend`
  protocol with `LogNotificationBackend` routing alerts
  through the structured logger by severity.
- `polylogue/daemon/status.py`: `DaemonStatus` gains
  `health: DaemonHealth`, populated by `build_daemon_status()`
  and exposed in the JSON payload and text formatter.
- `polylogue/daemon/cli.py`: `polylogued health` subcommand
  with tier selection (`--tier`, `--expensive`), JSON output,
  and deterministic exit codes (1 on error/critical).
- `polylogue/cli/commands/backup.py` + registration:
  `polylogue backup` with `--output-dir`, `--check`,
  `--include-blobs`.

Closes #830 on the substrate axis; remaining health-check
additions land in PR #920.

Refs #830
Sinity added a commit that referenced this pull request May 7, 2026
Completes #830 on top of the health/backup substrate from PRs
#898 / #903: four new health checks across the FAST/MEDIUM/
EXPENSIVE tiers, config-driven notification backend selection,
and operator vs. daemon maintenance documentation.

- `polylogue/daemon/health.py`:
  - FAST: `_check_source_availability_fast()` verifies each
    watch root from `default_sources()` exists and is readable.
  - MEDIUM: `_check_insight_freshness_medium()` flags >10% gap
    between session-profile coverage and total conversations.
  - MEDIUM: `_check_repeated_stage_failures_medium()` reads
    `live_ingest_attempt` for recent failure rates and samples
    the latest error.
  - EXPENSIVE: `_check_blob_integrity_expensive()` runs a
    bounded `BlobStore.verify_all(max_failures=5)` content check.
  - EXPENSIVE: `_check_embedding_coverage_expensive()` reports
    coverage and failure count when embeddings are enabled.
- `polylogue/daemon/notifications.py` + `config.py`: backend
  factory `_resolve_backend(backend_name)` (currently log-only),
  resolved from `PolylogueConfig` so tier set, interval, and
  backend can be set via TOML or the matching env vars.
- `polylogue/daemon/cli.py`: `_periodic_health_check()` reads
  config to pick the tier set and backend.
- `docs/daemon.md`: separates daemon-owned and operator-owned
  maintenance tasks.

Refs #830
@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.F001 / P1: fixed-already at the checked revision: The environment parser now dispatches by the declared key type: integer settings use int(value) at polylogue/config.py:1907 rather than boolean-token coercion. Numeric health intervals therefore remain integers for the typed accessor.

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