Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Fail closed when patrol_resolve_finding verifier is inconclusive

rcourtmand02255907c4c
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index ef42e0c536..a753f4aac9 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -108,7 +108,7 @@ runtime cost control, and shared AI transport surfaces.
## Completion Obligations
-1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as DeepSeek `tool_choice` coercion, runtime-failure classification splits (for example separating forced tool selection rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load, the auto-trigger contract on `HandleUpdateAISettings` where the save handler runs `TriggerPatrolPreflightAsync` only when the change actually moved Patrol transport (model swap, provider key for that model changed, or assistant just enabled with a Patrol model) so routine settings saves do not burn provider tokens, the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified", the readiness-integration contract where the `tools` check in the Patrol readiness payload consults the cached preflight and surfaces the classified evidence (success, soft warning, or failure with classified summary plus "last preflight <age>") for the configured provider+model when available (falling back to the static `PatrolToolReadinessForModel` classifier only when the cache is empty or holds a result for a different model), the stateless-Patrol-input contract where `ExecutePatrolStream` must pass only the current run's user prompt into the agentic loop rather than reloading the persisted `patrol-main` session history (so a prior run that ended with orphan `tool_calls` cannot poison every subsequent run with malformed conversation structure), and the deterministic-resolve-gate contract where the `patrol_resolve_finding` tool adapter rejects LLM-driven resolves of event/persistent category findings (`backup`, `reliability`, `security`, `general`) when a deterministic verifier exists for the finding's key and that verifier still detects the failure signal — preventing the LLM from optimistically resolving a finding its current investigation simply didn't re-surface, which was the source of the "Backup failed" flap (detected → auto-resolved → re-detected ten times in a day before this gate), the assessment-recovery contract where the overall-health "Recent Patrol errors" coverage factor in `summarizeRecentPatrolCoverage` suppresses the score penalty once three consecutive trailing successful full Patrol runs exist at the most-recent end of the recent-runs window — so the grade reflects current reality after a Patrol-affecting bug is fixed rather than dragging stale failures forward for the ~9 hours it takes scheduled runs to age them out of the trailing-10 ratio, the orphan-tool-call-repair contract where `convertToProviderMessages` injects synthetic is_error tool result messages for any `tool_call_id` in an assistant message that has no matching downstream tool result, so a chat session that ended mid-tool-call (network drop, ctx timeout, browser crash) cannot poison its next message with the structural-violation error the provider rejects — the synthetic content is marked is_error=true and explains the interruption so the model can retry the call or proceed without the data, and the patrol-session-bound contract where `ExecutePatrolStream` calls `SessionStore.TrimMessages` after persisting each run's messages to cap the patrol-main session at 200 messages (roughly two recent runs' worth) — without the bound the file grew unbounded at every scheduled run, reaching 16 MB and 3,593 messages within a month and making every `AddMessage` rewrite linearly more expensive; the canonical Patrol forensic log is the `PatrolRunRecord` history surfaced at `/api/ai/patrol/runs`, not the chat-session-shaped file
+1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as DeepSeek `tool_choice` coercion, runtime-failure classification splits (for example separating forced tool selection rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load, the auto-trigger contract on `HandleUpdateAISettings` where the save handler runs `TriggerPatrolPreflightAsync` only when the change actually moved Patrol transport (model swap, provider key for that model changed, or assistant just enabled with a Patrol model) so routine settings saves do not burn provider tokens, the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified", the readiness-integration contract where the `tools` check in the Patrol readiness payload consults the cached preflight and surfaces the classified evidence (success, soft warning, or failure with classified summary plus "last preflight <age>") for the configured provider+model when available (falling back to the static `PatrolToolReadinessForModel` classifier only when the cache is empty or holds a result for a different model), the stateless-Patrol-input contract where `ExecutePatrolStream` must pass only the current run's user prompt into the agentic loop rather than reloading the persisted `patrol-main` session history (so a prior run that ended with orphan `tool_calls` cannot poison every subsequent run with malformed conversation structure), and the deterministic-resolve-gate contract where the `patrol_resolve_finding` tool adapter rejects LLM-driven resolves of event/persistent category findings (`backup`, `reliability`, `security`, `general`) when a deterministic verifier exists for the finding's key and that verifier either still detects the failure signal **or returns an inconclusive result** — preventing the LLM from optimistically resolving a finding its current investigation simply didn't re-surface, which was the source of the "Backup failed" flap (detected → auto-resolved → re-detected ten times in a day before this gate). The fail-closed-on-inconclusive policy treats verifier errors (timeouts, executor unavailability, transport faults) as "we don't know" rather than "go ahead": resolution of an event/persistent finding is effectively permanent (next detection registers as a regression and inflates counters), so the safe default is to refuse and require either a successful re-verification or operator action, the assessment-recovery contract where the overall-health "Recent Patrol errors" coverage factor in `summarizeRecentPatrolCoverage` suppresses the score penalty once three consecutive trailing successful full Patrol runs exist at the most-recent end of the recent-runs window — so the grade reflects current reality after a Patrol-affecting bug is fixed rather than dragging stale failures forward for the ~9 hours it takes scheduled runs to age them out of the trailing-10 ratio, the orphan-tool-call-repair contract where `convertToProviderMessages` injects synthetic is_error tool result messages for any `tool_call_id` in an assistant message that has no matching downstream tool result, so a chat session that ended mid-tool-call (network drop, ctx timeout, browser crash) cannot poison its next message with the structural-violation error the provider rejects — the synthetic content is marked is_error=true and explains the interruption so the model can retry the call or proceed without the data, and the patrol-session-bound contract where `ExecutePatrolStream` calls `SessionStore.TrimMessages` after persisting each run's messages to cap the patrol-main session at 200 messages (roughly two recent runs' worth) — without the bound the file grew unbounded at every scheduled run, reaching 16 MB and 3,593 messages within a month and making every `AddMessage` rewrite linearly more expensive; the canonical Patrol forensic log is the `PatrolRunRecord` history surfaced at `/api/ai/patrol/runs`, not the chat-session-shaped file
2. Keep AI runtime and shared API proof routing aligned in `registry.json`
3. Preserve explicit coverage for chat, Patrol, remediation, and cost-control behavior when AI runtime changes
Patrol runtime failures are part of that runtime contract: provider, model,
diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.go
index 876c260642..a5308d3233 100644
--- a/internal/ai/patrol_findings.go
+++ b/internal/ai/patrol_findings.go
@@ -1005,13 +1005,26 @@ func (a *patrolFindingCreatorAdapter) ResolveFinding(findingID, reason string) e
defer verifyCancel()
verified, verifyErr := a.patrol.VerifyFixResolved(verifyCtx, finding.ResourceID, finding.ResourceType, finding.Key, findingID)
if verifyErr != nil {
- log.Warn().
+ // Fail closed. Resolution of an event/persistent finding is
+ // effectively permanent (next detection will register as a
+ // regression, inflating counters and re-running the cycle the
+ // rest of this branch's work spent commits closing). If the
+ // deterministic verifier cannot confidently say the failure
+ // signal is gone, we don't have grounds to honor the LLM's
+ // judgment, even charitably — the LLM's "current investigation
+ // didn't surface a fresh failure" is exactly the signal that
+ // produced the bogus auto_resolved → re-detected cycles in
+ // the first place. Surfacing the error back to the tool lets
+ // the LLM choose to retry or escalate to the operator instead.
+ log.Info().
Err(verifyErr).
Str("finding_id", findingID).
Str("category", string(finding.Category)).
Str("key", finding.Key).
- Msg("AI Patrol: deterministic verifier inconclusive on resolve attempt; allowing resolve")
- } else if !verified {
+ Msg("AI Patrol: rejected LLM resolve — deterministic verifier was inconclusive (fail closed)")
+ return fmt.Errorf("cannot resolve %s: deterministic verification was inconclusive (%v). Confirm the underlying issue is actually fixed by running the verifier separately, or let the operator mark resolved", findingID, verifyErr)
+ }
+ if !verified {
log.Info().
Str("finding_id", findingID).
Str("category", string(finding.Category)).
diff --git a/internal/ai/patrol_findings_additional_test.go b/internal/ai/patrol_findings_additional_test.go
index 1593365f29..23d5818234 100644
--- a/internal/ai/patrol_findings_additional_test.go
+++ b/internal/ai/patrol_findings_additional_test.go
@@ -1171,6 +1171,52 @@ func TestPatrolFindingCreatorAdapter_ResolveFinding_SkipsVerifierForCategoriesTh
}
}
+func TestPatrolFindingCreatorAdapter_ResolveFinding_RejectsWhenVerifierIsInconclusive(t *testing.T) {
+ // For event/persistent categories with a registered deterministic
+ // verifier (backup-failed in this case), an inconclusive verifier
+ // outcome must reject the LLM's resolve attempt. Earlier behaviour
+ // was "fail open — allow resolve and warn" which let the
+ // auto_resolved → re-detected cycle continue any time the verifier
+ // errored. Resolution of an event finding is effectively permanent
+ // (next detection registers as a regression and inflates counters),
+ // so the safe default is to refuse and ask the operator or a
+ // re-run to confirm.
+ //
+ // We trigger the inconclusive path by calling VerifyFixResolved on
+ // a service that doesn't have a chat service / executor wired up,
+ // which causes getExecutorForVerification to return an
+ // ErrVerificationUnknown error — exactly the "fail-closed" code
+ // path the gate now defends.
+ ps := NewPatrolService(nil, nil)
+ finding := &Finding{
+ ID: "backup-1",
+ Key: "backup-failed",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryBackup,
+ ResourceID: "vm-100",
+ ResourceName: "delly",
+ ResourceType: "backup",
+ Title: "Backup failed",
+ DetectedAt: time.Now().Add(-time.Hour),
+ LastSeenAt: time.Now().Add(-time.Hour),
+ }
+ ps.findings.Add(finding)
+
+ adapter := newPatrolFindingCreatorAdapterState(ps, newPatrolRuntimeState(models.StateSnapshot{}))
+ err := adapter.ResolveFinding(finding.ID, "no backup failures in current investigation")
+ if err == nil {
+ t.Fatal("expected resolve to fail when deterministic verifier is inconclusive; got nil error (fail-open regression)")
+ }
+ if !strings.Contains(err.Error(), "inconclusive") {
+ t.Errorf("expected error to mention 'inconclusive', got: %v", err)
+ }
+ if stored := ps.findings.Get(finding.ID); stored == nil {
+ t.Fatal("expected finding to remain in store")
+ } else if stored.ResolvedAt != nil {
+ t.Fatalf("expected finding to remain unresolved on inconclusive verification, got ResolvedAt=%v", stored.ResolvedAt)
+ }
+}
+
func TestPatrolFindingCreatorAdapter_ResolveFinding_FallsThroughWhenNoVerifierAvailable(t *testing.T) {
// Reliability category does NOT support stale-auto-resolve, but
// "node-offline" has no deterministic verifier. The gate must fall