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.

Harden Patrol provider streams and runtime scoring

rcourtman7deaf60b3708
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index e332232cc0..6718f863c2 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -5625,6 +5625,18 @@ OpenAI-compatible chat streams. Provider reads that return payload bytes with
process the buffered frame set and route tool-call assembly plus final done
event emission through the same canonical finalizer used for `[DONE]` instead
of dropping the last chunk or leaving tool calls unfinalized on clean close.
+Patrol detection and investigation streams under that boundary must also carry
+an explicit 60-second inter-chunk stall allowance, capped by the operator's
+configured provider request timeout. Interactive Assistant streams retain the
+short default stall bound. A compatible provider pausing between streamed
+reasoning and its next tool-call chunk must not invalidate an otherwise live
+Patrol run, while a genuinely stalled stream must still terminate within the
+Patrol run budget.
+Qualification scoring must keep synthetic Patrol runtime findings on the
+`ai-service` resource separate from model-authored infrastructure findings.
+Provider/runtime failure remains an unconditional qualification hard failure,
+but its synthetic service finding must not be reported as an infrastructure
+false positive or matched to scenario ground truth.
That same provider-transport boundary owns OpenAI-compatible tool protocol
adaptation. Pulse must keep normal tool selection automatic/model-owned for
OpenAI-compatible providers, including direct DeepSeek paths. Text-only
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index 9bc66d1aaa..97b8e2c39c 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -28,6 +28,8 @@ type parallelToolResult struct {
Err error
}
+const patrolProviderStreamIdleTimeout = 60 * time.Second
+
func isRetryableProviderStreamError(err error) bool {
if err == nil {
return false
@@ -477,13 +479,14 @@ func (a *AgenticLoop) executeToolSafely(ctx context.Context, id, name string, in
// AgenticLoop handles the tool-calling loop with streaming
type AgenticLoop struct {
- provider providers.StreamingProvider
- executor *tools.PulseToolExecutor
- tools []providers.Tool
- baseSystemPrompt string // Base prompt without mode context
- maxTurns int
- orgID string
- executionID string
+ provider providers.StreamingProvider
+ executor *tools.PulseToolExecutor
+ tools []providers.Tool
+ baseSystemPrompt string // Base prompt without mode context
+ maxTurns int
+ orgID string
+ executionID string
+ streamIdleTimeout time.Duration
// Provider info for telemetry (e.g., "anthropic", "claude-3-sonnet")
providerName string
@@ -658,6 +661,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
providerName := a.providerName
modelName := a.modelName
requestSanitizer := a.requestSanitizer
+ streamIdleTimeout := a.streamIdleTimeout
a.mu.Unlock()
// === MID-TURN STEERING: inject queued user messages at the boundary ===
@@ -709,10 +713,11 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
// Build the request with dynamic system prompt (includes current mode)
systemPrompt := a.getSystemPrompt()
req := providers.ChatRequest{
- Messages: providerMessages,
- System: systemPrompt,
- Tools: tools,
- ExecutionID: a.executionID,
+ Messages: providerMessages,
+ System: systemPrompt,
+ Tools: tools,
+ ExecutionID: a.executionID,
+ StreamIdleTimeout: streamIdleTimeout,
}
// Tool selection is model-owned. Pulse normally exposes the governed tool
diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.go
index 5beab15d40..39bdf0d74a 100644
--- a/internal/ai/chat/agentic_additional_test.go
+++ b/internal/ai/chat/agentic_additional_test.go
@@ -36,6 +36,19 @@ func TestAgenticLoop_Setters(t *testing.T) {
if !called {
t.Fatalf("expected budgetChecker to be invoked")
}
+
+ loop.SetExecutionProfile(tools.ProfilePatrolDetection)
+ if loop.streamIdleTimeout != patrolProviderStreamIdleTimeout {
+ t.Fatalf("detection stream idle timeout=%s want %s", loop.streamIdleTimeout, patrolProviderStreamIdleTimeout)
+ }
+ loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
+ if loop.streamIdleTimeout != patrolProviderStreamIdleTimeout {
+ t.Fatalf("investigation stream idle timeout=%s want %s", loop.streamIdleTimeout, patrolProviderStreamIdleTimeout)
+ }
+ loop.SetExecutionProfile(tools.ProfileInteractiveAssistant)
+ if loop.streamIdleTimeout != 0 {
+ t.Fatalf("interactive stream idle timeout=%s want provider default", loop.streamIdleTimeout)
+ }
}
func TestPruneMessagesForModel_Stateless(t *testing.T) {
diff --git a/internal/ai/chat/agentic_control.go b/internal/ai/chat/agentic_control.go
index 4304a89220..5f36745693 100644
--- a/internal/ai/chat/agentic_control.go
+++ b/internal/ai/chat/agentic_control.go
@@ -30,6 +30,11 @@ func (a *AgenticLoop) SetExecutionProfile(profile tools.ExecutionProfile) {
}
a.mu.Lock()
a.executionProfile = profile
+ if profile == tools.ProfilePatrolDetection || profile == tools.ProfilePatrolInvestigation {
+ a.streamIdleTimeout = patrolProviderStreamIdleTimeout
+ } else {
+ a.streamIdleTimeout = 0
+ }
a.mu.Unlock()
}
diff --git a/internal/ai/chat/service_patrol_additional_test.go b/internal/ai/chat/service_patrol_additional_test.go
index effea7ee27..18df3c2d6c 100644
--- a/internal/ai/chat/service_patrol_additional_test.go
+++ b/internal/ai/chat/service_patrol_additional_test.go
@@ -226,6 +226,9 @@ func TestService_ExecutePatrolStream_Success(t *testing.T) {
if mockProvider.lastRequest.ExecutionID != "patrol-run-123" {
t.Fatalf("execution_id=%q want patrol-run-123", mockProvider.lastRequest.ExecutionID)
}
+ if mockProvider.lastRequest.StreamIdleTimeout != patrolProviderStreamIdleTimeout {
+ t.Fatalf("stream_idle_timeout=%s want %s", mockProvider.lastRequest.StreamIdleTimeout, patrolProviderStreamIdleTimeout)
+ }
if doneCount != 1 {
t.Fatalf("expected done event to be emitted")
}
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.go
index a3af463bf3..a476b14018 100644
--- a/internal/ai/providers/openai.go
+++ b/internal/ai/providers/openai.go
@@ -167,6 +167,16 @@ func boundedOpenAIStreamChunkTimeout(timeout time.Duration) time.Duration {
return openaiStreamChunkTimeout
}
+func streamChunkTimeoutForRequest(base, requestLimit, requested time.Duration) time.Duration {
+ if requested <= base {
+ return base
+ }
+ if requestLimit > 0 && requested > requestLimit {
+ return requestLimit
+ }
+ return requested
+}
+
type openAIStreamReadResult struct {
n int
err error
@@ -1131,8 +1141,9 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
}
receivedFirstChunk := false
+ streamChunkTimeout := streamChunkTimeoutForRequest(c.streamChunkTimeout, c.streamFirstChunkTimeout, req.StreamIdleTimeout)
for {
- chunkTimeout := c.streamChunkTimeout
+ chunkTimeout := streamChunkTimeout
if !receivedFirstChunk {
chunkTimeout = c.streamFirstChunkTimeout
}
diff --git a/internal/ai/providers/openai_test.go b/internal/ai/providers/openai_test.go
index 7f7dc5973e..b41def9cce 100644
--- a/internal/ai/providers/openai_test.go
+++ b/internal/ai/providers/openai_test.go
@@ -361,6 +361,42 @@ func TestOpenAIClient_ChatStream_TimesOutWaitingForLaterStreamChunk(t *testing.T
assert.False(t, doneCalled)
}
+func TestOpenAIClient_ChatStream_RequestIdleTimeoutExtendsLaterChunkWait(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.WriteHeader(http.StatusOK)
+ flusher := w.(http.Flusher)
+ fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"first\"}}]}\n\n")
+ flusher.Flush()
+ time.Sleep(40 * time.Millisecond)
+ fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ flusher.Flush()
+ }))
+ defer server.Close()
+
+ client := NewOpenAIClient("sk-test", "gpt-4", server.URL, time.Second)
+ client.streamChunkTimeout = 10 * time.Millisecond
+ var content string
+ err := client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "Hi"}},
+ StreamIdleTimeout: 100 * time.Millisecond,
+ }, func(event StreamEvent) {
+ if event.Type == "content" {
+ content += event.Data.(ContentEvent).Text
+ }
+ })
+
+ require.NoError(t, err)
+ assert.Equal(t, "first", content)
+}
+
+func TestStreamChunkTimeoutForRequestHonorsConfiguredLimit(t *testing.T) {
+ assert.Equal(t, 12*time.Second, streamChunkTimeoutForRequest(12*time.Second, 5*time.Minute, 0))
+ assert.Equal(t, time.Minute, streamChunkTimeoutForRequest(12*time.Second, 5*time.Minute, time.Minute))
+ assert.Equal(t, 30*time.Second, streamChunkTimeoutForRequest(12*time.Second, 30*time.Second, time.Minute))
+}
+
// TestOpenAIClient_ChatStream_OpenRouterReasoning guards the OpenRouter reasoning
// path. OpenRouter (and other OpenAI-compatible gateways) stream chain-of-thought
// in the "reasoning" delta field rather than DeepSeek's "reasoning_content". A
diff --git a/internal/ai/providers/provider.go b/internal/ai/providers/provider.go
index 32b84bf886..5bfe2c80ff 100644
--- a/internal/ai/providers/provider.go
+++ b/internal/ai/providers/provider.go
@@ -3,6 +3,7 @@ package providers
import (
"context"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
)
@@ -69,14 +70,15 @@ type ToolChoice struct {
// ChatRequest represents a request to the AI provider
type ChatRequest struct {
- Messages []Message `json:"messages"`
- Model string `json:"model"`
- ExecutionID string `json:"execution_id,omitempty"` // Stable higher-level run ID shared across related provider turns
- MaxTokens int `json:"max_tokens,omitempty"`
- Temperature float64 `json:"temperature,omitempty"`
- System string `json:"system,omitempty"` // System prompt (Anthropic style)
- Tools []Tool `json:"tools,omitempty"` // Available tools
- ToolChoice *ToolChoice `json:"tool_choice,omitempty"` // nil = model-owned automatic selection; none = text-only safety brake; required = provider-native forced tool use where supported
+ Messages []Message `json:"messages"`
+ Model string `json:"model"`
+ ExecutionID string `json:"execution_id,omitempty"` // Stable higher-level run ID shared across related provider turns
+ MaxTokens int `json:"max_tokens,omitempty"`
+ Temperature float64 `json:"temperature,omitempty"`
+ System string `json:"system,omitempty"` // System prompt (Anthropic style)
+ Tools []Tool `json:"tools,omitempty"` // Available tools
+ ToolChoice *ToolChoice `json:"tool_choice,omitempty"` // nil = model-owned automatic selection; none = text-only safety brake; required = provider-native forced tool use where supported
+ StreamIdleTimeout time.Duration `json:"-"` // Optional use-case-specific inter-chunk stall allowance; provider request payloads must not serialize it.
}
func (r ChatRequest) NormalizeCollections() ChatRequest {
diff --git a/internal/ai/qualification/scorer.go b/internal/ai/qualification/scorer.go
index 8325ce6f30..336261e33a 100644
--- a/internal/ai/qualification/scorer.go
+++ b/internal/ai/qualification/scorer.go
@@ -108,6 +108,7 @@ type Score struct {
EndToEndLatency time.Duration `json:"end_to_end_latency_ns"`
Matches []MatchResult `json:"matches"`
UnmatchedFindingIDs []string `json:"unmatched_finding_ids,omitempty"`
+ RuntimeFindingIDs []string `json:"runtime_finding_ids,omitempty"`
HardFailures []string `json:"hard_failures,omitempty"`
GateFailures []string `json:"gate_failures,omitempty"`
}
@@ -210,13 +211,21 @@ func ScoreRun(input ScoringInput) Score {
score.Cost = CostEstimate{Provider: provider, Model: model, USD: usd, Known: known, PricingAsOf: price.AsOf, InputPerMTok: price.InputUSDPerMTok, OutputPerMTok: price.OutputUSDPerMTok}
eligibleFindings := findingsEligibleForDetection(input.Findings, input.Run.FindingAssessments)
+ infrastructureFindings := make([]Finding, 0, len(eligibleFindings))
+ for _, finding := range eligibleFindings {
+ if isPatrolRuntimeFinding(finding) {
+ score.RuntimeFindingIDs = append(score.RuntimeFindingIDs, finding.ID)
+ continue
+ }
+ infrastructureFindings = append(infrastructureFindings, finding)
+ }
used := make(map[string]struct{})
for _, truth := range input.GroundTruth.Faults {
if !truth.Active {
continue
}
fault := findFault(input.Manifest.Faults, truth.ID)
- match, found := bestFindingMatch(truth, fault, eligibleFindings, used)
+ match, found := bestFindingMatch(truth, fault, infrastructureFindings, used)
result := evaluateMatch(truth, fault, match, found)
if found {
detectedAt := findingDetectionTime(match, input.Run.FindingAssessments)
@@ -244,7 +253,7 @@ func ScoreRun(input ScoringInput) Score {
}
score.Matches = append(score.Matches, result)
}
- for _, finding := range eligibleFindings {
+ for _, finding := range infrastructureFindings {
if _, ok := used[finding.ID]; !ok {
if !isExpectedCorrelatedSymptom(input.GroundTruth, finding.ResourceID) {
score.UnmatchedFindingIDs = append(score.UnmatchedFindingIDs, finding.ID)
@@ -340,6 +349,11 @@ func findingsEligibleForDetection(findings []Finding, assessments []PatrolFindin
return eligible
}
+func isPatrolRuntimeFinding(finding Finding) bool {
+ return strings.EqualFold(strings.TrimSpace(finding.Key), "ai-patrol-error") ||
+ strings.EqualFold(strings.TrimSpace(finding.ResourceID), "ai-service")
+}
+
func (g GroundTruth) activeFaultCount() int {
count := 0
for _, fault := range g.Faults {
diff --git a/internal/ai/qualification/scorer_test.go b/internal/ai/qualification/scorer_test.go
index 297d4a5442..c2e03d7da7 100644
--- a/internal/ai/qualification/scorer_test.go
+++ b/internal/ai/qualification/scorer_test.go
@@ -59,6 +59,35 @@ func TestScoreRunPreservesDiagnosticsButFailsErroredPatrolRun(t *testing.T) {
}
}
+func TestScoreRunSeparatesSyntheticRuntimeFindingFromInfrastructureFalsePositives(t *testing.T) {
+ manifest := validTestManifest()
+ manifest.Gates = GateSpec{MaxFalsePositives: 0}
+ ground := GroundTruth{Faults: []FaultTruth{{
+ ID: "fault", CausalGroup: "fault", TargetName: "target",
+ ResourceID: "r1", ResourceType: "app-container", Active: true,
+ }}}
+ runtimeFinding := Finding{
+ ID: "runtime-error", Key: "ai-patrol-error", ResourceID: "ai-service",
+ ResourceName: "Pulse Patrol Service", ResourceType: "service",
+ Category: "reliability", Severity: "warning",
+ }
+ score := ScoreRun(ScoringInput{
+ Manifest: manifest, GroundTruth: ground, Model: "ollama:qwen3:8b",
+ Run: PatrolRun{Status: "error", ErrorCount: 1}, Findings: []Finding{runtimeFinding},
+ FaultsIntact: true, NoMutation: true,
+ })
+
+ if score.FalsePositives != 0 || len(score.UnmatchedFindingIDs) != 0 {
+ t.Fatalf("synthetic runtime finding counted as infrastructure false positive: %+v", score)
+ }
+ if len(score.RuntimeFindingIDs) != 1 || score.RuntimeFindingIDs[0] != "runtime-error" {
+ t.Fatalf("runtime finding was not reported separately: %+v", score)
+ }
+ if score.Passed || !strings.Contains(strings.Join(score.HardFailures, "\n"), "runtime errors") {
+ t.Fatalf("runtime failure must remain a hard failure: %+v", score)
+ }
+}
+
func TestApplyProTrackGatesRequiresGroundedInvestigationAndBoundAction(t *testing.T) {
manifest := validTestManifest()
manifest.Track = TrackRemediation