Skip to content

perf(daemon): keep live convergence status bounded (#845) - #854

Merged
Sinity merged 4 commits into
masterfrom
feature/fix/daemon-status-heartbeat
May 6, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/fix/daemon-status-heartbeat

Conversation

@Sinity

@Sinity Sinity commented May 6, 2026 •

Copy link
Copy Markdown
Owner

Summary

Follow-up to the daemon-first #845 work after deploying #847/#850/#851 on the workstation. The live daemon exposed two deployment-scale problems: status payloads became huge with thousands of retryable live cursor failures, and full-ingest attempts could look stale while the worker was actually busy inside storage replacement. The same live run also exposed an unindexed SQLite foreign-key path that made conversation replacement scan millions of provider events.

Problem

During the Sinnix switch, polylogued status --format json returned quickly after #851 but emitted thousands of file paths. The active attempt was marked stale in full_blob_copy, while py-spy showed the daemon was actually in _process_ingest_batch_sync -> replace_conversation_runtime_state_sync. The live archive has ~4.0M provider_events rows, and provider_events.source_message_id referenced messages(message_id) without an index, so deleting messages during replacement caused repeated child-table scans and ~91GB of read I/O before I stopped the old service.

Solution

  • Bound live cursor file samples in daemon status while preserving exact failed/excluded/retry counts.
  • Heartbeat full-ingest file scanning, blob materialization, and worker-write handoff with current path and payload-read counters.
  • Add schema v9 with indexes on provider_events(source_message_id) and attachment_refs(message_id) so message deletion during replacement has supporting FK indexes; v8 archives upgrade in place.
  • Split live-batch helper code and the new focused tests out of oversized modules, then refresh topology projections.

Verification

  • ruff check polylogue/sources/live/batch.py polylogue/sources/live/batch_support.py polylogue/storage/sqlite/schema_bootstrap.py tests/unit/sources/test_live_batch_support.py tests/unit/storage/test_schema_upgrades.py tests/unit/sources/test_live_watcher.py tests/unit/storage/test_backend.py -> all checks passed.
  • mypy polylogue/sources/live/batch.py polylogue/sources/live/batch_support.py polylogue/storage/sqlite/schema_bootstrap.py tests/unit/sources/test_live_watcher.py tests/unit/sources/test_live_batch_support.py tests/unit/storage/test_backend.py tests/unit/storage/test_schema_upgrades.py -> success, no issues.
  • pytest tests/unit/sources/test_live_watcher.py tests/unit/sources/test_live_batch_support.py tests/unit/daemon/test_daemon_status.py tests/unit/storage/test_backend.py tests/unit/storage/test_schema_upgrades.py tests/unit/devtools/test_verify_file_budgets.py -q -> 110 passed.
  • devtools verify-file-budgets -> clean.
  • devtools render-all --check -> OK.
  • devtools verify -> all checks passed.
  • pre-push quick verification -> all checks passed.

Ref #845

Summary by CodeRabbit

Release Notes

  • Changed
    • Daemon status now caps live cursor file sample display at 50 entries while preserving exact counts of all failing files.
    • Improved monitoring with heartbeat events emitted during long storage-write phases.
    • Schema v9 adds database indexes for message lookups, improving performance during conversation replacement operations.

Sinity added 4 commits May 6, 2026 23:26
Keep daemon status payloads usable when thousands of live cursor rows are failed or excluded by reporting exact counts with a bounded path sample.

Heartbeat full-ingest file scanning, blob materialization, and worker-write handoff with the current path and payload-read counts so active convergence does not look stale during long storage phases.

Ref #845
Add schema v9 with provider_events.source_message_id and attachment_refs.message_id indexes so deleting messages during conversation replacement does not scan large child tables.

The daemon catch-up exposed this on the production archive as repeated provider_events scans during live convergence. Existing v8 archives upgrade in place.

Ref #845
Move live-batch helper types and parsing utilities out of the daemon batch executor, split the new focused tests out of oversized unit files, and collapse repeated schema upgrade-tail planning.

This keeps the #845 follow-up under the repository file-size budgets without changing the daemon behavior or schema semantics.

Ref #845
Regenerate the topology projection after splitting live batch helper code into its own module.

Ref #845
Copilot AI review requested due to automatic review settings May 6, 2026 21:46
@coderabbitai

coderabbitai Bot commented May 6, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 03aea798-b184-4c53-9e4c-d6a34d635b3d

📥 Commits

Reviewing files that changed from the base of the PR and between 419c359 and 1b39247.

📒 Files selected for processing (16)
  • CHANGELOG.md
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/daemon/status.py
  • polylogue/sources/live/batch.py
  • polylogue/sources/live/batch_support.py
  • polylogue/storage/sqlite/schema.py
  • polylogue/storage/sqlite/schema_bootstrap.py
  • polylogue/storage/sqlite/schema_ddl.py
  • polylogue/storage/sqlite/schema_ddl_archive.py
  • polylogue/storage/sqlite/schema_ddl_provider_events.py
  • tests/unit/daemon/test_daemon_status.py
  • tests/unit/sources/test_live_batch_support.py
  • tests/unit/sources/test_live_watcher.py
  • tests/unit/storage/test_backend.py
  • tests/unit/storage/test_schema_upgrades.py

📝 Walkthrough

Walkthrough

This PR caps live cursor file samples in daemon status reporting while preserving exact counts, adds heartbeat emissions during storage operations, introduces schema v9 with message foreign-key indexes to optimize conversation queries, refactors live batch ingestion internals into a new batch_support module, and updates documentation accordingly.

Changes

Daemon Status Sampling

Layer / File(s) Summary
Data Shape
polylogue/daemon/status.py
LiveCursorSummary gains sampled_file_count and omitted_file_count fields; constant _LIVE_CURSOR_FAILURE_SAMPLE_LIMIT = 50 added to control sample size.
Core Sampling Logic
polylogue/daemon/status.py
Retry-due counts now use a two-pass approach via dedicated retry_rows query; failing_files list is capped at 50 entries with omission count tracked separately.
Output Formatting
polylogue/daemon/status.py
format_daemon_status_lines computes omitted count and appends "Failing files: X shown, Y omitted" when samples exceed limit.
Tests
tests/unit/daemon/test_daemon_status.py
New test test_daemon_status_caps_failed_file_samples verifies 55 failing files are sampled to 50 with 5 omitted and properly formatted in status output.

Schema v8 → v9 Upgrade with Message Foreign-Key Indexes

Layer / File(s) Summary
Schema Version
polylogue/storage/sqlite/schema_ddl.py
SCHEMA_VERSION incremented from 8 to 9.
Index Definitions
polylogue/storage/sqlite/schema_ddl_archive.py, polylogue/storage/sqlite/schema_ddl_provider_events.py
Partial indexes added: idx_attachment_refs_message on attachment_refs(message_id) and idx_provider_events_source_message on provider_events(source_message_id), both filtered by NOT NULL.
Upgrade Planning
polylogue/storage/sqlite/schema_bootstrap.py
New build_v8_to_v9_upgrade_plan function generates upgrade statements; _upgrade_tail_statements helper centralizes multi-version upgrade aggregation; SchemaBootstrapDecision.action now includes "upgrade_v8_to_v9".
Schema Activation
polylogue/storage/sqlite/schema.py
_ensure_schema and ensure_schema_async now include "upgrade_v8_to_v9" in upgrade action sets.
Tests
tests/unit/storage/test_schema_upgrades.py, tests/unit/storage/test_backend.py
New tests verify v8 schemas upgrade to v9 with correct indexes present; catalog snapshot scope expanded to include new index descriptors.

Live Batch Ingestion Refactoring

Layer / File(s) Summary
Batch Support Module
polylogue/sources/live/batch_support.py
New module introduces 20+ internal helpers: protocols for heartbeat/progress emission, dataclasses for append plans/results, utilities for fingerprinting, newline detection, path grouping, worker-count selection, throttled heartbeat, JSONL sampling, provider detection, and conversation artifact classification.
Batch Module Restructuring
polylogue/sources/live/batch.py
_AppendPlan and _AppendResult moved to and imported from batch_support; re-exports expanded via __all__ to include heartbeat and parsing utilities; _full_ingest_heartbeat enhanced to support flexible current_path and payload_read_bytes overrides.
Heartbeat Emissions
polylogue/sources/live/batch.py
New heartbeat events emitted at full_file_scan, full_blob_copy, and full_worker_wait phases; progress data enriched with current_source, current_path, and source_payload_read_bytes.
Batch Ingestion Integration
polylogue/sources/live/batch.py
_process_ingest_batch_sync call now conditionally passes heartbeat callback when provided, enabling live progress feedback during ingestion.
Tests
tests/unit/sources/test_live_batch_support.py, tests/unit/sources/test_live_watcher.py
New test for LiveBatchProcessor ingestion with heartbeat handling; existing tests updated to reference _path_size from batch_support instead of batch.

Supporting Documentation

Layer / File(s) Summary
Changelog
CHANGELOG.md
Two bullets added under Unreleased > Changed documenting daemon status sampling and schema v9 message-FK indexes.
Topology Files
docs/plans/topology-target.yaml, docs/topology-status.md
Topology map updated to reflect new hunks and relocated references; summary counts incremented (Stable 575→576, Total 691→692).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related issues

  • Sinity/polylogue#844: Adds bounded, sampled failure reporting in daemon status with capped live-cursor samples and richer status fields.

Possibly related PRs

  • Sinity/polylogue#541: Modifies live filesystem-watcher surface (polylogue/sources/live/*) with cursor store and watcher integration.
  • Sinity/polylogue#742: Modifies SQLite schema bootstrap/upgrade machinery; both PRs add explicit in-place upgrade paths with new indexes.
  • Sinity/polylogue#831: Adds daemon /api/status CLI endpoint that consumes the revised daemon status reporting from this PR.

Suggested labels

type:refactor, area:storage, type:feature

Poem

🐰 The daemon keeps its samples small,
Schema v9 indexes all,
Batch support splits and grows,
Heartbeats tick where ingest flows,
A refactor hops along! 🥕

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/daemon-status-heartbeat

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 a6c48e0 into master May 6, 2026
3 of 4 checks passed
@Sinity
Sinity deleted the feature/fix/daemon-status-heartbeat branch May 6, 2026 21:50

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 addresses daemon convergence scalability issues observed on large live archives by (1) bounding daemon status payloads for live cursor failures, (2) adding more granular heartbeats during full-ingest work so “busy vs. stuck” is clearer, and (3) introducing schema v9 FK-supporting indexes to avoid pathological SQLite scans during conversation replacement.

Changes:

  • Cap live-cursor failing/excluded file samples in polylogued status while preserving exact counts (failed/excluded/retry/backoff).
  • Add full-ingest heartbeats (current path + payload-read counters) and extract shared live-batch helper code into batch_support.py with targeted unit tests.
  • Bump SQLite schema to v9 and add indexes on provider_events(source_message_id) and attachment_refs(message_id), including an in-place v8→v9 upgrade path and upgrade tests.

Reviewed changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated no comments.

Show a summary per file
File Description
polylogue/daemon/status.py Bounds live cursor failure samples in daemon status; adds omitted/sample counts and updates plain output formatting.
polylogue/sources/live/batch.py Uses shared helpers; adds richer heartbeats during full ingest phases (scan/blob copy/worker wait).
polylogue/sources/live/batch_support.py New module factoring out live batch helper logic (fingerprinting, grouping, throttled heartbeat, provider detection).
polylogue/storage/sqlite/schema_ddl.py Bumps SCHEMA_VERSION from 8 to 9.
polylogue/storage/sqlite/schema_ddl_provider_events.py Adds idx_provider_events_source_message to support FK delete/set-null performance.
polylogue/storage/sqlite/schema_ddl_archive.py Adds idx_attachment_refs_message to support FK delete/set-null performance.
polylogue/storage/sqlite/schema.py Allows upgrade action upgrade_v8_to_v9 in sync/async schema ensure paths.
polylogue/storage/sqlite/schema_bootstrap.py Adds v8→v9 upgrade plan + tail upgrade refactor; registers new index extension descriptors.
tests/unit/daemon/test_daemon_status.py Adds test ensuring status caps failing file samples and reports omitted counts.
tests/unit/sources/test_live_watcher.py Updates monkeypatch target after helper extraction to batch_support._path_size.
tests/unit/sources/test_live_batch_support.py New unit test verifying full-ingest heartbeat emits current path + byte counters.
tests/unit/storage/test_backend.py Extends schema snapshot catalog expectations to include the two new indexes.
tests/unit/storage/test_schema_upgrades.py New tests covering v8→v9 index upgrade behavior and upgrade plan contents.
docs/plans/topology-target.yaml Refreshes topology LOC/projections to include new module and updated file sizes.
docs/topology-status.md Updates generated topology status counts.
CHANGELOG.md Notes bounded status samples, ingest heartbeats, and schema v9 FK indexes.

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

Sinity added a commit that referenced this pull request May 6, 2026
## Summary

Replace the daemon startup FTS coverage check's direct `COUNT(*) FROM
messages_fts` calls with the existing docsize-backed FTS status helper.
This keeps daemon startup bounded enough to report liveness before live
convergence work resumes on large archives.

## Problem

Production deployment of #854 showed `polylogued` blocked before
liveness in `_ensure_fts_startup_readiness`. `py-spy` showed the daemon
inside the startup FTS check, and the process had already read multiple
GB while `PRAGMA user_version` still showed the archive had not reached
the later convergence/schema work. The repo already documents that
`COUNT(*)` on FTS5 virtual tables is O(N); daemon startup had
reintroduced that pattern.

## Solution

`polylogue/daemon/cli.py` now uses `fts_index_status_sync()`, which
counts `messages_fts_docsize`, for both the initial gap check and
post-rebuild logging. A focused daemon CLI test proves the startup check
schedules a rebuild from cheap counts and never issues `COUNT(*) FROM
messages_fts`.

## Verification

- `ruff format --check polylogue/daemon/cli.py
tests/unit/daemon/test_daemon_cli.py` -> `2 files already formatted`
- `ruff check polylogue/daemon/cli.py
tests/unit/daemon/test_daemon_cli.py` -> `All checks passed!`
- `mypy --strict polylogue/daemon/cli.py
tests/unit/daemon/test_daemon_cli.py` -> `Success: no issues found in 2
source files`
- `pytest tests/unit/daemon/test_daemon_cli.py -q` -> `12 passed in
11.41s`
- `devtools verify` -> `verify: all checks passed`
- `git push` pre-push quick gate -> `verify: all checks passed`

Ref #845.
Sinity added a commit that referenced this pull request May 7, 2026
## Summary

Follow-up to the daemon-first #845 work after deploying #847/#850/#851
on the workstation. The live daemon exposed two deployment-scale
problems: status payloads became huge with thousands of retryable live
cursor failures, and full-ingest attempts could look stale while the
worker was actually busy inside storage replacement. The same live run
also exposed an unindexed SQLite foreign-key path that made conversation
replacement scan millions of provider events.

## Problem

During the Sinnix switch, `polylogued status --format json` returned
quickly after #851 but emitted thousands of file paths. The active
attempt was marked stale in `full_blob_copy`, while `py-spy` showed the
daemon was actually in `_process_ingest_batch_sync ->
replace_conversation_runtime_state_sync`. The live archive has ~4.0M
`provider_events` rows, and `provider_events.source_message_id`
referenced `messages(message_id)` without an index, so deleting messages
during replacement caused repeated child-table scans and ~91GB of read
I/O before I stopped the old service.

## Solution

- Bound live cursor file samples in daemon status while preserving exact
failed/excluded/retry counts.
- Heartbeat full-ingest file scanning, blob materialization, and
worker-write handoff with current path and payload-read counters.
- Add schema v9 with indexes on `provider_events(source_message_id)` and
`attachment_refs(message_id)` so message deletion during replacement has
supporting FK indexes; v8 archives upgrade in place.
- Split live-batch helper code and the new focused tests out of
oversized modules, then refresh topology projections.

## Verification

- `ruff check polylogue/sources/live/batch.py
polylogue/sources/live/batch_support.py
polylogue/storage/sqlite/schema_bootstrap.py
tests/unit/sources/test_live_batch_support.py
tests/unit/storage/test_schema_upgrades.py
tests/unit/sources/test_live_watcher.py
tests/unit/storage/test_backend.py` -> all checks passed.
- `mypy polylogue/sources/live/batch.py
polylogue/sources/live/batch_support.py
polylogue/storage/sqlite/schema_bootstrap.py
tests/unit/sources/test_live_watcher.py
tests/unit/sources/test_live_batch_support.py
tests/unit/storage/test_backend.py
tests/unit/storage/test_schema_upgrades.py` -> success, no issues.
- `pytest tests/unit/sources/test_live_watcher.py
tests/unit/sources/test_live_batch_support.py
tests/unit/daemon/test_daemon_status.py
tests/unit/storage/test_backend.py
tests/unit/storage/test_schema_upgrades.py
tests/unit/devtools/test_verify_file_budgets.py -q` -> 110 passed.
- `devtools verify-file-budgets` -> clean.
- `devtools render-all --check` -> OK.
- `devtools verify` -> all checks passed.
- pre-push quick verification -> all checks passed.

Ref #845
Sinity added a commit that referenced this pull request May 7, 2026
Production deployment of #854 showed `polylogued` blocked
before liveness inside `_ensure_fts_startup_readiness`. A
py-spy trace showed the daemon inside the startup FTS check
while `PRAGMA user_version` reported the archive had not
yet reached later convergence/schema work; multiple GB had
already been read because the check used
`COUNT(*) FROM messages_fts`, which is O(N) on FTS5 virtual
tables (the repo already documents that pattern).

Follow-up to PR #854 after deployment exposed the regression.

- `polylogue/daemon/cli.py`: replaces the direct
  `COUNT(*) FROM messages_fts` calls with the existing
  `fts_index_status_sync()` helper that counts
  `messages_fts_docsize` for both the initial gap check and
  the post-rebuild logging, keeping daemon startup bounded
  enough to report liveness before live convergence work
  resumes on large archives.
- `tests/unit/daemon/test_daemon_cli.py`: focused test
  proves the startup check schedules a rebuild from cheap
  counts and never issues `COUNT(*) FROM messages_fts`.

Refs #845
Sinity added a commit that referenced this pull request May 7, 2026
`polylogue status` was reading fields from a pre-#854
`DaemonStatus` shape and partially fabricating values when
those fields were missing. After the typed `DaemonStatus`
redesign the command was stale and showed misleading data
such as a constant uptime or a wrong daemon-running flag.

- `polylogue/cli/commands/status.py`: rewritten against the
  current `DaemonStatus` Pydantic model. Adds
  `--format json` for machine consumers and a deterministic
  text format for humans.
- `docs/verification-catalog.md`: regenerated after the
  command-help surface change.

Refs #825
Sinity added a commit that referenced this pull request May 7, 2026
Production deployment of #854 showed `polylogued` blocked
before liveness inside `_ensure_fts_startup_readiness`. A
py-spy trace showed the daemon inside the startup FTS check
while `PRAGMA user_version` reported the archive had not
yet reached later convergence/schema work; multiple GB had
already been read because the check used
`COUNT(*) FROM messages_fts`, which is O(N) on FTS5 virtual
tables (the repo already documents that pattern).

Follow-up to PR #854 after deployment exposed the regression.

- `polylogue/daemon/cli.py`: replaces the direct
  `COUNT(*) FROM messages_fts` calls with the existing
  `fts_index_status_sync()` helper that counts
  `messages_fts_docsize` for both the initial gap check and
  the post-rebuild logging, keeping daemon startup bounded
  enough to report liveness before live convergence work
  resumes on large archives.
- `tests/unit/daemon/test_daemon_cli.py`: focused test
  proves the startup check schedules a rebuild from cheap
  counts and never issues `COUNT(*) FROM messages_fts`.

Refs #845
Sinity added a commit that referenced this pull request May 7, 2026
`polylogue status` was reading fields from a pre-#854
`DaemonStatus` shape and partially fabricating values when
those fields were missing. After the typed `DaemonStatus`
redesign the command was stale and showed misleading data
such as a constant uptime or a wrong daemon-running flag.

- `polylogue/cli/commands/status.py`: rewritten against the
  current `DaemonStatus` Pydantic model. Adds
  `--format json` for machine consumers and a deterministic
  text format for humans.
- `docs/verification-catalog.md`: regenerated after the
  command-help surface change.

Refs #825
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