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.

Repair orphan tool_calls in convertToProviderMessages

rcourtman99c499ade7cf
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 9c18ab940b..897120ae73 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), and 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
+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
2. 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 changes
Patrol runtime failures are part of that runtime contract: provider, model,
diff --git a/internal/ai/chat/agentic_context.go b/internal/ai/chat/agentic_context.go
index 9ef45f44fb..e09f27aabc 100644
--- a/internal/ai/chat/agentic_context.go
+++ b/internal/ai/chat/agentic_context.go
@@ -69,7 +69,9 @@ func truncateToolResultForModel(text string) string {
return fmt.Sprintf("%s\n\n---\n[TRUNCATED: %d characters cut. The result was too large. If you need specific details that may have been cut, make a more targeted query (e.g., filter by specific resource or type).]", truncated, truncatedChars)
}
-// convertToProviderMessages converts our messages to provider format.
+// convertToProviderMessages converts our messages to provider format
+// and applies a structural-repair pass for orphan tool_calls. See
+// repairOrphanToolCalls for why this guard exists.
func convertToProviderMessages(messages []Message) []providers.Message {
result := make([]providers.Message, 0, len(messages))
@@ -102,7 +104,101 @@ func convertToProviderMessages(messages []Message) []providers.Message {
result = append(result, pm)
}
- return result
+ return repairOrphanToolCalls(result)
+}
+
+// orphanToolCallRepairMessage is the synthetic tool result content used
+// to fill missing tool_call_id slots in a loaded conversation. Distinct
+// enough that the model recognizes it as a structural placeholder and
+// either retries the call or proceeds without that data.
+const orphanToolCallRepairMessage = "Pulse did not capture a response for this tool call — the previous run was interrupted before this tool completed. Treat the result as missing; either retry the same tool call now or proceed without this data."
+
+// repairOrphanToolCalls scans provider messages for assistant messages
+// whose tool_calls do not have matching tool result messages downstream
+// and inserts synthetic error tool results to satisfy the provider's
+// structural-validity check.
+//
+// Background: providers like DeepSeek and OpenAI require that an
+// assistant message with N tool_calls be followed by N tool messages
+// each carrying a matching tool_call_id. When a multi-turn agentic run
+// ends mid-execution — network drop, ctx timeout, browser crash, an
+// uncaught panic, anything — the persisted session can contain
+// "assistant: [tool_calls A, B, C]" followed by only "tool: A" and "tool:
+// B." The next request that includes this history is rejected with
+//
+// An assistant message with 'tool_calls' must be followed by tool
+// messages responding to each 'tool_call_id'.
+//
+// Patrol used to flap on this for 33 days because patrol-main sessions
+// were reused and any prior interruption poisoned every subsequent run.
+// The Patrol fix made those runs stateless (no session history loaded),
+// but Assistant chat sessions are inherently multi-turn and must keep
+// their history. This pass is the safety net for every other surface:
+// any conversation that crosses convertToProviderMessages is repaired
+// to a structurally-valid shape before it reaches the provider.
+//
+// The repair preserves continuity (assistant message stays) and tells
+// the model the missing call was interrupted (is_error=true with an
+// explanation), so the model can retry the same call or proceed.
+func repairOrphanToolCalls(messages []providers.Message) []providers.Message {
+ fulfilled := make(map[string]bool)
+ for _, m := range messages {
+ if m.ToolResult != nil && m.ToolResult.ToolUseID != "" {
+ fulfilled[m.ToolResult.ToolUseID] = true
+ }
+ }
+
+ // Walk in order. After each assistant message with tool_calls,
+ // inject synthetic results for any tool_call_ids that don't already
+ // have a fulfilled result somewhere in the slice.
+ repaired := make([]providers.Message, 0, len(messages))
+ repaired = append(repaired, messages...)
+ for i := 0; i < len(repaired); i++ {
+ m := repaired[i]
+ if len(m.ToolCalls) == 0 {
+ continue
+ }
+ // Collect ids missing a result. Order preserved to match the
+ // assistant message's tool_calls order, which some providers
+ // rely on.
+ var missing []string
+ for _, tc := range m.ToolCalls {
+ if tc.ID == "" {
+ continue
+ }
+ if fulfilled[tc.ID] {
+ continue
+ }
+ missing = append(missing, tc.ID)
+ fulfilled[tc.ID] = true
+ }
+ if len(missing) == 0 {
+ continue
+ }
+ // Insert synthetic results immediately after the assistant
+ // message, in order. This keeps the structural invariant the
+ // provider validates: every tool_call_id has a downstream tool
+ // message.
+ inject := make([]providers.Message, 0, len(missing))
+ for _, id := range missing {
+ inject = append(inject, providers.Message{
+ Role: "user",
+ ToolResult: &providers.ToolResult{
+ ToolUseID: id,
+ Content: orphanToolCallRepairMessage,
+ IsError: true,
+ },
+ })
+ }
+ // Splice the synthetic messages in at position i+1.
+ tail := append([]providers.Message{}, repaired[i+1:]...)
+ repaired = append(repaired[:i+1], inject...)
+ repaired = append(repaired, tail...)
+ // Advance i past the injected messages so the next iteration
+ // resumes at the originally-following message.
+ i += len(inject)
+ }
+ return repaired
}
// compactOldToolResults replaces full tool result content with short summaries
diff --git a/internal/ai/chat/agentic_format_test.go b/internal/ai/chat/agentic_format_test.go
index 3bae03afdd..d3a904917e 100644
--- a/internal/ai/chat/agentic_format_test.go
+++ b/internal/ai/chat/agentic_format_test.go
@@ -23,6 +23,132 @@ func TestFormatKeyParams_PriorityAndFallback(t *testing.T) {
}
}
+func TestConvertToProviderMessages_RepairsOrphanToolCallsInLoadedSession(t *testing.T) {
+ // Real production trigger: the patrol-main session accumulated
+ // "assistant: [tool_calls A, B, C, D] / tool: A / tool: B / tool: C /
+ // tool: D" turns interleaved with user prompts. When a prior run was
+ // interrupted (the malformed-history bug for Patrol, or a chat session
+ // ending mid-tool-call for Assistant), some result messages were never
+ // captured. The next request that loads this history is rejected by
+ // the provider as a structural violation. Without the repair pass,
+ // that's the exact "must be followed by tool messages responding to
+ // each tool_call_id" error that flapped Patrol for 33 days.
+ //
+ // The repair pass must inject synthetic error tool results for the
+ // missing call ids so the conversation is structurally valid before
+ // it reaches the provider. The synthetic result must be marked as an
+ // error and tell the model the call was interrupted so it can retry
+ // or proceed without that data.
+ messages := []Message{
+ {Role: "user", Content: "investigate infrastructure"},
+ {
+ Role: "assistant",
+ ToolCalls: []ToolCall{
+ {ID: "call-A", Name: "pulse_storage"},
+ {ID: "call-B", Name: "pulse_backups"},
+ {ID: "call-C", Name: "pulse_alerts"},
+ },
+ },
+ // Only call-A has a tool result. B and C are orphans.
+ {Role: "user", ToolResult: &ToolResult{ToolUseID: "call-A", Content: "ok"}},
+ {Role: "user", Content: "next question"},
+ }
+
+ converted := convertToProviderMessages(messages)
+
+ // The synthetic results must appear immediately after the assistant
+ // message so the structural invariant holds: every tool_call_id has
+ // a matching downstream tool message before the next user turn.
+ if len(converted) != 6 {
+ t.Fatalf("expected 6 messages after repair (original 4 + 2 synthetic), got %d:\n%+v", len(converted), converted)
+ }
+
+ assistantIdx := -1
+ for i, m := range converted {
+ if len(m.ToolCalls) > 0 {
+ assistantIdx = i
+ break
+ }
+ }
+ if assistantIdx == -1 {
+ t.Fatalf("expected to find assistant message with tool_calls")
+ }
+
+ // Collect tool_call_ids present in tool result messages AFTER the
+ // assistant message, in order.
+ var fulfilledAfter []string
+ for _, m := range converted[assistantIdx+1:] {
+ if m.ToolResult != nil {
+ fulfilledAfter = append(fulfilledAfter, m.ToolResult.ToolUseID)
+ }
+ }
+ wantInOrder := []string{"call-A", "call-B", "call-C"}
+ // Real tool result + 2 synthetic. The real one (call-A) is already
+ // in the conversation at its original position; call-B and call-C
+ // are the injected ones, immediately following the assistant turn.
+ // Just check that all three IDs are present.
+ have := map[string]bool{}
+ for _, id := range fulfilledAfter {
+ have[id] = true
+ }
+ for _, want := range wantInOrder {
+ if !have[want] {
+ t.Fatalf("expected tool_call_id %q to have a downstream tool result, got %+v", want, fulfilledAfter)
+ }
+ }
+
+ // The synthetic results must be marked as errors so the model
+ // knows the data is missing rather than treating empty content as
+ // a successful empty response.
+ syntheticCount := 0
+ for _, m := range converted {
+ if m.ToolResult == nil {
+ continue
+ }
+ if m.ToolResult.ToolUseID == "call-A" {
+ continue // real result, not synthetic
+ }
+ if !m.ToolResult.IsError {
+ t.Fatalf("expected synthetic tool result %q to be marked is_error=true, got %+v", m.ToolResult.ToolUseID, m.ToolResult)
+ }
+ if !strings.Contains(m.ToolResult.Content, "interrupted") {
+ t.Fatalf("expected synthetic content to explain the interruption, got %q", m.ToolResult.Content)
+ }
+ syntheticCount++
+ }
+ if syntheticCount != 2 {
+ t.Fatalf("expected exactly 2 synthetic results, got %d", syntheticCount)
+ }
+}
+
+func TestConvertToProviderMessages_NoOpWhenAllToolCallsHaveResults(t *testing.T) {
+ // When every tool_call_id is already matched by a downstream tool
+ // message, the repair pass must be a no-op — no synthetic messages
+ // injected, no reordering, no leaked is_error tags.
+ messages := []Message{
+ {Role: "user", Content: "ok"},
+ {
+ Role: "assistant",
+ ToolCalls: []ToolCall{
+ {ID: "x", Name: "pulse_storage"},
+ {ID: "y", Name: "pulse_alerts"},
+ },
+ },
+ {Role: "user", ToolResult: &ToolResult{ToolUseID: "x", Content: "ok"}},
+ {Role: "user", ToolResult: &ToolResult{ToolUseID: "y", Content: "ok"}},
+ }
+
+ converted := convertToProviderMessages(messages)
+ if len(converted) != len(messages) {
+ t.Fatalf("expected no synthetic messages, got %d vs %d", len(converted), len(messages))
+ }
+ for _, m := range converted {
+ if m.ToolResult != nil && m.ToolResult.IsError {
+ t.Fatalf("expected no is_error results, got %+v", m.ToolResult)
+ }
+ }
+}
+
func TestConvertToProviderMessages_TruncatesToolResult(t *testing.T) {
longContent := strings.Repeat("a", MaxToolResultCharsLimit+1)