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.

feat(patrol): add timeout handling and shorter retry cooldown

rcourtman519e8a637ac1
diff --git a/internal/ai/findings.go b/internal/ai/findings.go
index 21edb19ecf..c7f098e636 100644
--- a/internal/ai/findings.go
+++ b/internal/ai/findings.go
@@ -10,8 +10,9 @@ import (
// Investigation limits for automatic finding investigation.
const (
- investigationCooldown = 1 * time.Hour // Minimum time between investigation attempts
- maxInvestigationAttempts = 3 // Maximum number of investigation retries
+ investigationCooldown = 1 * time.Hour // Minimum time between investigation attempts
+ investigationTimeoutCooldown = 10 * time.Minute // Shorter cooldown for timeout failures
+ maxInvestigationAttempts = 3 // Maximum number of investigation retries
)
// FindingSeverity represents how urgent a finding is
@@ -59,6 +60,7 @@ const (
InvestigationOutcomeFixQueued InvestigationOutcome = "fix_queued" // Fix identified, awaiting approval
InvestigationOutcomeNeedsAttention InvestigationOutcome = "needs_attention" // Requires user intervention
InvestigationOutcomeCannotFix InvestigationOutcome = "cannot_fix" // AI determined it cannot fix this
+ InvestigationOutcomeTimedOut InvestigationOutcome = "timed_out" // Transient timeout, will retry sooner
)
// Finding represents an AI-discovered insight about infrastructure
@@ -166,9 +168,14 @@ func (f *Finding) ShouldInvestigate(autonomyLevel string) bool {
return false
}
- // Don't re-investigate within cooldown period (1 hour)
+ // Don't re-investigate within cooldown period
+ // Timeout failures use a shorter cooldown (10min) since they're transient
if f.LastInvestigatedAt != nil {
- if time.Since(*f.LastInvestigatedAt) < investigationCooldown {
+ cooldown := investigationCooldown
+ if f.InvestigationOutcome == string(InvestigationOutcomeTimedOut) {
+ cooldown = investigationTimeoutCooldown
+ }
+ if time.Since(*f.LastInvestigatedAt) < cooldown {
return false
}
}
@@ -233,8 +240,13 @@ func (f *Finding) CanRetryInvestigation() bool {
return false
}
// Can't retry if still in cooldown
+ // Timeout failures use a shorter cooldown (10min) since they're transient
if f.LastInvestigatedAt != nil {
- if time.Since(*f.LastInvestigatedAt) < investigationCooldown {
+ cooldown := investigationCooldown
+ if f.InvestigationOutcome == string(InvestigationOutcomeTimedOut) {
+ cooldown = investigationTimeoutCooldown
+ }
+ if time.Since(*f.LastInvestigatedAt) < cooldown {
return false
}
}
diff --git a/internal/ai/findings_timeout_test.go b/internal/ai/findings_timeout_test.go
new file mode 100644
index 0000000000..6c9f3aff28
--- /dev/null
+++ b/internal/ai/findings_timeout_test.go
@@ -0,0 +1,98 @@
+package ai
+
+import (
+ "testing"
+ "time"
+)
+
+func TestShouldInvestigate_TimeoutUsesShortCooldown(t *testing.T) {
+ // Finding with timed_out outcome and LastInvestigatedAt 15 minutes ago
+ // should be eligible for re-investigation (shorter 10min cooldown)
+ fifteenMinsAgo := time.Now().Add(-15 * time.Minute)
+ f := &Finding{
+ ID: "f1",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryPerformance,
+ ResourceID: "r1",
+ InvestigationStatus: string(InvestigationStatusFailed),
+ InvestigationOutcome: string(InvestigationOutcomeTimedOut),
+ LastInvestigatedAt: &fifteenMinsAgo,
+ InvestigationAttempts: 1,
+ }
+
+ if !f.ShouldInvestigate("approval") {
+ t.Fatalf("expected timed-out finding (15min old) to be eligible for re-investigation")
+ }
+
+ // Same finding but only 5 minutes ago — still within the 10min timeout cooldown
+ fiveMinsAgo := time.Now().Add(-5 * time.Minute)
+ f.LastInvestigatedAt = &fiveMinsAgo
+
+ if f.ShouldInvestigate("approval") {
+ t.Fatalf("expected timed-out finding (5min old) to still be in cooldown")
+ }
+}
+
+func TestShouldInvestigate_NonTimeoutKeepsLongCooldown(t *testing.T) {
+ // Finding with no special outcome (regular failure) at 15 minutes ago
+ // should NOT be eligible — still within the 1-hour cooldown
+ fifteenMinsAgo := time.Now().Add(-15 * time.Minute)
+ f := &Finding{
+ ID: "f1",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryPerformance,
+ ResourceID: "r1",
+ InvestigationStatus: string(InvestigationStatusFailed),
+ InvestigationOutcome: "", // no special outcome
+ LastInvestigatedAt: &fifteenMinsAgo,
+ InvestigationAttempts: 1,
+ }
+
+ if f.ShouldInvestigate("approval") {
+ t.Fatalf("expected non-timeout failure (15min old) to still be in 1hr cooldown")
+ }
+
+ // After 2 hours, should be eligible
+ twoHoursAgo := time.Now().Add(-2 * time.Hour)
+ f.LastInvestigatedAt = &twoHoursAgo
+ if !f.ShouldInvestigate("approval") {
+ t.Fatalf("expected non-timeout failure (2hr old) to be eligible for re-investigation")
+ }
+}
+
+func TestCanRetryInvestigation_TimeoutUsesShortCooldown(t *testing.T) {
+ fifteenMinsAgo := time.Now().Add(-15 * time.Minute)
+ f := &Finding{
+ ID: "f1",
+ Severity: FindingSeverityWarning,
+ InvestigationOutcome: string(InvestigationOutcomeTimedOut),
+ LastInvestigatedAt: &fifteenMinsAgo,
+ InvestigationAttempts: 1,
+ }
+
+ if !f.CanRetryInvestigation() {
+ t.Fatalf("expected timed-out finding (15min old) to allow retry")
+ }
+
+ fiveMinsAgo := time.Now().Add(-5 * time.Minute)
+ f.LastInvestigatedAt = &fiveMinsAgo
+
+ if f.CanRetryInvestigation() {
+ t.Fatalf("expected timed-out finding (5min old) to block retry")
+ }
+}
+
+func TestCanRetryInvestigation_NonTimeoutKeepsLongCooldown(t *testing.T) {
+ fifteenMinsAgo := time.Now().Add(-15 * time.Minute)
+ f := &Finding{
+ ID: "f1",
+ Severity: FindingSeverityWarning,
+ InvestigationOutcome: "",
+ LastInvestigatedAt: &fifteenMinsAgo,
+ InvestigationAttempts: 1,
+ }
+
+ if f.CanRetryInvestigation() {
+ t.Fatalf("expected non-timeout failure (15min old) to block retry")
+ }
+}
diff --git a/internal/ai/investigation/lifecycle_test.go b/internal/ai/investigation/lifecycle_test.go
new file mode 100644
index 0000000000..9354554a11
--- /dev/null
+++ b/internal/ai/investigation/lifecycle_test.go
@@ -0,0 +1,358 @@
+package investigation
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// stubFixVerifier implements FixVerifier for testing verification flow.
+type stubFixVerifier struct {
+ resolved bool
+ err error
+ called bool
+}
+
+func (s *stubFixVerifier) VerifyFixResolved(ctx context.Context, finding *Finding) (bool, error) {
+ s.called = true
+ return s.resolved, s.err
+}
+
+// TestLifecycle_FindingToFixVerified tests the full investigation lifecycle:
+// Finding → Investigation → Fix Execution → Verification (success)
+func TestLifecycle_FindingToFixVerified(t *testing.T) {
+ store := NewStore("")
+ findings := &stubFindingsStore{finding: &Finding{
+ ID: "f1",
+ Key: "high-cpu",
+ Title: "High CPU on web-01",
+ Severity: "critical",
+ Category: "performance",
+ ResourceID: "vm-100",
+ ResourceName: "web-01",
+ ResourceType: "vm",
+ Description: "CPU usage at 95%",
+ Evidence: "cpu=95.2%",
+ }}
+
+ chatService := &stubChatService{
+ execute: func(cb StreamCallback) error {
+ payload, _ := json.Marshal(map[string]string{
+ "text": "Investigation complete.\nPROPOSED_FIX: systemctl restart app\nTARGET_HOST: web-01",
+ })
+ cb(StreamEvent{Type: "content", Data: payload})
+ return nil
+ },
+ }
+
+ executor := &stubCommandExecutor{output: "Service restarted", code: 0}
+ verifier := &stubFixVerifier{resolved: true}
+
+ config := DefaultConfig()
+ config.VerificationDelay = 0 // Skip sleep in test
+ orchestrator := NewOrchestrator(chatService, store, findings, nil, config)
+ orchestrator.SetCommandExecutor(executor)
+ orchestrator.SetFixVerifier(verifier)
+
+ // Execute the full lifecycle
+ err := orchestrator.InvestigateFinding(context.Background(), findings.finding, "full")
+ require.NoError(t, err)
+
+ // Verify the investigation reached the terminal state
+ inv := store.GetLatestByFinding("f1")
+ require.NotNil(t, inv)
+
+ assert.Equal(t, StatusCompleted, inv.Status, "investigation should be completed")
+ assert.Equal(t, OutcomeFixVerified, inv.Outcome, "outcome should be fix_verified")
+ assert.NotNil(t, inv.ProposedFix, "should have a proposed fix")
+ assert.Equal(t, "systemctl restart app", inv.ProposedFix.Commands[0])
+ assert.Contains(t, inv.ProposedFix.Rationale, "Verification: Issue confirmed resolved")
+
+ // Verify finding was updated
+ assert.True(t, findings.updated, "findings store should have been updated")
+ assert.Equal(t, string(OutcomeFixVerified), findings.finding.InvestigationOutcome)
+ assert.Equal(t, string(StatusCompleted), findings.finding.InvestigationStatus)
+ assert.NotNil(t, findings.finding.LastInvestigatedAt)
+
+ // Verify verifier was actually called
+ assert.True(t, verifier.called, "fix verifier should have been called")
+}
+
+// TestLifecycle_FindingToFixVerificationFailed tests fix that executes but verification
+// determines the issue persists.
+func TestLifecycle_FindingToFixVerificationFailed(t *testing.T) {
+ store := NewStore("")
+ findings := &stubFindingsStore{finding: &Finding{
+ ID: "f2",
+ Key: "disk-full",
+ Title: "Disk Full",
+ Severity: "warning",
+ }}
+
+ chatService := &stubChatService{
+ execute: func(cb StreamCallback) error {
+ payload, _ := json.Marshal(map[string]string{
+ "text": "PROPOSED_FIX: apt autoremove -y\nTARGET_HOST: local",
+ })
+ cb(StreamEvent{Type: "content", Data: payload})
+ return nil
+ },
+ }
+
+ executor := &stubCommandExecutor{output: "done", code: 0}
+ verifier := &stubFixVerifier{resolved: false} // Issue still present
+
+ config := DefaultConfig()
+ config.VerificationDelay = 0
+ orchestrator := NewOrchestrator(chatService, store, findings, nil, config)
+ orchestrator.SetCommandExecutor(executor)
+ orchestrator.SetFixVerifier(verifier)
+
+ err := orchestrator.InvestigateFinding(context.Background(), findings.finding, "full")
+ require.NoError(t, err)
+
+ inv := store.GetLatestByFinding("f2")
+ require.NotNil(t, inv)
+ assert.Equal(t, OutcomeFixVerificationFailed, inv.Outcome, "outcome should be fix_verification_failed")
+ assert.Contains(t, inv.ProposedFix.Rationale, "Issue persists after fix execution")
+}
+
+// TestLifecycle_FindingToApproval tests the approval path — when autonomy is "controlled",
+// the fix should be queued for approval rather than executed.
+func TestLifecycle_FindingToApproval(t *testing.T) {
+ store := NewStore("")
+ findings := &stubFindingsStore{finding: &Finding{
+ ID: "f3",
+ Key: "mem-leak",
+ Title: "Memory Leak",
+ Severity: "critical",
+ }}
+
+ chatService := &stubChatService{
+ execute: func(cb StreamCallback) error {
+ payload, _ := json.Marshal(map[string]string{
+ "text": "PROPOSED_FIX: systemctl restart leaky-app\nTARGET_HOST: db-01",
+ })
+ cb(StreamEvent{Type: "content", Data: payload})
+ return nil
+ },
+ }
+
+ approval := &stubApprovalStore{}
+ executor := &stubCommandExecutor{output: "ok", code: 0}
+
+ config := DefaultConfig()
+ orchestrator := NewOrchestrator(chatService, store, findings, approval, config)
+ orchestrator.SetCommandExecutor(executor)
+
+ // Use "controlled" autonomy — should queue for approval, NOT auto-execute
+ err := orchestrator.InvestigateFinding(context.Background(), findings.finding, "controlled")
+ require.NoError(t, err)
+
+ inv := store.GetLatestByFinding("f3")
+ require.NotNil(t, inv)
+
+ assert.Equal(t, OutcomeFixQueued, inv.Outcome, "should queue for approval in controlled mode")
+ assert.True(t, approval.called, "approval store should have been called")
+ assert.NotNil(t, inv.ProposedFix, "fix should be recorded on investigation")
+ assert.Equal(t, "systemctl restart leaky-app", inv.ProposedFix.Commands[0])
+}
+
+// TestLifecycle_FindingToCannotFix tests the path where investigation determines
+// the issue cannot be automatically fixed.
+func TestLifecycle_FindingToCannotFix(t *testing.T) {
+ store := NewStore("")
+ findings := &stubFindingsStore{finding: &Finding{
+ ID: "f4",
+ Key: "hardware-fail",
+ Title: "Hardware Failure",
+ Severity: "critical",
+ }}
+
+ chatService := &stubChatService{
+ execute: func(cb StreamCallback) error {
+ payload, _ := json.Marshal(map[string]string{
+ "text": "CANNOT_FIX: Requires physical hardware replacement",
+ })
+ cb(StreamEvent{Type: "content", Data: payload})
+ return nil
+ },
+ }
+
+ config := DefaultConfig()
+ orchestrator := NewOrchestrator(chatService, store, findings, nil, config)
+
+ err := orchestrator.InvestigateFinding(context.Background(), findings.finding, "full")
+ require.NoError(t, err)
+
+ inv := store.GetLatestByFinding("f4")
+ require.NotNil(t, inv)
+ assert.Equal(t, OutcomeCannotFix, inv.Outcome)
+ assert.Equal(t, string(OutcomeCannotFix), findings.finding.InvestigationOutcome)
+}
+
+// TestLifecycle_TimeoutSetsOutcome tests that when investigation times out,
+// the finding is correctly tagged with OutcomeTimedOut for faster retry.
+func TestLifecycle_TimeoutSetsOutcome(t *testing.T) {
+ store := NewStore("")
+ findings := &stubFindingsStore{finding: &Finding{
+ ID: "f5",
+ Key: "slow-query",
+ Title: "Slow Queries",
+ Severity: "warning",
+ }}
+
+ chatService := &stubChatService{
+ execute: func(cb StreamCallback) error {
+ // Simulate a timeout by returning DeadlineExceeded
+ return context.DeadlineExceeded
+ },
+ }
+
+ config := DefaultConfig()
+ orchestrator := NewOrchestrator(chatService, store, findings, nil, config)
+
+ err := orchestrator.InvestigateFinding(context.Background(), findings.finding, "full")
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "investigation failed")
+
+ // Verify the finding was tagged with timed_out outcome
+ assert.Equal(t, string(StatusFailed), findings.finding.InvestigationStatus)
+ assert.Equal(t, string(OutcomeTimedOut), findings.finding.InvestigationOutcome)
+ assert.NotNil(t, findings.finding.LastInvestigatedAt)
+
+ // Verify the investigation session also has the outcome
+ inv := store.GetLatestByFinding("f5")
+ require.NotNil(t, inv)
+ assert.Equal(t, StatusFailed, inv.Status)
+ assert.Equal(t, OutcomeTimedOut, inv.Outcome)
+}
+
+// TestLifecycle_FixExecutionFails tests the path where fix command returns non-zero.
+func TestLifecycle_FixExecutionFails(t *testing.T) {
+ store := NewStore("")
+ findings := &stubFindingsStore{finding: &Finding{
+ ID: "f6",
+ Key: "stuck-service",
+ Title: "Service Not Responding",
+ Severity: "warning",
+ }}
+
+ chatService := &stubChatService{
+ execute: func(cb StreamCallback) error {
+ payload, _ := json.Marshal(map[string]string{
+ "text": "PROPOSED_FIX: systemctl restart stuck-service\nTARGET_HOST: local",
+ })
+ cb(StreamEvent{Type: "content", Data: payload})
+ return nil
+ },
+ }
+
+ executor := &stubCommandExecutor{output: "Failed to restart: unit not found", code: 1}
+
+ config := DefaultConfig()
+ config.VerificationDelay = 0
+ orchestrator := NewOrchestrator(chatService, store, findings, nil, config)
+ orchestrator.SetCommandExecutor(executor)
+
+ err := orchestrator.InvestigateFinding(context.Background(), findings.finding, "full")
+ require.NoError(t, err)
+
+ inv := store.GetLatestByFinding("f6")
+ require.NotNil(t, inv)
+ assert.Equal(t, OutcomeFixFailed, inv.Outcome)
+ assert.Contains(t, inv.ProposedFix.Rationale, "exit code 1")
+}
+
+// TestLifecycle_ReinvestigateAfterTimeout verifies that a finding that timed out
+// can be reinvestigated and succeed on the second attempt.
+func TestLifecycle_ReinvestigateAfterTimeout(t *testing.T) {
+ store := NewStore("")
+ finding := &Finding{
+ ID: "f7",
+ Key: "intermittent",
+ Title: "Intermittent Issue",
+ Severity: "warning",
+ }
+ findings := &stubFindingsStore{finding: finding}
+
+ callCount := 0
+ chatService := &stubChatService{
+ execute: func(cb StreamCallback) error {
+ callCount++
+ if callCount == 1 {
+ // First attempt: timeout
+ return context.DeadlineExceeded
+ }
+ // Second attempt: success
+ payload, _ := json.Marshal(map[string]string{
+ "text": "CANNOT_FIX: Transient issue already resolved",
+ })
+ cb(StreamEvent{Type: "content", Data: payload})
+ return nil
+ },
+ }
+
+ config := DefaultConfig()
+ orchestrator := NewOrchestrator(chatService, store, findings, nil, config)
+
+ // First attempt — times out
+ err := orchestrator.InvestigateFinding(context.Background(), finding, "full")
+ require.Error(t, err)
+ assert.Equal(t, string(OutcomeTimedOut), finding.InvestigationOutcome)
+ assert.Equal(t, 1, finding.InvestigationAttempts)
+
+ // Simulate cooldown elapsed — reset LastInvestigatedAt
+ past := time.Now().Add(-15 * time.Minute)
+ finding.LastInvestigatedAt = &past
+ finding.InvestigationStatus = "" // Clear so orchestrator accepts it
+
+ // Second attempt — succeeds
+ err = orchestrator.InvestigateFinding(context.Background(), finding, "full")
+ require.NoError(t, err)
+ assert.Equal(t, string(OutcomeCannotFix), finding.InvestigationOutcome)
+ assert.Equal(t, 2, finding.InvestigationAttempts)
+}
+
+// TestLifecycle_VerificationError tests verification returning an error.
+func TestLifecycle_VerificationError(t *testing.T) {
+ store := NewStore("")
+ findings := &stubFindingsStore{finding: &Finding{
+ ID: "f8",
+ Key: "net-issue",
+ Title: "Network Connectivity",
+ Severity: "warning",
+ }}
+
+ chatService := &stubChatService{
+ execute: func(cb StreamCallback) error {
+ payload, _ := json.Marshal(map[string]string{
+ "text": "PROPOSED_FIX: ip route flush cache\nTARGET_HOST: local",
+ })
+ cb(StreamEvent{Type: "content", Data: payload})
+ return nil
+ },
+ }
+
+ executor := &stubCommandExecutor{output: "ok", code: 0}
+ verifier := &stubFixVerifier{err: fmt.Errorf("verification patrol failed: circuit breaker open")}
+
+ config := DefaultConfig()
+ config.VerificationDelay = 0
+ orchestrator := NewOrchestrator(chatService, store, findings, nil, config)
+ orchestrator.SetCommandExecutor(executor)
+ orchestrator.SetFixVerifier(verifier)
+
+ err := orchestrator.InvestigateFinding(context.Background(), findings.finding, "full")
+ require.NoError(t, err)
+
+ inv := store.GetLatestByFinding("f8")
+ require.NotNil(t, inv)
+ assert.Equal(t, OutcomeFixVerificationFailed, inv.Outcome)
+ assert.Contains(t, inv.ProposedFix.Rationale, "Verification error")
+}
diff --git a/internal/ai/investigation/orchestrator.go b/internal/ai/investigation/orchestrator.go
index 184d7e57ce..5fbb974489 100644
--- a/internal/ai/investigation/orchestrator.go
+++ b/internal/ai/investigation/orchestrator.go
@@ -3,6 +3,7 @@ package investigation
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"strings"
"sync"
@@ -318,6 +319,10 @@ func (o *Orchestrator) InvestigateFinding(ctx context.Context, finding *Finding,
if err != nil {
// Mark as failed
o.store.Fail(investigation.ID, err.Error())
+ if isTimeoutError(err) {
+ o.store.SetOutcome(investigation.ID, OutcomeTimedOut)
+ finding.InvestigationOutcome = string(OutcomeTimedOut)
+ }
finding.InvestigationStatus = string(StatusFailed)
now := time.Now()
finding.LastInvestigatedAt = &now
@@ -855,6 +860,15 @@ func stripMarkdownCodeFences(s string) string {
return s
}
+// isTimeoutError returns true if the error is caused by a context deadline or timeout.
+func isTimeoutError(err error) bool {
+ if err == nil {
+ return false
+ }
+ return errors.Is(err, context.DeadlineExceeded) ||
+ strings.Contains(err.Error(), "context deadline exceeded")
+}
+
func (o *Orchestrator) updateFinding(finding *Finding) {
if o.findingsStore != nil {
o.findingsStore.Update(finding)
diff --git a/internal/ai/investigation/store.go b/internal/ai/investigation/store.go
index 43cdfe7c94..17032a7159 100644
--- a/internal/ai/investigation/store.go
+++ b/internal/ai/investigation/store.go
@@ -326,6 +326,21 @@ func (s *Store) Fail(id string, errorMsg string) bool {
return true
}
+// SetOutcome updates just the outcome of an investigation
+func (s *Store) SetOutcome(id string, outcome Outcome) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ session, exists := s.sessions[id]
+ if !exists {
+ return false
+ }
+
+ session.Outcome = outcome
+ s.scheduleSaveLocked()
+ return true
+}
+
// IncrementTurnCount increments the turn count for an investigation
func (s *Store) IncrementTurnCount(id string) int {
s.mu.Lock()
diff --git a/internal/ai/investigation/timeout_test.go b/internal/ai/investigation/timeout_test.go
new file mode 100644
index 0000000000..8adb63ecfd
--- /dev/null
+++ b/internal/ai/investigation/timeout_test.go
@@ -0,0 +1,66 @@
+package investigation
+
+import (
+ "context"
+ "fmt"
+ "testing"
+)
+
+func TestIsTimeoutError(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ expected bool
+ }{
+ {"nil error", nil, false},
+ {"bare deadline exceeded", context.DeadlineExceeded, true},
+ {"wrapped deadline exceeded", fmt.Errorf("failed: %w", context.DeadlineExceeded), true},
+ {"string contains deadline", fmt.Errorf("context deadline exceeded during stream"), true},
+ {"unrelated error", fmt.Errorf("connection refused"), false},
+ {"empty error", fmt.Errorf(""), false},
+ {"context canceled", context.Canceled, false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := isTimeoutError(tt.err)
+ if got != tt.expected {
+ t.Errorf("isTimeoutError(%v) = %v, want %v", tt.err, got, tt.expected)
+ }
+ })
+ }
+}
+
+func TestStore_SetOutcome(t *testing.T) {
+ store := NewStore("")
+
+ session := store.Create("finding-1", "session-1")
+
+ // Set outcome on existing session
+ ok := store.SetOutcome(session.ID, OutcomeTimedOut)
+ if !ok {
+ t.Fatalf("expected SetOutcome to succeed")
+ }
+
+ retrieved := store.Get(session.ID)
+ if retrieved.Outcome != OutcomeTimedOut {
+ t.Fatalf("expected outcome %s, got %s", OutcomeTimedOut, retrieved.Outcome)
+ }
+
+ // Set outcome on non-existent session
+ ok = store.SetOutcome("nonexistent", OutcomeTimedOut)
+ if ok {
+ t.Fatalf("expected SetOutcome to fail for nonexistent session")
+ }
+}
+
+func TestDefaultConfig_TimeoutCooldown(t *testing.T) {
+ cfg := DefaultConfig()
+ if cfg.TimeoutCooldownDuration == 0 {
+ t.Fatalf("expected non-zero TimeoutCooldownDuration")
+ }
+ if cfg.TimeoutCooldownDuration >= cfg.CooldownDuration {
+ t.Fatalf("expected TimeoutCooldownDuration (%v) < CooldownDuration (%v)",
+ cfg.TimeoutCooldownDuration, cfg.CooldownDuration)
+ }
+}
diff --git a/internal/ai/investigation/types.go b/internal/ai/investigation/types.go
index a6cab7727d..73cd61503c 100644
--- a/internal/ai/investigation/types.go
+++ b/internal/ai/investigation/types.go
@@ -49,6 +49,7 @@ const (
OutcomeFixVerificationFailed Outcome = "fix_verification_failed" // Fix ran but issue persists
OutcomeNeedsAttention Outcome = "needs_attention"
OutcomeCannotFix Outcome = "cannot_fix"
+ OutcomeTimedOut Outcome = "timed_out" // Transient timeout, will retry sooner
)
// Fix represents a proposed remediation action
@@ -68,23 +69,25 @@ var DestructivePatterns = safety.DestructivePatterns
// InvestigationConfig holds configuration for investigations
type InvestigationConfig struct {
- MaxTurns int // Maximum agentic turns per investigation
- Timeout time.Duration // Maximum duration per investigation
- MaxConcurrent int // Maximum concurrent investigations
- MaxAttemptsPerFinding int // Maximum investigation attempts per finding
- CooldownDuration time.Duration // Cooldown before re-investigating
- VerificationDelay time.Duration // Wait before verifying fix (default: 30s)
+ MaxTurns int // Maximum agentic turns per investigation
+ Timeout time.Duration // Maximum duration per investigation
+ MaxConcurrent int // Maximum concurrent investigations
+ MaxAttemptsPerFinding int // Maximum investigation attempts per finding
+ CooldownDuration time.Duration // Cooldown before re-investigating
+ TimeoutCooldownDuration time.Duration // Shorter cooldown for timeout failures (default: 10min)
+ VerificationDelay time.Duration // Wait before verifying fix (default: 30s)
}
// DefaultConfig returns the default investigation configuration
func DefaultConfig() InvestigationConfig {
return InvestigationConfig{
- MaxTurns: 15,
- Timeout: 5 * time.Minute,
- MaxConcurrent: 3,
- MaxAttemptsPerFinding: 3,
- CooldownDuration: 1 * time.Hour,
- VerificationDelay: 30 * time.Second,
+ MaxTurns: 15,
+ Timeout: 10 * time.Minute,
+ MaxConcurrent: 3,
+ MaxAttemptsPerFinding: 3,
+ CooldownDuration: 1 * time.Hour,
+ TimeoutCooldownDuration: 10 * time.Minute,
+ VerificationDelay: 30 * time.Second,
}
}
diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.go
index 9ceb2d2acf..71b5fe7d8f 100644
--- a/internal/ai/patrol_findings.go
+++ b/internal/ai/patrol_findings.go
@@ -814,6 +814,31 @@ func normalizeFindingKey(key string) string {
return strings.Trim(b.String(), "-")
}
+// retryTimedOutInvestigations re-triggers investigation for findings that failed due to timeout.
+// Called at the end of each patrol run to give timed-out investigations another chance
+// without waiting for the full 1-hour cooldown.
+func (p *PatrolService) retryTimedOutInvestigations() {
+ if p.findings == nil {
+ return
+ }
+ active := p.findings.GetActive(FindingSeverityWarning)
+ retried := 0
+ for _, f := range active {
+ if f.InvestigationStatus != string(InvestigationStatusFailed) {
+ continue
+ }
+ if f.InvestigationOutcome != string(InvestigationOutcomeTimedOut) {
+ continue
+ }
+ p.MaybeInvestigateFinding(f)
+ retried++
+ }
+ if retried > 0 {
+ log.Info().Int("retried", retried).
+ Msg("AI Patrol: Retried timed-out investigations")
+ }
+}
+
// MaybeInvestigateFinding checks if a finding should be investigated and triggers investigation if so
// This is called both during scheduled patrol runs and when alert-triggered findings are created
func (p *PatrolService) MaybeInvestigateFinding(f *Finding) {
diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.go
index 067afa70a4..e83e174f5c 100644
--- a/internal/ai/patrol_run.go
+++ b/internal/ai/patrol_run.go
@@ -358,6 +358,9 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
log.Debug().Int("cleaned", cleaned).Msg("AI Patrol: Cleaned up old findings")
}
+ // Retry investigations that failed due to timeout (shorter cooldown than permanent failures)
+ p.retryTimedOutInvestigations()
+
// AI-based alert review: check active alerts against current state and auto-resolve fixed issues
// Pass llmAllowed so it knows whether AI calls are allowed.
alertsResolved := p.reviewAndResolveAlerts(ctx, state, llmAllowed)