Skip to content

perf(daemon): observe and retry live catch-up convergence - #1033

Merged
Sinity merged 3 commits into
masterfrom
feature/perf/daemon-catchup-observability
May 15, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/perf/daemon-catchup-observability

Conversation

@Sinity

@Sinity Sinity commented May 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

This PR carries the current Polylogue performance stack through the merge path: CLI/render startup deferral, legacy insight provenance normalization, and the daemon catch-up/convergence work. The daemon now records durable live-ingest stage events, exposes catch-up/read-amplification status, keeps raw ingest success separate from derived convergence debt, retries conversation-scoped debt without resolving back to source files, and bulk-loads cursor state during catch-up and append planning.

Problem

Production polylogued catch-up was observable only through coarse logs while it could still generate heavy physical reads. A derived-stage failure could make the live path look like raw ingest had failed, causing repeated source work instead of clear derived debt. Host friendliness also belonged in systemd packaging, not ad-hoc app-level throttling or daemon scope reduction.

Solution

  • Added live_ingest_stage_event and live_convergence_debt durable tables plus typed daemon status projections for catch-up and convergence debt.
  • Added read-amplification, throughput, stage timing, memory, and cgroup counters to live ingest metrics/status.
  • Preserved full daemon convergence while allowing raw ingest cursors to advance after successful raw writes; derived failures are recorded as retryable convergence debt.
  • Added first-class conversation-id convergence hooks for FTS, embeddings, and session insights so conversation debt retries do not reread or resolve source files.
  • Reduced catch-up planning overhead by scanning/statting once, bulk-loading cursor rows, and bulk-loading append-planning cursor state inside the batch processor.
  • Kept host pressure policy in Nix/systemd packaging with configurable Nice, idle IO scheduling, IOWeight, MemoryHigh, and MemoryMax.
  • Repaired inherited CLI/render lazy-loading fallout: nested lazy groups dispatch correctly, summary dependencies remain patchable without eager imports, render-all cache support tolerates test fakes, and generated scenario catalogs continue to see JSON-contract surfaces.

Verification

  • PATH="$PWD/.cache/no-notify-bin:$PATH" devtools verify passed on 2026-05-15.
    • pytest: 6348 passed, 2 skipped, 2 xfailed, 2 xpassed
    • total duration: 107.94s
  • Pre-push hook ran devtools verify --quick and passed on 2026-05-15.
  • Focused regression runs during development:
    • pytest tests/unit/daemon/test_daemon_convergence.py tests/unit/daemon/test_daemon_cli.py tests/unit/sources/test_live_watcher.py tests/unit/cli/test_source_selection_helpers.py tests/unit/devtools/test_render_all.py tests/unit/devtools/test_quality_registry.py tests/unit/devtools/test_scenario_projections.py tests/unit/devtools/test_artifact_graph.py tests/unit/cli/test_insights.py -q --tb=short
    • pytest tests/unit/cli/test_terminal_snapshots.py --snapshot-update -q --tb=short

Deployment Notes

Deployment is intentionally not folded into the app PR. After merge, update the Sinnix flake input for Polylogue, switch the NixOS generation, restart/deploy polylogued, then validate the real archive using polylogued status --json, stage-event rows, convergence-debt rows, journal logs, and physical read deltas.

Summary by CodeRabbit

  • New Features

    • Added selective test verification mode to run only tests related to changed files.
    • Enhanced daemon status visibility with catch-up progress tracking and convergence debt reporting.
    • Added systemd resource control options for daemon configuration.
  • Improvements

    • Improved CLI startup performance through deferred module loading.
    • Optimized database queries for building pages and rendering help.
    • Enhanced live ingest observability with detailed stage event tracking.
  • Documentation

    • Updated CLI reference with corrected help formatting.
    • Added daemon operational guidance for systemd control (pause, stop, restart).

Sinity added 3 commits May 12, 2026 06:07
Problem: root CLI startup still imported command and surface helpers that pulled archive-adjacent stacks, while docs rendering paid repeated CLI subprocess costs and the pages builder waited on live stats queries. This kept help/import and generated-surface workflows slower than the current performance targets.

What changed: register all root/query commands through lazy Click proxies, split query verb names into a lightweight module, move formatting and machine-envelope dependencies off the startup path, add package-root lazy submodule access, render CLI help and page feeder surfaces in-process, read site stats from conversation_stats directly, and add affected-test verification with a content-aware verify cache.

Verification: devtools render-all --check; python -X importtime -c 'from polylogue.cli.click_app import cli' with no archive/storage/rendering/daemon/surfaces imports; focused CLI/devtools pytest set passed with 89 passed, 4 skipped; devtools verify --affected --skip-slow --force --json passed in 51.91s.
…yloads

Add pydantic `field_validator(mode="before")` on
`SessionInferencePayload.work_events` and `phases` to backfill
`timing_provenance` and `date_provenance` when older archived documents
lack those fields.

The validators run at deserialization time and only set defaults when the
fields are missing (`setdefault`), preserving any explicit values already
on the document. The provenance values are derived from `start_time` /
`end_time` / `canonical_session_date`:

- `timing_provenance`: timestamped_range | start_timestamp_only |
  end_timestamp_only | untimestamped
- `date_provenance`: event_timestamp | date_only | none

This makes deserialization of legacy archive payloads (pre-`timing_provenance`
schema) succeed instead of failing with missing-field errors when those
defaults can't be inferred from the existing class-level defaults
("untimestamped" / "none") because they ignore available timestamps.

Coverage:
  tests/unit/storage/test_session_insight_mapper_fallbacks.py — 6 passed
Problem: daemon catch-up could keep rereading source files and derived convergence failures were hard to distinguish from raw ingest success. Operators also lacked durable progress and read-amplification evidence while polylogued was under IO pressure.

What changed: add durable live-ingest stage events, catch-up status projection, convergence-debt status, conversation-id convergence retry hooks, bulk cursor planning in catch-up and batch append planning, legacy provenance normalization for typed insight payloads, and Nix/systemd service resource controls. Generated verification docs and terminal snapshots were refreshed for the updated CLI lazy-loading surface.

Verification: PATH="/realm/project/polylogue/.cache/no-notify-bin:/home/sinity/.codex/tmp/arg0/codex-arg0Voz8KF:/nix/store/dk9qhjgg469lv6mriys7v4c59igarmvx-bubblewrap-0.11.1/bin:/nix/store/4bwbk4an4bx7cb8xwffghvjjyfyl7m2i-bash-interactive-5.3p9/bin:/nix/store/jjxngswsb214vb58qx485jhmilf0kxxy-coreutils-9.10/bin:/realm/project/polylogue/.direnv/sinnix-scope/bin:/realm/project/polylogue/.venv/bin:/nix/store/66lksljlljdd5ppgvfk8g89y8xgqcxd7-patchelf-0.15.2/bin:/nix/store/qd70v8g0561vm8m33kmnp79z00cgyi5n-gcc-wrapper-15.2.0/bin:/nix/store/sanx9fg8mry8mq92zhlm5qvb83qlxrlx-gcc-15.2.0/bin:/nix/store/pf30k3mg7n6bibc1k6609gyq7glk00k2-glibc-2.42-61-bin/bin:/nix/store/jjxngswsb214vb58qx485jhmilf0kxxy-coreutils-9.10/bin:/nix/store/kfwagnh6i1mysf7vxq679rzh30z9zj3g-binutils-wrapper-2.46/bin:/nix/store/p2vkw5s89ff1fs2d2rxqxiqil9s0jpcm-binutils-2.46/bin:/nix/store/0r6k8xa2kgqyp3r4v2w7yrb80ma2iawm-python3-3.13.12/bin:/nix/store/9xinbvah2sr4k5g05g7w48q2klf2va5f-uv-0.11.8/bin:/nix/store/sl5031w08yhja3hhfkwxpm187c9f9qkb-devtools/bin:/nix/store/c0277k5giric1mn9dklllavbzvxl6hzb-git-2.53.0/bin:/nix/store/97mrhz21xc7dx218i36m6s9jyi7q5469-ruff-0.15.12/bin:/nix/store/nrc6fg23g7q6qm5dfd63kfg74l613cyi-python3.13-mypy-1.19.1/bin:/nix/store/fvs3zhpvndbca8mppb829174ckdrdgcv-py-spy-0.4.0/bin:/nix/store/p60rxkda75nmha060ikxhkzy4dmpz53i-python3.13-pyinstrument-5.1.2/bin:/nix/store/s63r3nfiy3gni9ikx2ka7cwl5hz8imzi-bat-0.26.1/bin:/nix/store/hqg1pdb50bny98165djnr627h9y8fk5i-glow-2.1.2/bin:/nix/store/sqpq9fbwhs2r48z1amlib3cpf1y4qxmi-vhs-0.11.0/bin:/nix/store/jjxngswsb214vb58qx485jhmilf0kxxy-coreutils-9.10/bin:/nix/store/vhsirn9m1ifmnw5g1qczzhvqkx6lw1if-findutils-4.10.0/bin:/nix/store/hx084k7pgz4n0vgkvil9gbcnl8y6p1xf-diffutils-3.12/bin:/nix/store/af4a8i43kc2ss4rnmf0swkk2mprsw6xq-gnused-4.9/bin:/nix/store/wf7lr2hf43546jc5kwqh3dbxnpcnw1mn-gnugrep-3.12/bin:/nix/store/lakv43kv98sl6h0ba6wnyg513mcq61vl-gawk-5.4.0/bin:/nix/store/rnvb7bvp53v2dw7pcwh9xb89x5z4rjib-gnutar-1.35/bin:/nix/store/9lhr1c3l9qzv8pzp3idmii1nwvxxjys3-gzip-1.14/bin:/nix/store/zj6r42syyswkhrr174bzppj3n7xhq936-bzip2-1.0.8-bin/bin:/nix/store/yvrwcs1a45rj8142n0l2w9q9s6akamjr-gnumake-4.4.1/bin:/nix/store/i27rhb3nr65rkrwz36bchkwmav6ggsmn-bash-5.3p9/bin:/nix/store/zj7mxwji29zvj9vl70iip7gw4h6ljfam-patch-2.8/bin:/nix/store/2nm5c858fh52s6mhcffm07s3biaxys44-xz-5.8.3-bin/bin:/nix/store/iscmg3ivhx7z67dz14lrg7p77gnsa4dw-file-5.45/bin:/realm/project/polylogue/.direnv/bin:/home/sinity/.local/bin:/run/wrappers/bin:/home/sinity/.nix-profile/bin:/nix/profile/bin:/home/sinity/.local/state/nix/profile/bin:/etc/profiles/per-user/sinity/bin:/nix/var/nix/profiles/default/bin:/run/current-system/sw/bin:/nix/store/kfwagnh6i1mysf7vxq679rzh30z9zj3g-binutils-wrapper-2.46/bin:/nix/store/m0yqmmh44v2ykpr7gd6hp6yrvzpcqbjd-hyprland-qtutils-0.1.5/bin:/nix/store/jx13ah7k2zp0w21r2qncpdji93ylcncl-pciutils-3.14.0/bin:/nix/store/vqpm0alli7j5fvqxwrq9rg4csnkwk0j8-pkgconf-wrapper-2.5.1/bin:/nix/store/myjlf11fwy8yw3127hxsfyidxz6srg6x-kitty-0.46.2/bin:/nix/store/pjcg9z9zj4hqa7y8jjgsx06rc31q6r8s-imagemagick-7.1.2-19/bin:/nix/store/whrp41kk2qd790h8xg4v4giw5z0cmxa7-ncurses-6.6-dev/bin" devtools verify passed on 2026-05-15 with pytest 6348 passed, 2 skipped, 2 xfailed, 2 xpassed.
@coderabbitai

coderabbitai Bot commented May 15, 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: 82864db2-ac31-4868-910a-607f08459540

📥 Commits

Reviewing files that changed from the base of the PR and between ba2745e and 56d56c8.

📒 Files selected for processing (46)
  • devtools/pages_builder.py
  • devtools/render_all.py
  • devtools/render_cli_reference.py
  • devtools/render_pages.py
  • devtools/verify.py
  • docs/cli-reference.md
  • docs/daemon.md
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • docs/verification-catalog.md
  • nix/module.nix
  • polylogue/__init__.py
  • polylogue/cli/click_app.py
  • polylogue/cli/click_command_registration.py
  • polylogue/cli/query.py
  • polylogue/cli/query_group.py
  • polylogue/cli/query_verbs.py
  • polylogue/cli/shared/formatting.py
  • polylogue/cli/shared/helpers.py
  • polylogue/cli/shared/machine_errors.py
  • polylogue/cli/shared/types.py
  • polylogue/cli/verb_names.py
  • polylogue/daemon/catchup_status.py
  • polylogue/daemon/cli.py
  • polylogue/daemon/convergence.py
  • polylogue/daemon/convergence_debt_status.py
  • polylogue/daemon/convergence_stages.py
  • polylogue/daemon/status.py
  • polylogue/insights/archive_models.py
  • polylogue/showcase/generators.py
  • polylogue/sources/live/batch.py
  • polylogue/sources/live/batch_observability.py
  • polylogue/sources/live/convergence_debt.py
  • polylogue/sources/live/cursor.py
  • polylogue/sources/live/metrics.py
  • polylogue/sources/live/watcher.py
  • tests/conftest.py
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/cli/test_maintenance_registration.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/daemon/test_daemon_convergence.py
  • tests/unit/daemon/test_daemon_status.py
  • tests/unit/sources/test_live_catchup_planning.py
  • tests/unit/sources/test_live_watcher.py
  • tests/unit/storage/test_session_insight_mapper_fallbacks.py

📝 Walkthrough

Walkthrough

This PR introduces durable convergence-debt retry tracking with exponential backoff, conversation-scoped convergence stages, and live ingest observability (stage events and metrics) via new SQLite tables. It also refactors the CLI to use lazy command registration and defers heavyweight imports to reduce startup overhead. Supporting changes include session inference normalization, direct database access in devtools, and affected-test detection for selective verification.

Changes

Convergence Debt Tracking & Live Ingest Observability with CLI Import Optimization

Layer / File(s) Summary
CLI import optimization and lazy submodule loading
polylogue/cli/verb_names.py, polylogue/cli/click_app.py, polylogue/cli/click_command_registration.py, polylogue/cli/query*.py, polylogue/cli/shared/*.py, polylogue/__init__.py, tests/unit/cli/*
New verb_names module centralizes query verb constants. CLI commands now register via _LazyCommand and _LazyGroup that defer resolution until invocation. AppEnv.operations and package root now perform local imports instead of eagerly loading UI and operations stacks at module import time. Tests updated to locate commands from ROOT_COMMANDS rather than direct imports.
Convergence debt data models and SQLite schema
polylogue/sources/live/convergence_debt.py, polylogue/daemon/convergence_debt_status.py, polylogue/sources/live/cursor.py, tests/unit/daemon/test_daemon_*.py
New ConvergenceDebt dataclass and helpers (debt_by_path, convergence_debt_from_state) to derive debt from convergence states. ConvergenceDebtSummary models summarize failed/retry-due counts by stage. CursorStore gains live_convergence_debt table with exponential-backoff retry tracking, and new methods record_convergence_debt, clear_convergence_debt, list_convergence_debt.
Live ingest stage event recording and metrics tracking
polylogue/sources/live/batch_observability.py, polylogue/sources/live/watcher.py, polylogue/sources/live/batch.py, polylogue/sources/live/metrics.py, polylogue/sources/live/cursor.py, tests/unit/sources/test_live_*
New record_attempt_progress and conversation_ids_for_source_path helpers emit stage events to live_ingest_stage_event table. LiveBatchMetrics now computes read amplification, throughput rates, and throughput in MB/s. Live watcher refactors catch-up to use structured CandidateSourceFile and CatchUpPlan types. Batch ingestion persists convergence debt per source path and conversation ID.
Daemon convergence with conversation-scoped stages and debt retry
polylogue/daemon/convergence.py, polylogue/daemon/convergence_stages.py, polylogue/daemon/cli.py, tests/unit/daemon/test_daemon_convergence.py`
ConvergenceStage gains optional check_conversations and execute_conversations callbacks. fts, embed, and insights stages now implement conversation-scoped repair/execution via these callbacks. DaemonConverger.converge_conversations() batches and deduplicates conversation IDs, tracks ConversationState per ID, and marks stages as DONE/FAILED/SKIPPED. New _drain_convergence_debt_once in daemon CLI runs periodic convergence retries with exponential backoff.
Daemon status display with catchup and convergence debt reporting
polylogue/daemon/catchup_status.py, polylogue/daemon/status.py, tests/unit/daemon/test_daemon_status.py`
New CatchupStatus and related models read recent stage events from live_ingest_stage_event, compute throughput/read-amplification metrics, and fall back to latest_attempt when stage events are unavailable. DaemonStatus now includes catchup and convergence fields. Status payload and formatted output include catch-up mode, current phase, queued/needed/skipped/succeeded file counts, read amplification, and per-stage convergence-debt failure/retry-due tallies.
Supporting refactoring: insights normalization, devtools, and defensive code
polylogue/insights/archive_models.py, devtools/pages_builder.py, devtools/render_cli_reference.py, devtools/render_pages.py, devtools/render_all.py, devtools/verify.py, tests/conftest.py`
Session inference payload normalizes work_events and phases via field validators. Devtools refactored to use direct database access or in-process module imports instead of subprocess calls. verify.py computes affected tests from changed files and git diffs. Hypothesis CI profile conditionalized on POLYLOGUE_CI environment. Defensive getattr for optional surface inputs.
Unit tests for convergence, ingest, and daemon status
tests/unit/daemon/test_daemon_.py, tests/unit/sources/test_live_.py, tests/unit/storage/test_session_insight_*.py, tests/unit/cli/test_maintenance_registration.py
New tests verify conversation batching in DaemonConverger.converge_conversations(), debt draining retry behavior, live stage event persistence, catch-up planning with cursor state reuse, and convergence-debt display in daemon status. Maintenance command test helper locates command from ROOT_COMMANDS.
Generated documentation updates
docs/cli-reference.md, docs/topology-status.md, docs/verification-catalog.md, docs/test-quality-workflows.md, docs/daemon.md, docs/plans/topology-target.yaml, nix/module.nix, tests/unit/cli/snapshots/test_terminal_snapshots.ambr
Updated CLI help snapshots reflect --help-only formatting (no -h). Topology target and verification catalog refreshed with new source locations and updated subject/obligation counts. Test-quality workflows document new help/insights exercise coverage. NixOS module adds systemd resource-control options (nice, ioWeight, memoryHigh, memoryMax). Daemon documentation instructs operators to use systemd controls.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related issues

  • Sinity/polylogue#845: Main PR implements convergence-focused refactor including conversation-scoped convergence, durable convergence-debt retry, and live-ingest observability plumbing that directly addresses this issue.

Possibly related PRs

  • Sinity/polylogue#863: Both PRs modify polylogue/daemon/convergence_stages.py around the embed stage; main PR adds conversation-scoped check/execute callbacks while retrieved PR conditionally includes embed based on feature flags.
  • Sinity/polylogue#541: Main PR extends live cursor store with live_ingest_stage_event and live_convergence_debt tables/methods, building on the live filesystem watcher introduced in the retrieved PR.

Suggested labels

type:refactor, area:storage, area:cli, area:pipeline, type:test

Poem

🐰 A rabbit hops through convergence debt,
Tracking retries with exponential set,
Stage events flow to SQLite's care,
While lazy CLI commands wait in the air,
The daemon converges—one conversation at a time.

✨ 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/perf/daemon-catchup-observability

@Sinity
Sinity merged commit a73d69b into master May 15, 2026
3 of 4 checks passed
@Sinity
Sinity deleted the feature/perf/daemon-catchup-observability branch May 15, 2026 00:43

@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: 56d56c8bcf

ℹ️ 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
Comment on lines +210 to +211
if latest is not None and latest.status == "running":
return "converging" if latest.phase in {"convergence", "fts", "insights", "full_worker_wait"} else "catching_up"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Ignore stale running stage events when deriving catch-up mode

Mode selection treats the latest stage event with status == "running" as active work even when there is no running ingest attempt. After a crash/interruption, live_ingest_attempt is marked interrupted, but old stage events remain running, so status can stay stuck in catching_up/converging indefinitely and misreport daemon state.

Useful? React with 👍 / 👎.

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

Avoid full-file fingerprint reads during daemon catch-up when a source path has the same byte size and an existing content fingerprint but its device/inode changed under the cursor.

Problem

The deployed daemon still hammered disk after #1033. `py-spy dump` showed startup stuck in `fingerprint_file()` from `LiveWatcher._plan_catch_up()`. A production cursor classification found 10,916 files / 31.35 GB in the `fingerprint_read` path solely because stored `st_dev/st_ino` no longer matched the filesystem, even though paths, sizes, parser fingerprints, and stored content fingerprints were stable.

Solution

Treat stable path + stable byte size + recorded content fingerprint as the catch-up skip path independent of inode/device churn. Appends still trigger work via `size > byte_offset`, truncations still fall through, and legacy cursors without fingerprints still populate cursor state.

Verification

- `pytest tests/unit/sources/test_live_watcher.py -q --tb=short` → 60 passed
- `pytest tests/integration/test_live_read_amplification.py -q --tb=short` → 5 passed
- `ruff check polylogue/sources/live/watcher.py tests/unit/sources/test_live_watcher.py` → All checks passed
- `devtools verify-file-budgets` → clean
- `devtools render-all` → generated surfaces refreshed
- Pre-push `devtools verify --quick` → exit_code 0
- PR checks: CodeQL, CodeRabbit, GitGuardian pass
@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.F027 / P1: fixed-already at the checked revision: The current stage-scoped retry clears a debt row only when its subject converged at polylogue/daemon/cli.py:1535-1541. A failed stage is re-recorded directly at line 1548 without deleting its prior counter, preserving the existing backoff history.

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.

1 participant