Skip to content

fix(daemon): record lifecycle heartbeats and termination forensics - #2802

Merged
Sinity merged 10 commits into
masterfrom
feature/fanout/daemon-forensics
Jul 13, 2026
Merged

Sinity merged 10 commits into
masterfrom
feature/fanout/daemon-forensics

Conversation

@Sinity

@Sinity Sinity commented Jul 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds durable daemon-lifecycle forensics and a heartbeat-based liveness claim.

Ref polylogue-peo.

Problem

A daemon termination could leave only a stopped log and a stale pidfile. The
operator could not distinguish a clean stop, SIGTERM, or a vanished process,
and the status surface could still claim that the daemon was running.

Solution

  • Adds the disposable ops.db daemon_lifecycle ledger for process start,
    heartbeat, signal, and stop state.
  • Installs SIGTERM/SIGINT handlers that log the signal, dump all active thread
    stacks through faulthandler, record the signal, and then exit normally
    through daemon cleanup.
  • Routes ordinary lifecycle start, heartbeat, and stop writes through the
    daemon write coordinator. The synchronous signal-handler write is a
    best-effort pre-exit fallback with a real 500ms SQLite busy timeout.
  • Schedules lifecycle heartbeats independently of index statistics, so a
    missing or blocked derived tier does not make a living daemon appear gone.
  • Releases the pidfile if lifecycle startup cannot write the OPS tier, and
    derives status liveness from one lifecycle snapshot to avoid shutdown races.
  • Makes CLI status derive running from a fresh durable heartbeat rather than
    the pidfile; exposes lifecycle state and heartbeat age in the payload.
  • Adds process-local heartbeat_age_s to /healthz/live without adding DB I/O
    to that probe.
  • Regenerates topology and declares the new ops writers in the layering
    inventory.

The upstream Nix and Home Manager daemon modules already specify
Restart=on-failure and RestartSec=5s; no systemd change was needed.

Acceptance criteria

Criterion Status Evidence
1. Signal/start/stop forensic row and stack dump Satisfied daemon_lifecycle, signal handlers, atexit sentinel, focused real-daemon SIGTERM test
2. Periodic heartbeat and honest status/health Satisfied always-on lifecycle writer, stale-heartbeat projection, single-snapshot CLI status, and /healthz/live tests
3. Restart policy with backoff Satisfied existing nix/module.nix and nix/hm-module.nix service directives
4. Web unreachable banner Satisfied by merged web lane polylogue-bby.1 closed with merged PR #2673 / commit 5479beab
5. Read-only-serving postmortem Partial; bead remains open Controlled real-daemon fixture establishes SIGTERM exits 143 (128 + 15), records the signal/stop row, and emits a stack dump. The observed exit 144 is not ordinary SIGTERM by POSIX signal numbering and remains an external harness/systemd incident for evidence collection; the original serving/convergence death has not been reproduced.

Verification

  • env TMPDIR=/realm/tmp/polylogue-daemon-forensics-tests POLYLOGUE_PYTEST_BASETEMP_ROOT=/realm/tmp/polylogue-daemon-forensics-tests devtools test tests/unit/daemon/test_daemon_status.py::test_build_daemon_status_uses_one_lifecycle_snapshot tests/unit/daemon/test_daemon_lifecycle.py::test_signal_write_does_not_wait_for_the_normal_writer_timeout tests/unit/daemon/test_daemon_cli.py::test_lifecycle_start_failure_releases_pidfile tests/integration/test_daemon_resilience.py::test_sigterm_read_only_daemon_records_forensics
    • 4 passed.
    • Anti-vacuity: the integration test starts the actual daemon CLI against a
      temporary archive, sends SIGTERM, and reads the production ops.db row;
      the lock test holds a real SQLite write lock and proves the handler does
      not inherit the ordinary 30-second busy wait.
  • Pre-push devtools verify --quick
    • format, lint, mypy, render, topology, layering, schema roundtrip, clock
      hygiene, and degrade-loudly checks all passed.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 56 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9a2cefcf-1bf6-440f-b971-87e500058508

📥 Commits

Reviewing files that changed from the base of the PR and between c1f7704 and 086f2c2.

📒 Files selected for processing (17)
  • docs/plans/layering.yaml
  • docs/plans/test-clock-allowlist.yaml
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/daemon/cli.py
  • polylogue/daemon/healthz.py
  • polylogue/daemon/lifecycle.py
  • polylogue/daemon/status.py
  • polylogue/storage/sqlite/archive_tiers/ops.py
  • polylogue/storage/sqlite/archive_tiers/ops_write.py
  • polylogue/storage/sqlite/connection_profile.py
  • tests/integration/test_daemon_resilience.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/daemon/test_daemon_lifecycle.py
  • tests/unit/daemon/test_daemon_status.py
  • tests/unit/daemon/test_health_contract.py
  • tests/unit/storage/test_archive_tiers_ops_write.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fanout/daemon-forensics

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.

@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: 3447f67a5d

ℹ️ 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
@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial self-review — iteration 1

Findings and corrections:

  • Corrected the false 144 = SIGTERM attribution: the real daemon fixture now
    proves normal SIGTERM exits 143 (128 + 15); 144 remains an external
    harness/systemd incident rather than a source-level conclusion.
  • Moved lifecycle heartbeat scheduling ahead of the derived-tier maintenance
    gate, so absent or blocked index statistics cannot make a living daemon look
    stale.
  • Replaced the handler-only proof with a read-only actual-daemon subprocess
    test that sends SIGTERM and reads its production ops.db lifecycle row.
  • Classified SIGINT as signal, rather than allowing shutdown cleanup to label
    it clean.
  • Routed ordinary lifecycle start, heartbeat, and stop operations through the
    daemon write coordinator. The direct handler write is intentionally retained
    as the pre-exit best-effort fallback.

Verification:

  • env TMPDIR=/realm/tmp/polylogue-daemon-forensics-tests POLYLOGUE_PYTEST_BASETEMP_ROOT=/realm/tmp/polylogue-daemon-forensics-tests devtools test tests/unit/daemon/test_daemon_cli.py::test_lifecycle_heartbeat_runs_without_index_stats tests/unit/daemon/test_daemon_lifecycle.py::test_sigint_is_recorded_as_signal_not_clean_stop tests/integration/test_daemon_resilience.py::test_sigterm_read_only_daemon_records_forensics → 3 passed.
  • Push hook devtools verify --quick passed: format, lint, mypy, render,
    topology, layering, schema roundtrip, and degrade-loudly.

What survived scrutiny: the liveness probe remains process-local and DB-free;
CLI status remains durable-heartbeat based; the existing systemd backoff remains
unchanged; no live archive root was touched.

@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial self-review — iteration 2

Findings and fixes:

  • A lifecycle-start failure after pidfile acquisition could leave the daemon
    mutually excluded. Startup now records an error stop when possible, shuts
    down the coordinator, and releases the pidfile before re-raising.
  • The signal fallback initially appeared bounded but the daemon connection
    profile restored a 30-second busy_timeout. It now overrides both connect
    and pragma busy timeouts to 500ms; a real held-OPS-lock test proves the
    handler returns in under two seconds rather than inheriting the normal wait.
  • Status captured lifecycle twice and could render running beside a stopped
    record. It now derives liveness from the same captured lifecycle snapshot;
    the regression test supplies fresh then stopped snapshots and proves one
    read is used.
  • The PR’s web AC was stale: polylogue-bby.1 is already closed by merged PR
    fix(web): render truthful loading/stale/error states, not false emptiness #2673 (5479beab), so criterion 4 is now recorded as satisfied by that lane.

Verification:

  • env TMPDIR=/realm/tmp/polylogue-daemon-forensics-tests POLYLOGUE_PYTEST_BASETEMP_ROOT=/realm/tmp/polylogue-daemon-forensics-tests devtools test tests/unit/daemon/test_daemon_status.py::test_build_daemon_status_uses_one_lifecycle_snapshot tests/unit/daemon/test_daemon_lifecycle.py::test_signal_write_does_not_wait_for_the_normal_writer_timeout tests/unit/daemon/test_daemon_cli.py::test_lifecycle_start_failure_releases_pidfile tests/integration/test_daemon_resilience.py::test_sigterm_read_only_daemon_records_forensics → 4 passed.
  • devtools verify test-clock-hygiene → violations: 0.
  • Push hook devtools verify --quick passed after the final commit.

What survived scrutiny: criterion 5 is intentionally not treated as closed.
The bead remains open because reproducing the original read-only
serving/convergence death and identifying exit 144 requires external
harness/systemd evidence; this PR captures the normal SIGTERM baseline and
improves the evidence that future incidents leave behind.

@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial self-review — iteration 3

Findings and fixes:

  • A SIGTERM handler’s 500ms signal-row fallback was not enough: ordinary
    shutdown_started event emission and final stop could still wait behind a
    locked OPS database. Signal shutdown now omits that nonessential event and
    uses a bounded final stop; a real daemon subprocess holds an exclusive OPS
    lock, receives SIGTERM, and exits within the bounded window.
  • The schema-blocked test had replaced the lifecycle loop with an inert
    coroutine without proving scheduling. Its replacement now records entry and
    the test asserts that the production task creation reaches it.
  • The final cleanup expression initially failed strict mypy; the type-safe
    equivalent has been committed separately rather than amending a verified
    commit.

Verification:

  • env TMPDIR=/realm/tmp/polylogue-daemon-forensics-tests POLYLOGUE_PYTEST_BASETEMP_ROOT=/realm/tmp/polylogue-daemon-forensics-tests devtools test tests/integration/test_daemon_resilience.py::test_sigterm_with_locked_ops_exits_without_normal_sqlite_wait tests/unit/daemon/test_daemon_cli.py::test_run_daemon_services_schema_block_skips_db_background_work → both selected tests passed.
  • mypy polylogue/daemon/cli.py polylogue/daemon/lifecycle.py tests/integration/test_daemon_resilience.py tests/unit/daemon/test_daemon_cli.py → Success: no issues found in 4 source files.
  • Final push hook devtools verify --quick passed.

What survived scrutiny: SIGTERM still writes normal forensics when OPS is
available; under an external OPS lock it exits promptly and leaves the signal
marker/absence of a clean stop as the honest durable result. AC5 remains open
for the original serving/convergence incident evidence.

@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial self-review — iteration 4 (zero findings)

Full origin/master...HEAD review, bd show polylogue-peo --json, PR comments,
and a fresh independent hostile review found no new actionable defects. The
only automated-review output remains the known CodeRabbit rate-limit notice;
no substantive new review comments arrived.

Final acceptance-criteria matrix

AC Status Honest evidence / remaining scope
1. Start/signal/stop forensics and thread stacks Satisfied Actual read-only daemon subprocess receives SIGTERM, emits the thread-stack log, and persists signal/stop data. SIGINT is classified as signal; hard disappearance remains visibly stale.
2. Heartbeat-backed status and health Satisfied OPS-only heartbeat is scheduled even when the schema gate blocks archive work; bare status uses one durable snapshot and /healthz/live exposes DB-free process heartbeat age.
3. Restart policy/backoff Satisfied Existing Nix and Home Manager service units specify Restart=on-failure and RestartSec=5s.
4. Visible web unreachable state Satisfied by polylogue-bby.1 That web bead is closed with merged PR #2673 / 5479beab; this lane did not modify the web shell.
5. Original read-only serving/convergence death and exit 144 Deferred to polylogue-peo (open) This PR proves ordinary SIGTERM is exit 143 and makes future termination evidence durable. It does not reproduce the historical serving/convergence incident or identify its 144; that requires the external harness/systemd evidence path.

Verification that protects these claims:

  • Real CLI subprocess SIGTERM and held-OPS-lock shutdown tests exercise the
    production daemon entry point and SQLite lifecycle ledger, not a replica.
  • Focused devtools test selections passed with pytest temp rooted under
    /realm/tmp.
  • Final push hook devtools verify --quick passed (format, lint, mypy,
    generated surfaces, topology/layering, schema roundtrip, clock hygiene, and
    degrade-loudly).

Sinity added 10 commits July 13, 2026 02:16
Problem: daemon exits could leave only a stale pidfile and a stopped log,
with no durable signal, clean-stop, or heartbeat evidence.

What changed: add the disposable ops-tier daemon_lifecycle ledger; persist
start, periodic heartbeat, signal, and stop transitions; make status use
heartbeat freshness; expose the process-local heartbeat age in /healthz/live;
and dump all thread stacks before SIGTERM/SIGINT exits.

Compatibility: the pidfile remains the single-instance lock. Existing systemd
modules already restart failures with a five-second backoff.
Preserve the full handler values returned by Python's signal API while
casting only at the restoration boundary, so strict typing matches the
runtime contract.
Log an unreadable lifecycle ledger and report its state as unknown so
status does not silently collapse an operational failure into absence.
Schedule the disposable lifecycle heartbeat independently of index statistics
and convergence so schema-blocked API/health surfaces retain an honest
running claim.
Run lifecycle heartbeats through the daemon writer coordinator even when
schema preflight blocks archive maintenance. Classify SIGINT as a signal and
exercise the real read-only daemon process through SIGTERM shutdown.
Problem: lifecycle startup could strand its pidfile on an OPS failure,\nand the synchronous signal path inherited a 30-second SQLite busy timeout.\nStatus also read lifecycle state twice and could publish contradictory data.\n\nWhat changed: clean up failed lifecycle startup, use a bounded existing-OPS\nwrite for signal forensics, and derive status liveness from one snapshot.\n\nRef polylogue-peo.
Use the health model from its defining module so the status snapshot\nregression test remains strict-mypy clean.\n\nRef polylogue-peo.
The lifecycle signal test measures an OS-level SQLite lock timeout; a frozen\nclock cannot advance that external contention.\n\nRef polylogue-peo.
Problem: final shutdown bookkeeping could still wait on a locked OPS tier,\nand the schema-blocked test did not prove lifecycle scheduling.\n\nWhat changed: skip nonessential shutdown events for terminating signals, bound\nthe final lifecycle stop, and cover real locked-OPS process exit plus lifecycle\ntask scheduling.\n\nRef polylogue-peo.
Keep signal-termination cleanup type-safe after the bounded shutdown path.\n\nRef polylogue-peo.
@Sinity
Sinity force-pushed the feature/fanout/daemon-forensics branch from 14337b0 to 086f2c2 Compare July 13, 2026 00:17
@Sinity
Sinity merged commit 5ff5b0e into master Jul 13, 2026
3 of 15 checks passed
@Sinity
Sinity deleted the feature/fanout/daemon-forensics branch July 13, 2026 00:18
Sinity added a commit that referenced this pull request Jul 13, 2026
…807,2780,2790,2791,2795,2802,2806,2809

uwk3, jph5 (rigor-contracts #2783), bby.17 (web-cockpit #2793), dmp
(terminal-note #2801), ra3w (basetemp-fix #2807), r4no/bkff/r2kb
(extension-redesign #2780) fully satisfied — closed. nhjs (#2793), peo
(daemon-forensics #2802), 4g3n (#2780), 67ac/212.11 (demo-corpus #2795),
rsad (mcp-ergonomics #2790, real gaps remain per 5-iteration adversarial
cap), 9e5.8.4/jnj.7 (provider-origin #2806), mrxt/37t.12/p5g/rxdo.4
(annotation-judgment #2791), s7ae.8/20d.2 (live-performance-2 #2809)
partially satisfied — noted with disposition, left open.

Also discovered and documented the actual root cause of this session's
recurring bead-revert incidents: bd reimports the live database from
.beads/issues.jsonl on every CLI invocation, so a write not immediately
exported is lost the moment the next bd command runs. Every mutation in
this commit was individually export-verified against that behavior.

Co-Authored-By: Claude <[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.

  • 63.F044 / P2: fixed-already at the checked revision: The lifecycle heartbeat is an independently started supervisor service at polylogue/daemon/cli.py:2525. Its tick calls lifecycle.heartbeat through the writer without an index-existence or statistics gate at line 841, preserving liveness evidence during schema-blocked operation.

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