Repository navigation
fix(monitoring): wire fleet-health loop to lifespan, persist enabled (default OFF) (#1121) - #1123
Conversation
…(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: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
🔎 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
Both stem from deriving the reconcile decision from a model whose Reviewed with the |
…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]>
🔎 Re-review (after 470d17b) — both findings resolved, no new bugsFinding 1 (partial-PUT disabled monitoring) — fixed & verified. Finding 2 (enable→disable race) — fixed & verified. enable/disable/PUT reconcile inline ( Also clean: removed Non-blocking notes (neither introduced by this PR / neither a regression)
✅ Ready to merge from my side. Re-reviewed with the |
|
Resolve by running |
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
left a comment
There was a problem hiding this comment.
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.
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 everytrinity-backendrestart silently killed monitoring and left it off until a human re-enabled it; the persistedsystem_settings.monitoring_configwas 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.enableda real persisted setting that defaults OFF (single source of truth, was dead code), and closes a negative-interval flood gap.Changes
main.pylifespan()— delayed (+12s) resume that reads the persistedmonitoring_configand 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) —enablednow defaults to OFF;*_check_intervalfields reject non-positive values via a Pydantic validator (422 on request body; persisted bad config falls back to DEFAULT). Loop also clampsasyncio.sleepto ≥1s as a belt-and-suspenders guard.routers/monitoring.py—enable/disableandPUT /confignow persist theenabledflag and reconcile the running loop, soenabledis authoritative regardless of entry point. Sharedload_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_validationnow asserts 422 for non-positive intervals (it previously asserted the unvalidated 200 — its own comment predicted this fix).Acceptance criteria
/check+trigger_health_checkunchanged).enable/disablepersist the state across restarts.agent_health_checksfor the whole fleet (investigate: perform_fleet_health_check stops refreshing data for most agents (#669 root cause) #675, unchanged).*_check_intervalrejects non-positive values (422).architecture.mdupdated to match reality.Higher-than-7-day retention gated behind Enterprise (#1049) is out of scope per the issue.
Verification (live stack, end-to-end)
enable→ restart backend → waitfleet_health_checkpasses every ~30s (enabled(running)=true)disable→ restart backend → waitenabled=falsePUT /configwith*_check_interval∈ {-10, 0}PUT /configwith interval=45MonitoringConfig()defaultenabled=False; intervals validatedInstance left in clean default-off state.
Related to #1121
🤖 Generated with Claude Code