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
Bound patrol-main session at 200 messages to stop unbounded disk growth
rcourtman9f43a22fb122
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 3c450e90e0..ef42e0c536 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -108,7 +108,7 @@ runtime cost control, and shared AI transport surfaces.## Completion Obligations-1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as DeepSeek `tool_choice` coercion, runtime-failure classification splits (for example separating forced tool selection rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load, the auto-trigger contract on `HandleUpdateAISettings` where the save handler runs `TriggerPatrolPreflightAsync` only when the change actually moved Patrol transport (model swap, provider key for that model changed, or assistant just enabled with a Patrol model) so routine settings saves do not burn provider tokens, the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified", the readiness-integration contract where the `tools` check in the Patrol readiness payload consults the cached preflight and surfaces the classified evidence (success, soft warning, or failure with classified summary plus "last preflight <age>") for the configured provider+model when available (falling back to the static `PatrolToolReadinessForModel` classifier only when the cache is empty or holds a result for a different model), the stateless-Patrol-input contract where `ExecutePatrolStream` must pass only the current run's user prompt into the agentic loop rather than reloading the persisted `patrol-main` session history (so a prior run that ended with orphan `tool_calls` cannot poison every subsequent run with malformed conversation structure), and the deterministic-resolve-gate contract where the `patrol_resolve_finding` tool adapter rejects LLM-driven resolves of event/persistent category findings (`backup`, `reliability`, `security`, `general`) when a deterministic verifier exists for the finding's key and that verifier still detects the failure signal — preventing the LLM from optimistically resolving a finding its current investigation simply didn't re-surface, which was the source of the "Backup failed" flap (detected → auto-resolved → re-detected ten times in a day before this gate), the assessment-recovery contract where the overall-health "Recent Patrol errors" coverage factor in `summarizeRecentPatrolCoverage` suppresses the score penalty once three consecutive trailing successful full Patrol runs exist at the most-recent end of the recent-runs window — so the grade reflects current reality after a Patrol-affecting bug is fixed rather than dragging stale failures forward for the ~9 hours it takes scheduled runs to age them out of the trailing-10 ratio, and the orphan-tool-call-repair contract where `convertToProviderMessages` injects synthetic is_error tool result messages for any `tool_call_id` in an assistant message that has no matching downstream tool result, so a chat session that ended mid-tool-call (network drop, ctx timeout, browser crash) cannot poison its next message with the structural-violation error the provider rejects — the synthetic content is marked is_error=true and explains the interruption so the model can retry the call or proceed without the data+1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as DeepSeek `tool_choice` coercion, runtime-failure classification splits (for example separating forced tool selection rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load, the auto-trigger contract on `HandleUpdateAISettings` where the save handler runs `TriggerPatrolPreflightAsync` only when the change actually moved Patrol transport (model swap, provider key for that model changed, or assistant just enabled with a Patrol model) so routine settings saves do not burn provider tokens, the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified", the readiness-integration contract where the `tools` check in the Patrol readiness payload consults the cached preflight and surfaces the classified evidence (success, soft warning, or failure with classified summary plus "last preflight <age>") for the configured provider+model when available (falling back to the static `PatrolToolReadinessForModel` classifier only when the cache is empty or holds a result for a different model), the stateless-Patrol-input contract where `ExecutePatrolStream` must pass only the current run's user prompt into the agentic loop rather than reloading the persisted `patrol-main` session history (so a prior run that ended with orphan `tool_calls` cannot poison every subsequent run with malformed conversation structure), and the deterministic-resolve-gate contract where the `patrol_resolve_finding` tool adapter rejects LLM-driven resolves of event/persistent category findings (`backup`, `reliability`, `security`, `general`) when a deterministic verifier exists for the finding's key and that verifier still detects the failure signal — preventing the LLM from optimistically resolving a finding its current investigation simply didn't re-surface, which was the source of the "Backup failed" flap (detected → auto-resolved → re-detected ten times in a day before this gate), the assessment-recovery contract where the overall-health "Recent Patrol errors" coverage factor in `summarizeRecentPatrolCoverage` suppresses the score penalty once three consecutive trailing successful full Patrol runs exist at the most-recent end of the recent-runs window — so the grade reflects current reality after a Patrol-affecting bug is fixed rather than dragging stale failures forward for the ~9 hours it takes scheduled runs to age them out of the trailing-10 ratio, the orphan-tool-call-repair contract where `convertToProviderMessages` injects synthetic is_error tool result messages for any `tool_call_id` in an assistant message that has no matching downstream tool result, so a chat session that ended mid-tool-call (network drop, ctx timeout, browser crash) cannot poison its next message with the structural-violation error the provider rejects — the synthetic content is marked is_error=true and explains the interruption so the model can retry the call or proceed without the data, and the patrol-session-bound contract where `ExecutePatrolStream` calls `SessionStore.TrimMessages` after persisting each run's messages to cap the patrol-main session at 200 messages (roughly two recent runs' worth) — without the bound the file grew unbounded at every scheduled run, reaching 16 MB and 3,593 messages within a month and making every `AddMessage` rewrite linearly more expensive; the canonical Patrol forensic log is the `PatrolRunRecord` history surfaced at `/api/ai/patrol/runs`, not the chat-session-shaped file2. Keep AI runtime and shared API proof routing aligned in `registry.json`3. Preserve explicit coverage for chat, Patrol, remediation, and cost-control behavior when AI runtime changesPatrol runtime failures are part of that runtime contract: provider, model,diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex e794924bf0..88e166cd74 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -2029,6 +2029,20 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca}}+ // Patrol-main is reused across every scheduled run (the+ // stateless-input contract means we never load it back into the+ // agentic loop, but we still write to it for the Pulse Assistant+ // sidebar's forensic view). Without a cap, the file grew to 16 MB /+ // 3,593 messages within a month and every AddMessage rewrote the+ // whole file to disk. Cap at the most recent ~two Patrol runs'+ // worth of messages — enough for the sidebar to show recent+ // activity, far short of unbounded growth. The canonical forensic+ // log is the PatrolRunRecord history, not this session.+ const maxPatrolSessionMessages = 200+ if err := sessions.TrimMessages(session.ID, maxPatrolSessionMessages); err != nil {+ log.Warn().Err(err).Msg("failed to trim patrol session messages")+ }+// Collect content from result messagesvar contentBuilder strings.Builderfor _, msg := range resultMessages {diff --git a/internal/ai/chat/session.go b/internal/ai/chat/session.goindex 57d0b7e9af..1f0b2a7589 100644--- a/internal/ai/chat/session.go+++ b/internal/ai/chat/session.go@@ -805,6 +805,39 @@ func (s *SessionStore) GetMessages(id string) ([]Message, error) {return data.Messages, nil}+// TrimMessages keeps at most keepMostRecent messages in the session,+// dropping older ones. Used for sessions like patrol-main that are+// reused indefinitely across scheduled runs and would otherwise grow+// unbounded — at the default 3-hour Patrol cadence with ~20 messages+// per run, the file grew to 16 MB / 3,593 messages before this bound+// existed, and every AddMessage was rewriting the whole file to disk.+//+// keepMostRecent <= 0 is treated as a no-op so callers can disable the+// bound by passing 0 when they want full retention (e.g. user-driven+// chat sessions where conversation history is the product).+func (s *SessionStore) TrimMessages(id string, keepMostRecent int) error {+ if keepMostRecent <= 0 {+ return nil+ }++ s.mu.Lock()+ defer s.mu.Unlock()++ data, err := s.readSession(id)+ if err != nil {+ return err+ }+ if len(data.Messages) <= keepMostRecent {+ return nil+ }+ start := len(data.Messages) - keepMostRecent+ trimmed := make([]Message, keepMostRecent)+ copy(trimmed, data.Messages[start:])+ data.Messages = trimmed+ data.UpdatedAt = time.Now()+ return s.writeSession(*data)+}+// AddMessage adds a message to a sessionfunc (s *SessionStore) AddMessage(id string, msg Message) error {s.mu.Lock()diff --git a/internal/ai/chat/session_test.go b/internal/ai/chat/session_test.goindex 59507203f2..f778b559f3 100644--- a/internal/ai/chat/session_test.go+++ b/internal/ai/chat/session_test.go@@ -2,6 +2,7 @@ package chatimport ("encoding/json"+ "fmt""os""path/filepath""strings"@@ -103,6 +104,68 @@ func TestSessionStore(t *testing.T) {assert.NoError(t, err)assert.Equal(t, sessionFixed.ID, retrieved.ID)})++ t.Run("TrimMessages keeps the most recent N", func(t *testing.T) {+ // Patrol-main session was reused across every scheduled run+ // and grew to 16 MB / 3,593 messages within a month. Without+ // a per-session bound, the file rewrites on every AddMessage+ // got linearly more expensive. TrimMessages caps the slice to+ // the most recent N messages so the on-disk footprint stays+ // bounded and the I/O cost per write stays flat.+ session, err := store.EnsureSession("trim-test")+ require.NoError(t, err)+ for i := 0; i < 50; i++ {+ require.NoError(t, store.AddMessage(session.ID, Message{+ Role: "user",+ Content: fmt.Sprintf("message-%d", i),+ }))+ }++ // Trim to the last 10 — must drop messages 0..39 and keep 40..49.+ require.NoError(t, store.TrimMessages(session.ID, 10))+ got, err := store.GetMessages(session.ID)+ require.NoError(t, err)+ require.Len(t, got, 10)+ assert.Equal(t, "message-40", got[0].Content)+ assert.Equal(t, "message-49", got[9].Content)+ })++ t.Run("TrimMessages is a no-op below threshold", func(t *testing.T) {+ // When the session already has fewer messages than the cap,+ // no rewrite should happen and no messages should be lost.+ session, err := store.EnsureSession("trim-noop")+ require.NoError(t, err)+ for i := 0; i < 5; i++ {+ require.NoError(t, store.AddMessage(session.ID, Message{+ Role: "user",+ Content: fmt.Sprintf("msg-%d", i),+ }))+ }+ require.NoError(t, store.TrimMessages(session.ID, 200))+ got, err := store.GetMessages(session.ID)+ require.NoError(t, err)+ require.Len(t, got, 5)+ })++ t.Run("TrimMessages with non-positive keep is a no-op", func(t *testing.T) {+ // keepMostRecent <= 0 must not silently truncate the entire+ // session — that would be a footgun. Callers can disable the+ // cap explicitly by passing 0 for user-driven chat sessions+ // where full history is the product.+ session, err := store.EnsureSession("trim-zero")+ require.NoError(t, err)+ for i := 0; i < 3; i++ {+ require.NoError(t, store.AddMessage(session.ID, Message{+ Role: "user",+ Content: fmt.Sprintf("zero-%d", i),+ }))+ }+ require.NoError(t, store.TrimMessages(session.ID, 0))+ require.NoError(t, store.TrimMessages(session.ID, -5))+ got, err := store.GetMessages(session.ID)+ require.NoError(t, err)+ require.Len(t, got, 3)+ })}func TestSessionStoreMigratesLegacySessionFileOnWrite(t *testing.T) {