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.

Make Patrol lifecycle decisions idempotent

rcourtmanff15cd93ac22
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index fc80978b0f..36cc6fb0f1 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -143,6 +143,16 @@ finding heartbeat unchanged. The active-findings snapshot is likewise a
one-shot Watch capability: after the first successful `patrol_get_findings`,
the model no longer receives that tool in subsequent turns and must reuse the
accepted result.
+The provider-neutral Watch orchestration boundary also collapses an exact
+repeat of a finding lifecycle name and canonical arguments before it becomes a
+second canonical tool invocation. This applies to repeated calls in one
+provider batch and to calls repeated after an accepted lifecycle result. It
+does not collapse calls with different arguments, so the model can still
+report causally independent incidents sequentially. Lifecycle stream starts
+are delayed until the complete provider batch is normalized, preventing a
+suppressed retry from appearing as a second action in Patrol history or the
+browser. The finding adapter remains independently idempotent as the durable
+write boundary.
Patrol reports one operator-facing finding per causal incident. Symptoms that
share a causal chain are grouped on the user-facing degraded resource with
dependency evidence and honest uncertainty in the same finding; causally
@@ -7234,9 +7244,12 @@ target. Deleted-resource reconciliation still uses the full current global
state, and the synthetic Patrol runtime finding retains its existing special
handling.
-Every provider tool call from the main pass, evaluation pass, and assessment
-sweep is merged into the one durable Patrol run trace, including raw provider
-arguments, failed calls, and bounded outputs. Qualification and operator
-forensics therefore see the complete model-owned decision path; a follow-up
-cannot hide a duplicate findings read or a failed lifecycle write in an
-ephemeral callback.
+Every provider tool call admitted by the orchestration boundary from the main
+pass, evaluation pass, and assessment sweep is merged into the one durable
+Patrol run trace, including raw provider arguments, failed calls, and bounded
+outputs. Qualification and operator forensics therefore see the complete
+canonical model-owned decision path; a follow-up cannot hide a duplicate
+findings read or a failed lifecycle write in an ephemeral callback. Exact
+finding-lifecycle retries suppressed before canonical invocation are runtime
+loop-control decisions rather than tool executions and do not create a second
+tool-start/tool-end pair.
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index 6be55c1a59..ac0179f899 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -386,6 +386,45 @@ func isPatrolFindingLifecycleWrite(toolName string) bool {
}
}
+// filterRepeatedPatrolFindingLifecycleCalls keeps exact lifecycle retries from
+// becoming a second canonical tool invocation. Models occasionally repeat an
+// already accepted report or assessment on the next bounded completion turn,
+// even though the accepted result is present in context. The finding adapter
+// is independently idempotent, but admitting the retry still creates noisy
+// execution history and wastes a tool decision.
+//
+// Calls that differ in name or canonical arguments remain model-owned and are
+// preserved, so sequential reports for independent incidents still work. An
+// exact duplicate inside one provider batch is also collapsed to its first
+// call; a failed first call must be corrected on the bounded repair turn with
+// different arguments rather than retried unchanged.
+func filterRepeatedPatrolFindingLifecycleCalls(toolCalls []providers.ToolCall, accepted map[string]struct{}) ([]providers.ToolCall, []providers.ToolCall) {
+ if len(toolCalls) == 0 {
+ return toolCalls, nil
+ }
+
+ filtered := make([]providers.ToolCall, 0, len(toolCalls))
+ suppressed := make([]providers.ToolCall, 0)
+ seenThisTurn := make(map[string]struct{})
+ for _, tc := range toolCalls {
+ if !isPatrolFindingLifecycleWrite(tc.Name) {
+ filtered = append(filtered, tc)
+ continue
+ }
+
+ key := toolCallKey(tc.Name, tc.Input)
+ _, alreadyAccepted := accepted[key]
+ _, alreadySeen := seenThisTurn[key]
+ if alreadyAccepted || alreadySeen {
+ suppressed = append(suppressed, tc)
+ continue
+ }
+ seenThisTurn[key] = struct{}{}
+ filtered = append(filtered, tc)
+ }
+ return filtered, suppressed
+}
+
func containsPatrolFindingReport(toolCalls []providers.ToolCall) bool {
for _, tc := range toolCalls {
if strings.TrimSpace(tc.Name) == agentcapabilities.PatrolReportFindingToolName {
@@ -851,6 +890,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
investigationProposalCompleted := false
acceptedFindingReports := 0
patrolFindingsReadCompleted := false
+ acceptedPatrolLifecycleCallKeys := make(map[string]struct{})
// Loop detection: track identical tool calls (name + serialized input).
// After maxIdenticalCalls identical invocations, the next one is blocked.
@@ -1225,6 +1265,13 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
if data.Name == pulseQuestionToolName {
return
}
+ // Finding lifecycle starts are delayed until the complete provider
+ // batch is normalized. This lets the orchestration boundary absorb
+ // exact same-turn or already-accepted retries without presenting a
+ // second canonical tool invocation to Patrol history or the UI.
+ if isPatrolFindingLifecycleWrite(data.Name) {
+ return
+ }
key := toolStartKey(data.ID, data.Name)
if len(data.Input) == 0 {
if key != "" && !toolStartMapHas(visibleToolStarts, data.ID, data.Name) && !toolStartMapHas(suppressedToolStarts, data.ID, data.Name) {
@@ -1253,6 +1300,9 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
if data.Name == pulseQuestionToolName {
return
}
+ if isPatrolFindingLifecycleWrite(data.Name) {
+ return
+ }
if toolStartMapHas(suppressedToolStarts, data.ID, data.Name) {
return
}
@@ -1408,6 +1458,17 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
Msg("[AgenticLoop] Model returned tool calls after tools were omitted — stripping them")
toolCalls = nil
}
+ if isPatrolDetectionExecution(a.currentExecutionProfile()) && len(toolCalls) > 0 {
+ var suppressed []providers.ToolCall
+ toolCalls, suppressed = filterRepeatedPatrolFindingLifecycleCalls(toolCalls, acceptedPatrolLifecycleCallKeys)
+ for _, tc := range suppressed {
+ log.Info().
+ Str("tool", tc.Name).
+ Str("id", tc.ID).
+ Str("session_id", sessionID).
+ Msg("[AgenticLoop] Suppressed repeated Patrol finding lifecycle intent before canonical invocation")
+ }
+ }
a.totalToolCalls += len(toolCalls)
// Check mid-run budget after each turn completes
@@ -2091,6 +2152,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
patrolFindingLifecycleFailedThisTurn = true
} else {
patrolFindingLifecycleSucceededThisTurn = true
+ acceptedPatrolLifecycleCallKeys[toolCallKey(tc.Name, tc.Input)] = struct{}{}
}
}
diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.go
index 7613f12811..aa855d85de 100644
--- a/internal/ai/chat/agentic_additional_test.go
+++ b/internal/ai/chat/agentic_additional_test.go
@@ -428,6 +428,33 @@ func TestPatrolFindingLifecycleContinuationRequestNarrowsWatchTools(t *testing.T
}
}
+func TestFilterRepeatedPatrolFindingLifecycleCallsPreservesDistinctDecisions(t *testing.T) {
+ first := providers.ToolCall{ID: "report-a", Name: agentcapabilities.PatrolReportFindingToolName, Input: map[string]interface{}{
+ "key": "health-a", "resource_id": "app-container-a",
+ }}
+ repeated := first
+ repeated.ID = "report-a-repeated"
+ second := providers.ToolCall{ID: "report-b", Name: agentcapabilities.PatrolReportFindingToolName, Input: map[string]interface{}{
+ "key": "health-b", "resource_id": "app-container-b",
+ }}
+ read := providers.ToolCall{ID: "query", Name: agentcapabilities.PulseQueryToolName, Input: map[string]interface{}{"action": "fleet"}}
+
+ filtered, suppressed := filterRepeatedPatrolFindingLifecycleCalls([]providers.ToolCall{first, repeated, second, read}, nil)
+ if len(filtered) != 3 || filtered[0].ID != first.ID || filtered[1].ID != second.ID || filtered[2].ID != read.ID {
+ t.Fatalf("filtered calls = %+v, want first report, distinct report, and read", filtered)
+ }
+ if len(suppressed) != 1 || suppressed[0].ID != repeated.ID {
+ t.Fatalf("suppressed calls = %+v, want exact repeated report only", suppressed)
+ }
+
+ filtered, suppressed = filterRepeatedPatrolFindingLifecycleCalls([]providers.ToolCall{first, second}, map[string]struct{}{
+ toolCallKey(first.Name, first.Input): {},
+ })
+ if len(filtered) != 1 || filtered[0].ID != second.ID || len(suppressed) != 1 || suppressed[0].ID != first.ID {
+ t.Fatalf("accepted-call filtering = filtered:%+v suppressed:%+v", filtered, suppressed)
+ }
+}
+
func TestAgenticLoopRemovesPatrolFindingsReadAfterSuccess(t *testing.T) {
provider := &stubStreamingProvider{}
executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
@@ -1000,6 +1027,106 @@ func TestAgenticLoopAllowsSequentialIndependentWatchFindings(t *testing.T) {
}
}
+func TestAgenticLoopSuppressesExactRepeatedAcceptedPatrolReport(t *testing.T) {
+ provider := &stubStreamingProvider{}
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ executor.ApplyExecutionProfile(tools.ProfilePatrolDetection)
+ creator := &repairTestPatrolFindingCreator{}
+ executor.SetPatrolFindingCreator(creator)
+ loop := NewAgenticLoop(provider, executor, "full Patrol prompt")
+ loop.SetExecutionProfile(tools.ProfilePatrolDetection)
+ loop.SetMaxTurns(4)
+
+ reportInput := map[string]interface{}{
+ "key": "restart-loop",
+ "severity": "warning",
+ "category": "reliability",
+ "resource_id": "app-container-worker",
+ "resource_name": "worker",
+ "resource_type": "app-container",
+ "title": "Container restart count exceeds threshold",
+ "description": "Provider reported four restarts while the container remained running.",
+ "recommendation": "Inspect the restart pattern and recent exit logs.",
+ "evidence": "Provider state reports four restarts.",
+ }
+
+ providerCalls := 0
+ provider.chatStream = func(_ context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ providerCalls++
+ switch providerCalls {
+ case 1:
+ call := providers.ToolCall{ID: "get-findings", Name: agentcapabilities.PatrolGetFindingsToolName, Input: map[string]interface{}{}}
+ callback(providers.StreamEvent{Type: "tool_start", Data: providers.ToolStartEvent{ID: call.ID, Name: call.Name, Input: call.Input}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{call}}})
+ case 2:
+ call := providers.ToolCall{ID: "report-first", Name: agentcapabilities.PatrolReportFindingToolName, Input: reportInput}
+ callback(providers.StreamEvent{Type: "tool_start", Data: providers.ToolStartEvent{ID: call.ID, Name: call.Name, Input: call.Input}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{call}}})
+ case 3:
+ if req.System != patrolFindingLifecycleContinuationSystemPrompt {
+ t.Fatalf("repeat request system = %q, want lifecycle continuation", req.System)
+ }
+ call := providers.ToolCall{ID: "report-repeated", Name: agentcapabilities.PatrolReportFindingToolName, Input: reportInput}
+ callback(providers.StreamEvent{Type: "tool_start", Data: providers.ToolStartEvent{ID: call.ID, Name: call.Name, Input: call.Input}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{call}}})
+ case 4:
+ if len(req.Tools) != 0 {
+ t.Fatalf("final summary unexpectedly offered tools: %+v", req.Tools)
+ }
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "The restart issue was recorded once."}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
+ default:
+ t.Fatalf("unexpected provider call %d", providerCalls)
+ }
+ return nil
+ }
+
+ available := []providers.Tool{
+ {Name: agentcapabilities.PatrolGetFindingsToolName},
+ {Name: agentcapabilities.PatrolReportFindingToolName},
+ {Name: agentcapabilities.PatrolAssessFindingToolName},
+ }
+ var reportStarts, reportEnds int
+ result, err := loop.ExecuteWithTools(context.Background(), "repeated-accepted-report", []Message{{Role: "user", Content: "check worker"}}, available, func(event StreamEvent) {
+ switch event.Type {
+ case "tool_start":
+ var data ToolStartData
+ if err := json.Unmarshal(event.Data, &data); err != nil {
+ t.Fatalf("decode tool_start: %v", err)
+ }
+ if data.Name == agentcapabilities.PatrolReportFindingToolName {
+ reportStarts++
+ }
+ case "tool_end":
+ var data ToolEndData
+ if err := json.Unmarshal(event.Data, &data); err != nil {
+ t.Fatalf("decode tool_end: %v", err)
+ }
+ if data.Name == agentcapabilities.PatrolReportFindingToolName {
+ reportEnds++
+ }
+ }
+ })
+ if err != nil {
+ t.Fatalf("repeated accepted report run failed: %v", err)
+ }
+ if providerCalls != 4 {
+ t.Fatalf("provider calls = %d, want read, report, absorbed repeat, summary", providerCalls)
+ }
+ if reportStarts != 1 || reportEnds != 1 {
+ t.Fatalf("canonical report events = starts:%d ends:%d, want exactly one pair", reportStarts, reportEnds)
+ }
+ if len(creator.created) != 1 || creator.created[0].ResourceID != "app-container-worker" {
+ t.Fatalf("created findings = %+v, want one canonical report", creator.created)
+ }
+ if loop.GetTotalToolCalls() != 2 {
+ t.Fatalf("effective tool calls = %d, want findings read plus one report", loop.GetTotalToolCalls())
+ }
+ if len(result) == 0 || result[len(result)-1].Content != "The restart issue was recorded once." {
+ t.Fatalf("final result = %+v", result)
+ }
+}
+
func TestAgenticLoopStopsFindingContinuationAtAcceptedReportBudget(t *testing.T) {
provider := &stubStreamingProvider{}
executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})