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.

Keep Patrol continuations stateless

rcourtman67bbed4c40ad
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index d2eba7a7a5..5ce704cbbf 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -7166,6 +7166,18 @@ complete snapshot exists it receives only `patrol_get_findings` plus
`patrol_assess_finding`. These are structured call-site allowlists applied
after profile projection and may only reduce authority. An unavailable or
unknown requested tool fails closed. Prompt text never selects the manifest.
+Each Patrol invocation, including the main pass and both continuations, receives
+a fresh infrastructure workflow FSM and resolved-resource context. Its stable
+session ID remains a forensic-log key only and cannot carry a prior run's read
+authority, resource alias, validated target, or unfinished verification state
+into the next call.
+While that fresh FSM is resolving, Patrol state-only writes bypass the generic
+infrastructure read-before-write gate because their server-owned run adapters
+already validate exact finding scope, active finding identity, complete
+findings-read preconditions, or exact objective revision. The exception is
+limited to the Patrol detection profile and resolving state; infrastructure
+writes remain blocked, and a preceding infrastructure write's verification
+state can never be bypassed by a finding lifecycle call.
An explicitly scoped Watch may carry related hosts or dependencies in its
effective runtime snapshot as model evidence, but active, dismissed, and
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index 50dda58a0f..b40aa0dfb1 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -416,19 +416,20 @@ func applySuccessfulToolFSM(fsm *SessionFSM, toolKind ToolKind, toolName string)
return false
}
-// patrolWriteHasCoreValidatedTarget reports the one Patrol state-only write
-// whose target is already established by server-authored run context. An
-// objective-planning run carries the exact objective ID and optimistic
-// revision, and the proposal store validates both atomically. Requiring an
-// unrelated read before that write adds no target safety and can strand quiet
-// scoped runs that have no other evidence call to make.
+// patrolWriteHasCoreValidatedTarget reports Patrol state-only writes whose
+// target is validated by the server-owned run adapter. Finding lifecycle
+// adapters enforce the exact run scope, active finding identity, and complete
+// findings-read precondition; objective proposals validate the exact objective
+// ID and optimistic revision atomically. Requiring an unrelated infrastructure
+// read before these writes adds no target safety and can strand bounded Patrol
+// continuations that intentionally expose no read tool.
//
// This exception is intentionally limited to RESOLVING. It never permits a
-// proposal to bypass verification of a preceding infrastructure write.
+// state-only call to bypass verification of a preceding infrastructure write.
func patrolWriteHasCoreValidatedTarget(profile tools.ExecutionProfile, fsm *SessionFSM, toolName string) bool {
return profile == tools.ProfilePatrolDetection &&
fsm != nil && fsm.State == StateResolving &&
- strings.TrimSpace(toolName) == agentcapabilities.PatrolProposeObserverToolName
+ isPatrolStateOnlyWrite(toolName)
}
func appendFSMVerificationPrompt(messages []providers.Message, prompt string) []providers.Message {
diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.go
index 15b57f3101..3d08d1b3e7 100644
--- a/internal/ai/chat/agentic_additional_test.go
+++ b/internal/ai/chat/agentic_additional_test.go
@@ -268,10 +268,17 @@ func TestApplySuccessfulToolFSM_ObserverProposalDoesNotRequireInfrastructureVeri
}
}
-func TestPatrolObserverProposalUsesOnlyCoreValidatedDetectionTarget(t *testing.T) {
+func TestPatrolStateWritesUseOnlyCoreValidatedDetectionTarget(t *testing.T) {
fsm := NewSessionFSM()
- if !patrolWriteHasCoreValidatedTarget(tools.ProfilePatrolDetection, fsm, agentcapabilities.PatrolProposeObserverToolName) {
- t.Fatal("expected detection objective proposal to use its core-validated target")
+ for _, toolName := range []string{
+ agentcapabilities.PatrolReportFindingToolName,
+ agentcapabilities.PatrolAssessFindingToolName,
+ agentcapabilities.PatrolResolveFindingToolName,
+ agentcapabilities.PatrolProposeObserverToolName,
+ } {
+ if !patrolWriteHasCoreValidatedTarget(tools.ProfilePatrolDetection, fsm, toolName) {
+ t.Fatalf("expected %s to use its core-validated Patrol target", toolName)
+ }
}
for _, test := range []struct {
profile tools.ExecutionProfile
@@ -281,7 +288,7 @@ func TestPatrolObserverProposalUsesOnlyCoreValidatedDetectionTarget(t *testing.T
{tools.ProfilePatrolInvestigation, StateResolving, agentcapabilities.PatrolProposeObserverToolName},
{tools.ProfileInteractiveAssistant, StateResolving, agentcapabilities.PatrolProposeObserverToolName},
{tools.ProfilePatrolDetection, StateVerifying, agentcapabilities.PatrolProposeObserverToolName},
- {tools.ProfilePatrolDetection, StateResolving, agentcapabilities.PatrolReportFindingToolName},
+ {tools.ProfilePatrolDetection, StateVerifying, agentcapabilities.PatrolReportFindingToolName},
{tools.ProfilePatrolDetection, StateResolving, agentcapabilities.PulseControlToolName},
} {
fsm.State = test.state
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 07620ff904..a5784838a7 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -2882,14 +2882,19 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca
return nil, fmt.Errorf("failed to ensure patrol session: %w", err)
}
- // Set resolved context on executor (same as ExecuteStream does)
+ // Patrol's shared session ID is only a forensic log key. Resource resolution
+ // is invocation-scoped so an earlier Watch cannot leak aliases or validated
+ // action targets into a later run that happens to reuse the same ID.
if executor != nil {
- resolvedCtx := sessions.GetResolvedContext(session.ID)
+ resolvedCtx := NewResolvedContext(session.ID)
executor.SetResolvedContext(resolvedCtx)
}
- // Set session FSM
- sessionFSM := sessions.GetSessionFSM(session.ID)
+ // Patrol invocations are stateless investigations. Their session ID is a
+ // forensic log key, not a workflow-state boundary: reusing its FSM would
+ // let a prior run's read or unfinished infrastructure verification alter the
+ // next run's authority. Each invocation therefore starts from a fresh FSM.
+ sessionFSM := NewSessionFSM()
tempLoop.SetSessionFSM(sessionFSM)
// Create a fresh knowledge accumulator for this patrol run.
diff --git a/internal/ai/chat/service_patrol_additional_test.go b/internal/ai/chat/service_patrol_additional_test.go
index 3c1b318dfb..bb7730483e 100644
--- a/internal/ai/chat/service_patrol_additional_test.go
+++ b/internal/ai/chat/service_patrol_additional_test.go
@@ -25,6 +25,25 @@ func (m mockKnowledgeStore) GetKnowledge(resourceID, category string) []tools.Kn
return nil
}
+type patrolReportRecorder struct {
+ checked bool
+ inputs []tools.PatrolFindingInput
+}
+
+func (r *patrolReportRecorder) CreateFinding(input tools.PatrolFindingInput) (string, bool, error) {
+ r.inputs = append(r.inputs, input)
+ return "finding-runtime-boundary", true, nil
+}
+
+func (r *patrolReportRecorder) ResolveFinding(string, string) error { return nil }
+
+func (r *patrolReportRecorder) GetActiveFindings(string, string) []tools.PatrolFindingInfo {
+ r.checked = true
+ return nil
+}
+
+func (r *patrolReportRecorder) HasCheckedFindings() bool { return r.checked }
+
type mockStreamingProvider struct {
chatStreamFunc func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error
lastRequest providers.ChatRequest
@@ -242,6 +261,84 @@ func TestService_ExecutePatrolStream_Success(t *testing.T) {
}
}
+func TestService_ExecutePatrolStream_UsesFreshFSMAndAcceptsCoreValidatedFindingWrite(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ recorder := &patrolReportRecorder{checked: true}
+ executor.SetPatrolFindingCreator(recorder)
+
+ // A previous invocation may have ended while verifying an infrastructure
+ // write. The shared session ID is only a forensic key for Patrol and must not
+ // carry that workflow state into this bounded continuation.
+ staleFSM := store.GetSessionFSM("patrol-eval")
+ staleFSM.State = StateVerifying
+ staleFSM.WroteThisEpisode = true
+ staleFSM.ReadAfterWrite = false
+
+ service := &Service{
+ started: true,
+ sessions: store,
+ executor: executor,
+ cfg: &config.AIConfig{PatrolModel: "mock:model"},
+ }
+ providerCalls := 0
+ service.providerFactory = func(string) (providers.StreamingProvider, error) {
+ return &mockStreamingProvider{chatStreamFunc: func(_ context.Context, _ providers.ChatRequest, callback providers.StreamCallback) error {
+ providerCalls++
+ if providerCalls == 1 {
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{
+ InputTokens: 10,
+ ToolCalls: []providers.ToolCall{{
+ ID: "report-1",
+ Name: agentcapabilities.PatrolReportFindingToolName,
+ Input: map[string]interface{}{
+ "key": "service-unhealthy",
+ "severity": "warning",
+ "category": "reliability",
+ "resource_id": "app/service-a",
+ "resource_name": "service-a",
+ "resource_type": "app-container",
+ "title": "Service health check is failing",
+ "description": "The current health signal is unhealthy.",
+ "recommendation": "Inspect the bounded health-check failure and verify recovery.",
+ "evidence": "Current container health status is unhealthy.",
+ },
+ }},
+ }})
+ return nil
+ }
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "Finding recorded."}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{InputTokens: 4, OutputTokens: 2}})
+ return nil
+ }}, nil
+ }
+
+ resp, err := service.ExecutePatrolStream(context.Background(), PatrolRequest{
+ Prompt: "Record the validated signal.",
+ SessionID: "patrol-eval",
+ MaxTurns: 3,
+ AllowedToolNames: []string{agentcapabilities.PatrolReportFindingToolName},
+ }, func(StreamEvent) {})
+ if err != nil {
+ t.Fatalf("ExecutePatrolStream failed: %v", err)
+ }
+ if resp == nil || !strings.Contains(resp.Content, "Finding recorded") {
+ t.Fatalf("unexpected patrol response: %+v", resp)
+ }
+ if len(recorder.inputs) != 1 || recorder.inputs[0].ResourceID != "app/service-a" {
+ t.Fatalf("finding writes = %+v, want one exact scoped resource", recorder.inputs)
+ }
+ if providerCalls != 2 {
+ t.Fatalf("provider calls = %d, want report plus bounded summary", providerCalls)
+ }
+ if staleFSM.State != StateVerifying || staleFSM.ReadAfterWrite {
+ t.Fatalf("Patrol invocation mutated persisted forensic-session FSM: %+v", staleFSM)
+ }
+}
+
func TestRestrictPatrolProviderToolsFailsClosed(t *testing.T) {
available := []providers.Tool{
{Name: agentcapabilities.PatrolGetFindingsToolName},