Skip to content

fix(monitoring): wire fleet-health loop to lifespan, persist enabled (default OFF) (#1121) - #1123

Merged
vybe merged 3 commits into
devfrom
feature/1121-monitoring-lifespan
Jun 11, 2026
Merged

vybe merged 3 commits into
devfrom
feature/1121-monitoring-lifespan

Conversation

@dolho

@dolho dolho commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Summary

The MON-001 fleet-monitoring loop was never started at backend boot — the only code path that started it was an admin calling POST /api/monitoring/enable. So every trinity-backend restart silently killed monitoring and left it off until a human re-enabled it; the persisted system_settings.monitoring_config was never consulted on startup. The documented "30s monitoring loop is authoritative" invariant was silently false on any restarted instance.

This fixes the resume-on-restart defect, makes MonitoringConfig.enabled a real persisted setting that defaults OFF (single source of truth, was dead code), and closes a negative-interval flood gap.

Changes

  • main.py lifespan() — delayed (+12s) resume that reads the persisted monitoring_config and starts the loop only when enabled, so the choice survives restarts. Best-effort stop added to shutdown for parity with the other lifespan loops.
  • MonitoringConfig (db_models.py) — enabled now defaults to OFF; *_check_interval fields reject non-positive values via a Pydantic validator (422 on request body; persisted bad config falls back to DEFAULT). Loop also clamps asyncio.sleep to ≥1s as a belt-and-suspenders guard.
  • routers/monitoring.py — enable/disable and PUT /config now persist the enabled flag and reconcile the running loop, so enabled is authoritative regardless of entry point. Shared load_persisted_monitoring_config() + _persist_monitoring_enabled() helpers (one reader, no drift).
  • architecture.md — monitoring loop described as lifespan-wired + gated by the persisted default-off setting; coordinated the feat: Agent heartbeat push for fast failure detection (RELIABILITY-004) #307 heartbeat "stays authoritative" wording.
  • test_monitoring.py — test_update_config_validation now asserts 422 for non-positive intervals (it previously asserted the unvalidated 200 — its own comment predicted this fix).

Acceptance criteria

Higher-than-7-day retention gated behind Enterprise (#1049) is out of scope per the issue.

Verification (live stack, end-to-end)

Scenario Result
enable → restart backend → wait Loop resumes; fleet_health_check passes every ~30s (enabled(running)=true)
disable → restart backend → wait No loop (0 fleet passes); persisted enabled=false
PUT /config with *_check_interval ∈ {-10, 0} 422 for all three interval fields
PUT /config with interval=45 200
MonitoringConfig() default enabled=False; intervals validated

Instance left in clean default-off state.

Related to #1121

🤖 Generated with Claude Code

…(default OFF) (#1121)

The MON-001 fleet-monitoring loop was never started at backend boot — the
only path that started it was an admin calling POST /api/monitoring/enable.
Every trinity-backend restart silently killed the loop and left it off until
a human re-enabled it; the persisted monitoring_config was never consulted on
startup. The documented "30s monitoring loop is authoritative" invariant was
silently false on any restarted instance.

- main.py lifespan(): delayed (+12s) resume that reads the persisted
  monitoring_config and starts the loop only when enabled — survives restarts.
  Best-effort stop added to shutdown for parity with the other loops.
- MonitoringConfig.enabled now defaults to OFF and is the single source of
  truth (was dead code defaulting to True). enable/disable and PUT /config
  persist the flag and reconcile the running loop.
- Negative/zero *_check_interval rejected via a Pydantic validator (422 on
  request body; persisted bad config falls back to DEFAULT). Loop also clamps
  its sleep to >=1s as a belt-and-suspenders guard against a flood loop.
- routers/monitoring.py: shared load_persisted_monitoring_config() +
  _persist_monitoring_enabled() helpers (one reader, no drift).
- architecture.md: monitoring loop now described as lifespan-wired and
  gated by the persisted default-off setting; coordinated the #307
  heartbeat "stays authoritative" wording.
- test_monitoring.py: test_update_config_validation now asserts 422 for
  non-positive intervals (it previously asserted the unvalidated 200).

7-day health-check retention (#772) unchanged; longer retention is a
follow-up Enterprise knob (#1049) per the issue.

Verified end-to-end on the live stack: enable -> restart -> loop resumes
(fleet checks every ~30s); disable -> restart -> no loop; bad intervals -> 422.

Related to #1121

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
service.config = config
if config.enabled and not service.is_running:
background_tasks.add_task(start_monitoring_service, config)
elif not config.enabled and service.is_running:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Partial PUT /config now silently disables monitoring. MonitoringConfig has no required fields (every field has a default, and enabled now defaults to False). So a client PUT that omits enabled — e.g. {"docker_check_interval": 45} — deserializes to enabled=False, and this new reconcile then hits the elif not config.enabled and service.is_running branch and stops the running loop (and resets every omitted field to its default).

Before this PR the same lossy full-replace happened but was inert (no reconcile, and enabled defaulted True). Now a routine interval tweak via a partial body tears down monitoring.

Consider making enabled Optional for the update path (only reconcile when explicitly present), or document/enforce that PUT /config requires a full body. The existing test_update_config_partial won't catch this — it re-sends the full GET payload.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 470d17b — the update path now only treats enabled as authoritative when the client explicitly sends it (model_fields_set); an omitted enabled preserves the persisted run-state, so a partial interval PUT no longer stops the loop. Verified live: PUT {"docker_check_interval":50} while running → enabled stays true, loop keeps running.

"""
# #1121: persist enabled=False FIRST so a disabled fleet stays disabled
# across restarts even if the service wasn't running this process.
_persist_monitoring_enabled(False)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Rapid enable→disable can leave the loop running while persisted enabled=False. enable persists True then schedules start_monitoring_service as a background task (runs after the response). If a disable request is processed before that background task flips is_running to True, disable persists False, sees is_running == False, returns already_stopped, and schedules no stop. The queued start task then runs and the loop comes up — now running against a persisted enabled=False.

Narrow (self-heals on next restart since persisted state is False), but it's a real persisted-vs-runtime drift. Starting the loop inline (or guarding stop/start against the persisted flag at task-run time) would close it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 470d17b — enable/disable/PUT now reconcile inline (await start_monitoring_service/stop_monitoring_service) instead of via background tasks, so runtime state matches the persisted flag before the response returns. start()/stop() only create/cancel the loop task and don't block. Verified: after enable, is_running is true immediately (no pending-task window).

@dolho

dolho commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

🔎 Code review (high-effort, recall-biased)

Core fix is solid and verified end-to-end (lifespan resume, default-off, interval validation). 2 findings posted inline, both in the new enable/disable/PUT-config reconcile logic — neither blocks the central restart-survival fix:

  1. medium — Partial PUT /config (body omitting enabled) defaults enabled=False and the new reconcile stops a running loop. A routine interval tweak via a partial body now silently disables monitoring. (inline)
  2. low — Rapid enable→disable race: disable can no-op (loop's background start hasn't flipped is_running yet), leaving the loop running against persisted enabled=False. Self-heals on restart. (inline)

Both stem from deriving the reconcile decision from a model whose enabled can be defaulted, and from backgrounding the start. Passed clean: validator correctness, the shared loader/persister dedup (good reuse), json/model_copy usage, DEFAULT_CONFIG singleton safety, shutdown parity, single-worker assumption (consistent with the sibling lifespan loops).

Reviewed with the code-review skill.

…ne start/stop (#1121)

Two issues from PR review of the enable/disable/PUT reconcile path:

1. Partial `PUT /config` silently disabled monitoring. Every MonitoringConfig
   field has a default, so a body omitting `enabled` deserialized to
   `enabled=False` and the reconcile stopped a running loop on a routine
   interval tweak. Now only treat `enabled` as authoritative when the client
   explicitly sent it (`model_fields_set`); otherwise preserve the persisted
   run-state.

2. enable→disable race left the loop running against persisted `enabled=False`:
   enable scheduled the start as a background task, so a racing disable could
   no-op (is_running still False) before the start ran. start()/stop() only
   create/cancel the loop task and don't block, so enable/disable/PUT now
   reconcile inline (awaited) — runtime state matches the persisted flag before
   the response returns. Dropped the now-unused background_tasks params.

Verified live: enable -> is_running true immediately; partial PUT keeps
enabled+loop; explicit enabled:false PUT stops the loop; left clean (disabled).

Related to #1121

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@dolho

dolho commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

🔎 Re-review (after 470d17b) — both findings resolved, no new bugs

Finding 1 (partial-PUT disabled monitoring) — fixed & verified. update_monitoring_config now preserves the persisted enabled unless the client explicitly sends it (config.model_fields_set). A PUT {"docker_check_interval":50} while running keeps enabled=true and the loop alive (confirmed live).

Finding 2 (enable→disable race) — fixed & verified. enable/disable/PUT reconcile inline (await) instead of via background tasks. Checked the interleavings are now safe: start() has no internal await suspension (atomic up to create_task), and stop() sets _running=False before it awaits the task cancellation — so a concurrent enable/disable can't strand the loop against a stale persisted flag. After enable, is_running is true immediately.

Also clean: removed background_tasks params are truly unused (import still needed by /check-all); no direct (non-HTTP) callers of the changed signatures; compiles.

Non-blocking notes (neither introduced by this PR / neither a regression)

  • Partial PUT /config still resets non-enabled fields (intervals, thresholds, timeouts) to defaults — the endpoint is full-replace. enabled is now specially preserved, so there's a slight asymmetry. Pre-existing PUT semantics; worth a follow-up if partial/PATCH updates are desired, or document that the body must be complete. Not blocking.
  • status labels ("starting"/"stopping") are now slightly stale since the work completes synchronously before the response — cosmetic, and the existing tests assert those exact strings.

✅ Ready to merge from my side.

Re-reviewed with the code-review skill.

@dolho
dolho requested a review from vybe June 10, 2026 09:05
@github-actions

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

Resolved docs/memory/architecture.md: dev's restructure (0b2302a) made
catalog entries terse with details in subsystem blocks; folded the #1121
facts (lifespan-resumed, persisted default-off enabled flag, interval
validation) into the terse Monitoring Service entries and the Heartbeat
Liveness cross-reference instead of restoring the long-form prose.

Co-Authored-By: Claude Fable 5 <[email protected]>

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Validated via /validate-pr: lifespan resume + persisted default-off enabled flag verified (persist-first ordering, partial-PUT guard via model_fields_set, inline start/stop closes the enable/disable race, 422 interval validation + sleep clamp). Resolved the architecture.md conflict against the dev restructure (docs-only). CI green on the merge commit. Approving.

@vybe
vybe merged commit 3d3671b into dev Jun 11, 2026
14 checks passed
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