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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
fix(patrol): improve stream subscriber safety and detect stuck runs
rcourtmane4f488991566
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.goindex 599b42c908..a83f38d038 100644--- a/internal/ai/patrol.go+++ b/internal/ai/patrol.go@@ -41,6 +41,7 @@ import ("context""strings""sync"+ "sync/atomic""time""github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline"@@ -182,6 +183,12 @@ type InvestigationOrchestrator interface {Shutdown(ctx context.Context) error}+// InvestigationStoreMaintainer is an optional interface for orchestrators that+// expose their investigation store for periodic maintenance.+type InvestigationStoreMaintainer interface {+ CleanupInvestigationStore(maxAge time.Duration, maxSessions int)+}+// InvestigationFinding is the finding type expected by the orchestratortype InvestigationFinding struct {ID string@@ -285,6 +292,7 @@ type PatrolService struct {// Runtime staterunning boolrunInProgress bool+ runStartedAt time.TimestopCh chan struct{}configChanged chan struct{} // Signal when config changes to reset tickerlastPatrol time.Time@@ -302,7 +310,7 @@ type PatrolService struct {// Live streaming supportstreamMu sync.RWMutex- streamSubscribers map[chan PatrolStreamEvent]struct{}+ streamSubscribers map[chan PatrolStreamEvent]*streamSubscribercurrentOutput strings.Builder // Buffer for current streaming outputstreamPhase string // "idle", "analyzing", "complete"}@@ -319,6 +327,13 @@ type ToolCallRecord struct {Duration int64 `json:"duration_ms"`}+// streamSubscriber wraps a stream channel with an atomic close flag+// to prevent double-close panics when both broadcast and unsubscribe race.+type streamSubscriber struct {+ ch chan PatrolStreamEvent+ closed atomic.Bool+}+// PatrolStreamEvent represents a streaming update from the patroltype PatrolStreamEvent struct {Type string `json:"type"` // "start", "content", "phase", "complete", "error", "tool_start", "tool_end"@@ -344,7 +359,7 @@ func NewPatrolService(aiService *Service, stateProvider StateProvider) *PatrolSethresholds: DefaultPatrolThresholds(),stopCh: make(chan struct{}),runHistoryStore: NewPatrolRunHistoryStore(MaxPatrolRunHistory),- streamSubscribers: make(map[chan PatrolStreamEvent]struct{}),+ streamSubscribers: make(map[chan PatrolStreamEvent]*streamSubscriber),streamPhase: "idle",adHocTrigger: make(chan *alerts.Alert, 10), // Buffer triggers}diff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.goindex 6a7b0ce4d2..d199fabf17 100644--- a/internal/ai/patrol_ai.go+++ b/internal/ai/patrol_ai.go@@ -40,16 +40,42 @@ const (patrolQuickMaxTurns = 30)-// cleanThinkingTokens removes model-specific thinking markers from AI responses.+// CleanThinkingTokens removes model-specific thinking markers from AI responses.// Different AI models use different markers for their internal reasoning:// - DeepSeek: <|end▁of▁thinking|> or similar unicode variants+// - DeepSeek: <|DSML|...> internal function call format (hallucinated tool calls)// - Generic: <think>...</think>, <thought>...</thought>-// - Reasoning: <|reasoning|>...<|/reasoning|>-func cleanThinkingTokens(content string) string {+// - Reasoning: <|reasoning|>...</|/reasoning|>+//+// This function is exported so it can be used by both patrol and chat responses.+func CleanThinkingTokens(content string) string {if content == "" {return content}+ // Phase 0: Remove DeepSeek internal function call format leakage.+ // When DeepSeek doesn't properly use the function calling API, it may output+ // its internal markup like <|DSML|function_calls>, <|DSML|invoke>, etc.+ // These patterns can appear with Unicode pipe (|) or ASCII pipe (|).+ deepseekFunctionMarkers := []string{+ "<|DSML|", // Unicode pipe variant (opening)+ "</|DSML|", // Unicode pipe variant (closing)+ "<|DSML|", // ASCII pipe variant (opening)+ "</|DSML|", // ASCII pipe variant (closing)+ "<|/DSML|", // Alternative Unicode closing+ "<|/DSML|", // Alternative ASCII closing+ }+ for _, marker := range deepseekFunctionMarkers {+ if strings.Contains(content, marker) {+ // Find the start of the block and remove everything from there to the end+ // DeepSeek function call blocks typically appear at the end of responses+ idx := strings.Index(content, marker)+ if idx >= 0 {+ content = strings.TrimSpace(content[:idx])+ }+ }+ }+// Phase 1: Remove entire block-level tags (opening + content + closing).// Case-insensitive matching via lowercased copy.type blockTag struct {@@ -410,7 +436,7 @@ func (p *PatrolService) runAIAnalysis(ctx context.Context, state models.StateSnaoutputTokens = chatResp.OutputTokens// Clean thinking tokens- finalContent = cleanThinkingTokens(finalContent)+ finalContent = CleanThinkingTokens(finalContent)log.Debug().Int("input_tokens", inputTokens).diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.goindex 4e519599d9..a069da39e9 100644--- a/internal/ai/patrol_run.go+++ b/internal/ai/patrol_run.go@@ -1052,9 +1052,10 @@ func (p *PatrolService) GetStatus() PatrolStatus {// SubscribeToStream returns a channel that will receive streaming patrol eventsfunc (p *PatrolService) SubscribeToStream() chan PatrolStreamEvent {ch := make(chan PatrolStreamEvent, 100) // Buffered to prevent blocking+ sub := &streamSubscriber{ch: ch}p.streamMu.Lock()- p.streamSubscribers[ch] = struct{}{}+ p.streamSubscribers[ch] = sub// Send current state to new subscriberif p.streamPhase != "idle" {ch <- PatrolStreamEvent{@@ -1071,18 +1072,13 @@ func (p *PatrolService) SubscribeToStream() chan PatrolStreamEvent {// UnsubscribeFromStream removes a subscriberfunc (p *PatrolService) UnsubscribeFromStream(ch chan PatrolStreamEvent) {p.streamMu.Lock()- _, exists := p.streamSubscribers[ch]+ sub, exists := p.streamSubscribers[ch]delete(p.streamSubscribers, ch)p.streamMu.Unlock()- // Only close if we actually removed it from the map- // (broadcast may have already removed and closed it)- if exists {- defer func() {- if r := recover(); r != nil {- log.Error().Interface("error", r).Msg("panic recovered in UnsubscribeFromStream")- }- }()+ // Use atomic CAS to ensure exactly one goroutine closes the channel,+ // even if broadcast and unsubscribe race.+ if exists && sub.closed.CompareAndSwap(false, true) {close(ch)}}@@ -1104,18 +1100,13 @@ func (p *PatrolService) broadcast(event PatrolStreamEvent) {}}- // Clean up stale subscribers+ // Clean up stale subscribers using atomic CAS for safe closefor _, ch := range staleChannels {+ sub := p.streamSubscribers[ch]delete(p.streamSubscribers, ch)- // Close in a goroutine to avoid blocking if receiver is stuck- go func(c chan PatrolStreamEvent) {- defer func() {- if r := recover(); r != nil {- log.Error().Interface("error", r).Msg("panic recovered in broadcast channel close")- }- }()- close(c)- }(ch)+ if sub != nil && sub.closed.CompareAndSwap(false, true) {+ close(ch)+ }}}@@ -1482,16 +1473,29 @@ func (p *PatrolService) TriggerPatrolForAlert(alert *alerts.Alert) {func (p *PatrolService) tryStartRun(kind string) bool {p.mu.Lock()if p.runInProgress {- p.mu.Unlock()- if kind == "scoped" {- GetPatrolMetrics().RecordScopedDropped()- log.Warn().Str("kind", kind).Msg("AI Patrol: Run already in progress, dropping scoped patrol")+ // Detect stuck runs: if the current run has been going for >20 minutes,+ // force-clear the flag so a new run can proceed.+ if !p.runStartedAt.IsZero() && time.Since(p.runStartedAt) > 20*time.Minute {+ log.Warn().+ Str("kind", kind).+ Time("started_at", p.runStartedAt).+ Dur("elapsed", time.Since(p.runStartedAt)).+ Msg("AI Patrol: Previous run appears stuck (>20min), force-clearing runInProgress")+ p.runInProgress = false+ // Fall through to start new run} else {- log.Debug().Str("kind", kind).Msg("AI Patrol: Run already in progress, skipping")+ p.mu.Unlock()+ if kind == "scoped" {+ GetPatrolMetrics().RecordScopedDropped()+ log.Warn().Str("kind", kind).Msg("AI Patrol: Run already in progress, dropping scoped patrol")+ } else {+ log.Debug().Str("kind", kind).Msg("AI Patrol: Run already in progress, skipping")+ }+ return false}- return false}p.runInProgress = true+ p.runStartedAt = time.Now()p.mu.Unlock()return true}@@ -1499,7 +1503,13 @@ func (p *PatrolService) tryStartRun(kind string) bool {func (p *PatrolService) endRun() {p.mu.Lock()p.runInProgress = false+ orch := p.investigationOrchestratorp.mu.Unlock()++ // Periodic investigation store maintenance after each run+ if maintainer, ok := orch.(InvestigationStoreMaintainer); ok {+ maintainer.CleanupInvestigationStore(24*time.Hour, 1000)+ }}// runTargetedPatrol executes a focused patrol for a specific alertdiff --git a/internal/ai/remediation/engine.go b/internal/ai/remediation/engine.goindex 5f9b7ca586..ffd211d902 100644--- a/internal/ai/remediation/engine.go+++ b/internal/ai/remediation/engine.go@@ -9,6 +9,7 @@ import ("path/filepath""sort""sync"+ "sync/atomic""time""github.com/rcourtman/pulse-go-rewrite/internal/ai/safety"@@ -866,18 +867,18 @@ func (e *Engine) loadFromDisk() error {var planCounter, executionCounter, ruleCounter int64func generatePlanID() string {- planCounter++- return fmt.Sprintf("plan-%s-%d", time.Now().Format("20060102150405"), planCounter%1000)+ n := atomic.AddInt64(&planCounter, 1)+ return fmt.Sprintf("plan-%s-%d", time.Now().Format("20060102150405"), n%1000)}func generateExecutionID() string {- executionCounter++- return fmt.Sprintf("exec-%s-%d", time.Now().Format("20060102150405"), executionCounter%1000)+ n := atomic.AddInt64(&executionCounter, 1)+ return fmt.Sprintf("exec-%s-%d", time.Now().Format("20060102150405"), n%1000)}func generateRuleID() string {- ruleCounter++- return fmt.Sprintf("rule-%s-%d", time.Now().Format("20060102150405"), ruleCounter%1000)+ n := atomic.AddInt64(&ruleCounter, 1)+ return fmt.Sprintf("rule-%s-%d", time.Now().Format("20060102150405"), n%1000)}func containsIgnoreCase(s, substr string) bool {