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.

Bound Assistant fallback startup latency

rcourtman59e23a8030fd
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 6cf98b1d4c..903dcb6d28 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -343,7 +343,23 @@ runtime cost control, and shared AI transport surfaces.
fails before visible output. Once visible output has streamed, Pulse must
not silently switch providers for that turn; the error belongs to the visible
attempt and is surfaced through normal failed-turn recovery. Assistant
- completion events must carry the effective model route that actually
+ startup retry behavior must be route-aware: when another provider/model
+ attempt is already queued for the same user turn, non-final attempts must
+ fast-fail before visible output instead of spending hidden same-route retry
+ and backoff time. In that mode, provider-owned startup retries and the
+ agentic loop's retry of the same provider turn are disabled for the
+ non-final attempt, and the wait for the first visible provider event is
+ bounded so `provider_fallback` can reach the browser quickly. The final
+ queued attempt keeps normal provider retry behavior because there is no
+ later route to hand off to. The referenced OpenCode source at fetched
+ `origin/dev` commit `1025540fcc2a69609a0131a7168300205656d728` models retry
+ as explicit session activity through `RetryError` and `Retried` in
+ `packages/core/src/session/event.ts` and renders retry status in
+ `packages/ui/src/components/session-retry.tsx`; Pulse adapts that principle
+ by surfacing route changes through workflow/model rows and by yielding to
+ the next configured route quickly instead of hiding repeated startup
+ retries behind a static waiting label.
+ Assistant completion events must carry the effective model route that actually
completed the turn, and the drawer must update the in-flight transcript row
when `provider_fallback` names the next route so message labels, cost
context, retry decisions, and model-route recovery do not continue to point
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index 7350462427..723190a778 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -7,6 +7,7 @@ import (
"runtime/debug"
"strings"
"sync"
+ "sync/atomic"
"time"
"github.com/google/uuid"
@@ -27,6 +28,8 @@ type parallelToolResult struct {
Err error
}
+const providerFallbackStartupTimeout = 4 * time.Second
+
func isRetryableProviderStreamError(err error) bool {
if err == nil {
return false
@@ -66,6 +69,15 @@ func isRetryableProviderStreamError(err error) bool {
return false
}
+func providerStreamEventShowsStartup(event providers.StreamEvent) bool {
+ switch strings.ToLower(strings.TrimSpace(event.Type)) {
+ case "content", "done", "thinking", "tool_progress", "tool_start":
+ return true
+ default:
+ return false
+ }
+}
+
type workflowStateOption func(*WorkflowStateData)
func withWorkflowRetry(nextAttempt, maxAttempts int, retryAfter time.Duration) workflowStateOption {
@@ -557,6 +569,10 @@ type AgenticLoop struct {
// configured provider before the browser sees a failed first attempt.
suppressProviderErrorEvents bool
+ // When true, this loop is running as one attempt in a service-owned provider
+ // fallback chain, so hidden startup retries should yield to the next route.
+ fastFailProviderStartup bool
+
// Query-only count/overview turns should not let a provider accidentally
// expand a topology request into the full infrastructure tree.
preferSummaryOnlyQueries bool
@@ -603,6 +619,12 @@ func (a *AgenticLoop) SetSuppressProviderErrorEvents(suppress bool) {
a.suppressProviderErrorEvents = suppress
}
+func (a *AgenticLoop) SetFastFailProviderStartup(enabled bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.fastFailProviderStartup = enabled
+}
+
func (a *AgenticLoop) SetPreferSummaryOnlyQueries(prefer bool) {
a.mu.Lock()
defer a.mu.Unlock()
@@ -700,6 +722,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
modelName := a.modelName
requestSanitizer := a.requestSanitizer
preferSummaryOnlyQueries := a.preferSummaryOnlyQueries
+ fastFailProviderStartup := a.fastFailProviderStartup
a.mu.Unlock()
// Record telemetry for loop iteration
@@ -732,6 +755,9 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
Tools: tools,
ExecutionID: a.executionID,
}
+ if fastFailProviderStartup {
+ req.ProviderStartupMode = providers.ProviderStartupFastFailBeforeVisibleOutput
+ }
// Tool selection is model-owned. Pulse normally exposes the governed tool
// manifest unchanged. When a run must stop for safety or budget reasons,
@@ -886,14 +912,37 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
req = requestSanitizer(req)
}
- const maxProviderAttempts = 2
+ maxProviderAttempts := 2
+ if fastFailProviderStartup {
+ maxProviderAttempts = 1
+ }
err := error(nil)
for attempt := 1; attempt <= maxProviderAttempts; attempt++ {
attemptSawDone := false
attemptEmittedVisibleEvents := false
var attemptErrorMessages []string
+ providerCtx := ctx
+ var cancelProviderStartup context.CancelFunc
+ var startupTimedOut atomic.Bool
+ var startupTimer *time.Timer
+ stopStartupTimer := func() {}
+ if fastFailProviderStartup {
+ providerCtx, cancelProviderStartup = context.WithCancel(ctx)
+ startupTimer = time.AfterFunc(providerFallbackStartupTimeout, func() {
+ startupTimedOut.Store(true)
+ cancelProviderStartup()
+ })
+ stopStartupTimer = func() {
+ if startupTimer != nil {
+ startupTimer.Stop()
+ }
+ }
+ }
- err = a.provider.ChatStream(ctx, req, func(event providers.StreamEvent) {
+ err = a.provider.ChatStream(providerCtx, req, func(event providers.StreamEvent) {
+ if providerStreamEventShowsStartup(event) {
+ stopStartupTimer()
+ }
switch event.Type {
case "content":
if data, ok := event.Data.(providers.ContentEvent); ok {
@@ -1021,6 +1070,13 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
}
}
})
+ stopStartupTimer()
+ if cancelProviderStartup != nil {
+ cancelProviderStartup()
+ }
+ if startupTimedOut.Load() && err != nil {
+ err = fmt.Errorf("provider startup timed out after %s: %w", providerFallbackStartupTimeout, err)
+ }
effectiveErr := err
if effectiveErr == nil && len(attemptErrorMessages) > 0 {
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 534a8cc78b..832c16000f 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -817,7 +817,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
emitChatProviderFallback(streamCallback, selectedModel, initialFallbackModel)
}
- runAttempt := func(attempt chatProviderAttempt) ([]Message, *AgenticLoop, bool, error) {
+ runAttempt := func(attempt chatProviderAttempt, hasFallback bool) ([]Message, *AgenticLoop, bool, error) {
attemptProvider := attempt.Provider
if attemptProvider == nil {
if strings.TrimSpace(attempt.Model) == "" {
@@ -850,6 +850,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
loop := NewAgenticLoop(attemptProvider, executor, systemPrompt)
loop.SetOrgID(s.orgID)
loop.SetAutonomousMode(autonomousMode)
+ loop.SetFastFailProviderStartup(hasFallback)
loop.SetPreferSummaryOnlyQueries(assistantToolScope == assistantTurnToolScopeQueryOnly)
sanitizerOptions := []modelboundary.RequestSanitizerOption{}
if modelBoundaryAllowedInventoryContext != "" {
@@ -924,7 +925,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
for attemptIndex, attempt := range attempts {
var attemptVisible bool
lastAttemptModel = attempt.Model
- resultMessages, loop, attemptVisible, streamErr = runAttempt(attempt)
+ resultMessages, loop, attemptVisible, streamErr = runAttempt(attempt, attemptIndex < len(attempts)-1)
if streamErr == nil {
selectedModel = attempt.Model
break
diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go
index 04549b202e..ceab11676a 100644
--- a/internal/ai/chat/service_execute_additional_test.go
+++ b/internal/ai/chat/service_execute_additional_test.go
@@ -746,13 +746,17 @@ func TestService_ExecuteStream_FallsBackWhenPrimaryProviderFailsBeforeVisibleOut
t.Fatalf("failed to create session store: %v", err)
}
+ var primaryStartupMode providers.ProviderStartupMode
+ var fallbackStartupMode providers.ProviderStartupMode
primary := &stubServiceProvider{
streamFn: func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ primaryStartupMode = req.ProviderStartupMode
return errors.New("API error (401): unauthorized")
},
}
fallback := &stubServiceProvider{
streamFn: func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ fallbackStartupMode = req.ProviderStartupMode
callback(providers.StreamEvent{
Type: "content",
Data: providers.ContentEvent{Text: "PULSE_OK"},
@@ -832,6 +836,12 @@ func TestService_ExecuteStream_FallsBackWhenPrimaryProviderFailsBeforeVisibleOut
if doneModel != "gemini:gemini-test" {
t.Fatalf("done model = %q, want fallback model", doneModel)
}
+ if primaryStartupMode != providers.ProviderStartupFastFailBeforeVisibleOutput {
+ t.Fatalf("primary startup mode = %q, want fast-fail before fallback", primaryStartupMode)
+ }
+ if fallbackStartupMode != providers.ProviderStartupDefault {
+ t.Fatalf("fallback startup mode = %q, want provider default", fallbackStartupMode)
+ }
messages, err := store.GetMessages("fallback-before-visible-output")
if err != nil {
@@ -851,8 +861,10 @@ func TestService_ExecuteStream_FallsBackToSameModelOpenRouterGatewayBeforeDefaul
t.Fatalf("failed to create session store: %v", err)
}
+ var primaryCalls atomic.Int32
primary := &stubServiceProvider{
streamFn: func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ primaryCalls.Add(1)
return errors.New("dial tcp: i/o timeout")
},
}
@@ -930,6 +942,9 @@ func TestService_ExecuteStream_FallsBackToSameModelOpenRouterGatewayBeforeDefaul
if doneModel != "openrouter:deepseek/deepseek-v4-pro" {
t.Fatalf("done model = %q, want same-model OpenRouter route", doneModel)
}
+ if got := primaryCalls.Load(); got != 1 {
+ t.Fatalf("primary provider calls = %d, want one fast-fail call before fallback", got)
+ }
}
func TestService_ChatProviderAttemptsUsesStableFallbackModelsWithoutLiveCatalog(t *testing.T) {
diff --git a/internal/ai/providers/gemini.go b/internal/ai/providers/gemini.go
index c5733a0faa..69bec6a9d8 100644
--- a/internal/ai/providers/gemini.go
+++ b/internal/ai/providers/gemini.go
@@ -424,8 +424,13 @@ func (c *GeminiClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
// Retry loop for transient errors
var respBody []byte
var lastErr error
+ maxRetries := geminiMaxRetries
- for attempt := 0; attempt <= geminiMaxRetries; attempt++ {
+ if req.FastFailProviderStartup() {
+ maxRetries = 0
+ }
+
+ for attempt := 0; attempt <= maxRetries; attempt++ {
if attempt > 0 {
// Exponential backoff: 2s, 4s, 8s
backoff := geminiInitialBackoff * time.Duration(1<<(attempt-1))
@@ -506,7 +511,7 @@ func (c *GeminiClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
}
if lastErr != nil {
- return nil, fmt.Errorf("request failed after %d retries: %w", geminiMaxRetries, lastErr)
+ return nil, fmt.Errorf("request failed after %d retries: %w", maxRetries, lastErr)
}
var geminiResp geminiResponse
@@ -826,8 +831,13 @@ func (c *GeminiClient) ChatStream(ctx context.Context, req ChatRequest, callback
// Retry loop for transient errors (matching non-streaming Chat behavior)
var resp *http.Response
var lastErr error
+ maxRetries := geminiMaxRetries
+
+ if req.FastFailProviderStartup() {
+ maxRetries = 0
+ }
- for attempt := 0; attempt <= geminiMaxRetries; attempt++ {
+ for attempt := 0; attempt <= maxRetries; attempt++ {
// Bail out early if the parent context is already cancelled
if ctx.Err() != nil {
if lastErr != nil {
@@ -898,7 +908,7 @@ func (c *GeminiClient) ChatStream(ctx context.Context, req ChatRequest, callback
}
if lastErr != nil {
- return fmt.Errorf("request failed after %d retries: %w", geminiMaxRetries, lastErr)
+ return fmt.Errorf("request failed after %d retries: %w", maxRetries, lastErr)
}
if resp.StatusCode != http.StatusOK {
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.go
index a086a6aa8f..248d70ced4 100644
--- a/internal/ai/providers/openai.go
+++ b/internal/ai/providers/openai.go
@@ -439,8 +439,12 @@ func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
// Retry loop for transient errors (connection resets, 429, 5xx)
var respBody []byte
var lastErr error
+ maxRetries := openaiMaxRetries
+ if req.FastFailProviderStartup() {
+ maxRetries = 0
+ }
- for attempt := 0; attempt <= openaiMaxRetries; attempt++ {
+ for attempt := 0; attempt <= maxRetries; attempt++ {
if attempt > 0 {
// Exponential backoff: 2s, 4s, 8s
backoff := openaiInitialBackoff * time.Duration(1<<(attempt-1))
@@ -523,7 +527,7 @@ func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
}
if lastErr != nil {
- return nil, fmt.Errorf("request failed after %d retries: %w", openaiMaxRetries, lastErr)
+ return nil, fmt.Errorf("request failed after %d retries: %w", maxRetries, lastErr)
}
var openaiResp openaiResponse
@@ -907,8 +911,12 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
if streamClient == nil {
streamClient = c.client
}
+ maxRetries := openaiStreamMaxRetries
+ if req.FastFailProviderStartup() {
+ maxRetries = 0
+ }
- for attempt := 0; attempt <= openaiStreamMaxRetries; attempt++ {
+ for attempt := 0; attempt <= maxRetries; attempt++ {
if attempt > 0 {
backoff := openaiStreamInitialBackoff * time.Duration(1<<(attempt-1))
log.Warn().
@@ -971,7 +979,7 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
}
if lastErr != nil {
- return fmt.Errorf("request failed after %d stream retries: %w", openaiStreamMaxRetries, lastErr)
+ return fmt.Errorf("request failed after %d stream retries: %w", maxRetries, lastErr)
}
defer resp.Body.Close()
diff --git a/internal/ai/providers/openai_test.go b/internal/ai/providers/openai_test.go
index bdd4aadeb3..d9d987674e 100644
--- a/internal/ai/providers/openai_test.go
+++ b/internal/ai/providers/openai_test.go
@@ -181,6 +181,26 @@ func TestOpenAIClient_ChatStream_RetriesTransientStartupError(t *testing.T) {
assert.Equal(t, "ok", content)
}
+func TestOpenAIClient_ChatStream_FastFailSkipsTransientStartupRetry(t *testing.T) {
+ client := NewOpenAIClient("sk-test", "gpt-4", "https://example.invalid/v1", 0)
+ attempts := 0
+ client.streamClient = &http.Client{
+ Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ attempts++
+ return nil, io.ErrUnexpectedEOF
+ }),
+ }
+
+ err := client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "Hi"}},
+ ProviderStartupMode: ProviderStartupFastFailBeforeVisibleOutput,
+ }, func(StreamEvent) {})
+
+ require.Error(t, err)
+ assert.Equal(t, 1, attempts)
+ assert.Contains(t, err.Error(), "request failed after 0 stream retries")
+}
+
func TestNewOpenAIClient_BoundsStreamResponseHeaderTimeout(t *testing.T) {
client := NewOpenAIClient("sk-test", "gpt-4", "https://api.openai.com/v1", 0)
transport, ok := client.streamClient.Transport.(*http.Transport)
diff --git a/internal/ai/providers/provider.go b/internal/ai/providers/provider.go
index 40d72f04d6..72d4c1b97b 100644
--- a/internal/ai/providers/provider.go
+++ b/internal/ai/providers/provider.go
@@ -89,16 +89,28 @@ type ToolChoice struct {
Type ToolChoiceType `json:"type"`
}
+type ProviderStartupMode string
+
+const (
+ // ProviderStartupDefault keeps provider-owned startup retries enabled.
+ ProviderStartupDefault ProviderStartupMode = ""
+ // ProviderStartupFastFailBeforeVisibleOutput is used when the caller has a
+ // separate fallback route ready and wants startup failures to return quickly
+ // before any user-visible provider output is emitted.
+ ProviderStartupFastFailBeforeVisibleOutput ProviderStartupMode = "fast_fail_before_visible_output"
+)
+
// 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
+ 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
+ ProviderStartupMode ProviderStartupMode `json:"-"`
}
func (r ChatRequest) NormalizeCollections() ChatRequest {
@@ -117,6 +129,10 @@ func (r ChatRequest) NormalizeCollections() ChatRequest {
return r
}
+func (r ChatRequest) FastFailProviderStartup() bool {
+ return r.ProviderStartupMode == ProviderStartupFastFailBeforeVisibleOutput
+}
+
// ChatResponse represents a response from the AI provider
type ChatResponse struct {
Content string `json:"content"`