Fix Patrol summary timeouts, abandoned telemetry, and TLS retries (#5167)

Address three reliability and telemetry defects found while auditing
v6.8.0 and v6.9.0 production telemetry:

- Pass `investigationStreamIdleTimeout` on `ensureFinalTextResponse`
summary requests so OpenAI-compatible and local providers keep Patrol's
60s stream idle budget (and subscription agents keep 4m) instead of
falling back to the 12s default chunk timeout.
- Record `OutcomeTimedOut` on `abandonedInvestigationSession` when the
stuck-run sweep closes an overdue run, keeping durable schema-23/24
telemetry aligned with the finding outcome instead of recording generic
`failed`.
- Treat `NotificationFailureTLS` as non-retryable so broken-certificate
and HTTP-on-HTTPS destinations dead-letter immediately instead of
repeating failed handshakes across queue and SMTP retries.
- Clarify the TLS certificate test error message in
`classifyNotificationError` so Email and Webhook tests no longer suggest
a Skip TLS Verify toggle that only Apprise HTTP provides.

Verification:
- Targeted Go tests passed across `internal/ai/chat`, `internal/ai`,
`internal/notifications`, and `internal/api/alerting`.
- `status_audit.py --check`, `registry_audit.py --check`, and pre-commit
governance guardrails passed.
This commit is contained in:
rcourtman
2026-11-25 23:05:33 +00:00
committed by GitHub
8 changed files with 152 additions and 39 deletions

View File

@@ -74,18 +74,21 @@ func (a *AgenticLoop) ensureFinalTextResponseWithSystemPrompt(
if override := strings.TrimSpace(systemPromptOverride); override != "" {
summarySystemPrompt = override
}
a.mu.Lock()
providerName := a.providerName
requestSanitizer := a.requestSanitizer
streamIdleTimeout := a.streamIdleTimeout
a.mu.Unlock()
summaryReq := providers.ChatRequest{
Messages: cleanMessages,
System: summarySystemPrompt,
ExecutionID: a.executionID,
Messages: cleanMessages,
System: summarySystemPrompt,
ExecutionID: a.executionID,
StreamIdleTimeout: investigationStreamIdleTimeout(a.currentExecutionProfile(), providerName, streamIdleTimeout),
// No Tools field: this is a final narrative turn, and Pulse avoids
// provider-specific tool_choice transport fields.
}
applyExecutionInferenceAllowance(&summaryReq, a.currentExecutionProfile(), true, a.totalOutputTokens)
applyExecutionRuntimeEnvelope(&summaryReq, a.currentExecutionProfile())
a.mu.Lock()
requestSanitizer := a.requestSanitizer
a.mu.Unlock()
if requestSanitizer != nil {
summaryReq = requestSanitizer(summaryReq)
}

View File

@@ -209,3 +209,60 @@ func TestInvestigationSummaryTimeoutUsesTheRemainingDeadline(t *testing.T) {
t.Fatalf("near-deadline summary timeout = %s, want %s (the deadline still bounds it)", got, base)
}
}
func TestInvestigationSummaryRetainsStreamIdleTimeout(t *testing.T) {
cases := []struct {
name string
profile tools.ExecutionProfile
providerName string
wantIdle time.Duration
}{
{
name: "streaming investigation preserves patrol idle budget on summary",
profile: tools.ProfilePatrolInvestigation,
providerName: "openai",
wantIdle: PatrolProviderStreamIdleTimeout,
},
{
name: "subscription investigation widens idle budget on summary",
profile: tools.ProfilePatrolInvestigation,
providerName: string(providers.SubscriptionAgentCodex),
wantIdle: patrolSubscriptionInvestigationTurnTimeout,
},
{
name: "interactive summary keeps provider default",
profile: tools.ProfileInteractiveAssistant,
providerName: "openai",
wantIdle: 0,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var gotIdle time.Duration
provider := &stubStreamingProvider{chatStream: func(ctx context.Context, req providers.ChatRequest, cb providers.StreamCallback) error {
gotIdle = req.StreamIdleTimeout
cb(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "Final summary."}})
cb(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
return nil
}}
loop := NewAgenticLoop(provider, tools.NewPulseToolExecutor(tools.ExecutorConfig{}), "Investigate")
loop.SetExecutionProfile(tc.profile)
loop.SetProviderInfo(tc.providerName, "test-model")
_, err := loop.ensureFinalTextResponse(
context.Background(),
"summary-idle",
nil,
[]providers.Message{{Role: "user", Content: "Check service"}},
func(StreamEvent) {},
)
if err != nil {
t.Fatalf("ensureFinalTextResponse returned error: %v", err)
}
if gotIdle != tc.wantIdle {
t.Fatalf("summary StreamIdleTimeout = %s, want %s", gotIdle, tc.wantIdle)
}
})
}
}

View File

@@ -1895,11 +1895,14 @@ func stuckInvestigationResult(f *Finding, orchestrator InvestigationOrchestrator
const abandonedRunError = "Patrol stopped waiting for this investigation after it ran past its time limit."
// abandonedInvestigationSession is a run's session as the stuck-run sweep gives
// the run up at now: failed, because it ran past its limit without closing.
// The orchestrator's own session is left as it is.
// the run up at now: failed and timed out, because it ran past its limit without
// closing. The orchestrator's own session is left as it is.
func abandonedInvestigationSession(session *InvestigationSession, now time.Time) *InvestigationSession {
abandoned := *session
abandoned.Status = aicontracts.InvestigationStatusFailed
if abandoned.Outcome == "" {
abandoned.Outcome = aicontracts.OutcomeTimedOut
}
abandoned.CompletedAt = &now
if strings.TrimSpace(abandoned.Error) == "" {
abandoned.Error = abandonedRunError

View File

@@ -301,3 +301,38 @@ func TestInvestigationRunCeilingFollowsTheConfiguredTimeout(t *testing.T) {
t.Fatalf("subscription ceiling = %s, want %s", got, want)
}
}
func TestRecoverStuckInvestigationsRecordsTimedOutOnAbandonedSession(t *testing.T) {
now := time.Now()
findings := NewFindingsStore()
findings.Add(runningInvestigationFinding("stuck", "chat-stuck", nil))
orchestrator := &sessionReportingOrchestrator{sessions: map[string]*InvestigationSession{
"stuck": {ID: "inv-stuck", FindingID: "stuck", SessionID: "chat-stuck", Status: aicontracts.InvestigationStatusRunning, StartedAt: now.Add(-time.Hour)},
}}
var closedSession *InvestigationSession
patrol := &PatrolService{
findings: findings,
investigationOrchestrator: orchestrator,
investigationRunCloser: func(findingID string, session *InvestigationSession) {
if findingID == "stuck" {
closedSession = session
}
},
}
patrol.recoverStuckInvestigations()
assertInvestigationState(t, findings, "stuck", InvestigationStatusFailed, InvestigationOutcomeTimedOut)
if closedSession == nil {
t.Fatal("expected abandoned session close callback to be invoked")
}
if closedSession.Status != aicontracts.InvestigationStatusFailed {
t.Fatalf("closed session status = %q, want %q", closedSession.Status, aicontracts.InvestigationStatusFailed)
}
if closedSession.Outcome != aicontracts.OutcomeTimedOut {
t.Fatalf("closed session outcome = %q, want %q", closedSession.Outcome, aicontracts.OutcomeTimedOut)
}
if closedSession.CompletedAt == nil || closedSession.CompletedAt.IsZero() {
t.Fatal("closed session CompletedAt was not set")
}
}

View File

@@ -939,21 +939,21 @@ func classifyNotificationError(err error) (summary, detail string) {
switch {
case strings.Contains(lower, "connection refused"):
summary = "Could not connect to the server — check host, port, and firewall settings"
summary = "Could not connect to the server: check host, port, and firewall settings"
case strings.Contains(lower, "no such host"):
summary = "Server hostname not found — check the server address"
summary = "Server hostname not found: check the server address"
case strings.Contains(lower, "i/o timeout") || strings.Contains(lower, "deadline exceeded"):
summary = "Connection timed out — the server may be unreachable or the port may be blocked"
case strings.Contains(lower, "x509:") || strings.Contains(lower, "certificate"):
summary = "TLS certificate error — check certificate settings or try enabling 'Skip TLS Verify'"
summary = "Connection timed out: the server may be unreachable or the port may be blocked"
case strings.Contains(lower, "x509:") || strings.Contains(lower, "certificate") || strings.Contains(lower, "server gave http response to https client"):
summary = "TLS certificate error: check the server certificate and TLS settings"
case strings.Contains(lower, "535") || strings.Contains(lower, "authentication"):
summary = "Authentication failed — check username and password"
summary = "Authentication failed: check username and password"
case strings.Contains(lower, "executable file not found"):
summary = "Required program not found — ensure it is installed on the server"
summary = "Required program not found: ensure it is installed on the server"
case strings.Contains(lower, "permission denied"):
summary = "Permission denied — the server process lacks access to the required resource"
summary = "Permission denied: the server process lacks access to the required resource"
case strings.Contains(lower, "eof"):
summary = "The server closed the connection unexpectedly — check if TLS/StartTLS settings are correct"
summary = "The server closed the connection unexpectedly: check if TLS/StartTLS settings are correct"
default:
summary = raw
detail = ""

View File

@@ -1286,63 +1286,70 @@ func TestClassifyNotificationError(t *testing.T) {
{
name: "connection refused",
err: "dial tcp smtp.gmail.com:587: connect: connection refused",
wantSummary: "Could not connect to the server — check host, port, and firewall settings",
wantSummary: "Could not connect to the server: check host, port, and firewall settings",
wantHasDetail: true,
summaryMustNot: []string{"dial tcp"},
},
{
name: "no such host",
err: "dial tcp: lookup smtp.example.com: no such host",
wantSummary: "Server hostname not found — check the server address",
wantSummary: "Server hostname not found: check the server address",
wantHasDetail: true,
summaryMustNot: []string{"dial tcp"},
},
{
name: "i/o timeout",
err: "dial tcp 10.0.0.1:587: i/o timeout",
wantSummary: "Connection timed out — the server may be unreachable or the port may be blocked",
wantSummary: "Connection timed out: the server may be unreachable or the port may be blocked",
wantHasDetail: true,
summaryMustNot: []string{"dial tcp"},
},
{
name: "context deadline exceeded",
err: "context deadline exceeded",
wantSummary: "Connection timed out — the server may be unreachable or the port may be blocked",
wantSummary: "Connection timed out: the server may be unreachable or the port may be blocked",
wantHasDetail: true,
summaryMustNot: []string{"context"},
},
{
name: "x509 certificate error",
err: "x509: certificate signed by unknown authority",
wantSummary: "TLS certificate error — check certificate settings or try enabling 'Skip TLS Verify'",
wantSummary: "TLS certificate error: check the server certificate and TLS settings",
wantHasDetail: true,
summaryMustNot: []string{"x509:"},
summaryMustNot: []string{"x509:", "Skip TLS Verify"},
},
{
name: "https client to http endpoint",
err: `Post "https://192.168.1.50:8080/hook": http: server gave HTTP response to HTTPS client`,
wantSummary: "TLS certificate error: check the server certificate and TLS settings",
wantHasDetail: true,
summaryMustNot: []string{"Skip TLS Verify"},
},
{
name: "smtp auth failure",
err: "535 5.7.8 Username and Password not accepted",
wantSummary: "Authentication failed — check username and password",
wantSummary: "Authentication failed: check username and password",
wantHasDetail: true,
summaryMustNot: []string{"535"},
},
{
name: "executable not found",
err: `exec: "apprise": executable file not found in $PATH`,
wantSummary: "Required program not found — ensure it is installed on the server",
wantSummary: "Required program not found: ensure it is installed on the server",
wantHasDetail: true,
summaryMustNot: []string{"exec:"},
},
{
name: "permission denied",
err: "open /etc/ssl/certs: permission denied",
wantSummary: "Permission denied — the server process lacks access to the required resource",
wantSummary: "Permission denied: the server process lacks access to the required resource",
wantHasDetail: true,
summaryMustNot: []string{"open /etc"},
},
{
name: "eof",
err: "read tcp 192.168.1.1:587: EOF",
wantSummary: "The server closed the connection unexpectedly — check if TLS/StartTLS settings are correct",
wantSummary: "The server closed the connection unexpectedly: check if TLS/StartTLS settings are correct",
wantHasDetail: true,
summaryMustNot: []string{"read tcp"},
},
@@ -1381,7 +1388,7 @@ func TestWriteTestNotificationError(t *testing.T) {
var resp map[string]string
assert.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(t, "Could not connect to the server — check host, port, and firewall settings", resp["error"])
assert.Equal(t, "Could not connect to the server: check host, port, and firewall settings", resp["error"])
assert.Equal(t, "dial tcp smtp.gmail.com:587: connect: connection refused", resp["detail"])
})

View File

@@ -270,25 +270,27 @@ func ClassifyNotificationFailureError(err error) NotificationFailureClass {
// Retryable reports whether another delivery attempt could plausibly succeed.
//
// Authentication, configuration and rejection are verdicts about the request
// itself: the same payload, sent again to the same destination with the same
// credentials, gets the same answer. Retrying them spends attempts, delays the
// dead letter the operator needs to see, and learns nothing. Connectivity,
// rate limiting and server errors describe conditions that clear on their own,
// and an unclassified failure is retried because nothing proves it will not
// succeed.
// Authentication, configuration, rejection, and TLS certificate or handshake
// mismatches are verdicts about the destination setup or request itself: the
// same payload, sent again to the same destination with the same credentials
// and TLS settings, gets the same answer. Retrying them spends attempts, delays
// the dead letter the operator needs to see, and learns nothing. Connectivity
// (including transient EOF/reset/timeout drops), rate limiting, and server
// errors describe conditions that clear on their own, and an unclassified
// failure is retried because nothing proves it will not succeed.
//
// This generalises to every destination type the decision webhook delivery
// already made for HTTP 4xx in isRetryableWebhookError.
//
// A dead letter is not the end of the road: once the operator fixes the
// credentials or the configuration, RetryTerminalFailures returns retained
// terminal failures to the queue with a fresh budget.
// credentials, certificate, or configuration, RetryTerminalFailures returns
// retained terminal failures to the queue with a fresh budget.
func (class NotificationFailureClass) Retryable() bool {
switch class {
case NotificationFailureAuthentication,
NotificationFailureConfiguration,
NotificationFailureRejected:
NotificationFailureRejected,
NotificationFailureTLS:
return false
default:
return true

View File

@@ -254,10 +254,10 @@ func TestFailureClassRetryable(t *testing.T) {
NotificationFailureAuthentication: false,
NotificationFailureConfiguration: false,
NotificationFailureRejected: false,
NotificationFailureTLS: false,
NotificationFailureConnectivity: true,
NotificationFailureRateLimited: true,
NotificationFailureServerError: true,
NotificationFailureTLS: true,
NotificationFailureUnknown: true,
NotificationFailureClass(""): true,
}
@@ -295,6 +295,12 @@ func TestProcessNotificationDeadLettersDeterministicFailureImmediately(t *testin
wantStatus: QueueStatusDLQ,
wantCallCount: 1,
},
{
name: "tls does not retry",
sendErr: FailWithClass(NotificationFailureTLS, x509.UnknownAuthorityError{}),
wantStatus: QueueStatusDLQ,
wantCallCount: 1,
},
{
name: "connectivity still retries",
sendErr: FailWithClass(NotificationFailureConnectivity, errors.New("dial tcp: connection refused")),