| 1 | package control |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "golang.org/x/net/http2" |
| 16 | "reasonix/internal/agent" |
| 17 | "reasonix/internal/event" |
| 18 | "reasonix/internal/provider" |
| 19 | "reasonix/internal/provider/openai" |
| 20 | "reasonix/internal/session" |
| 21 | "reasonix/internal/tool" |
| 22 | ) |
| 23 | |
| 24 | type diagnosticFailureTransport struct { |
| 25 | calls int |
| 26 | beforeFailure func() |
| 27 | cause error |
| 28 | } |
| 29 | |
| 30 | func (r *diagnosticFailureTransport) RoundTrip(*http.Request) (*http.Response, error) { |
| 31 | r.calls++ |
| 32 | if r.beforeFailure != nil { |
| 33 | r.beforeFailure() |
| 34 | } |
| 35 | if r.cause != nil { |
| 36 | return nil, r.cause |
| 37 | } |
| 38 | return nil, http2.ConnectionError(http2.ErrCodeProtocol) |
| 39 | } |
| 40 | |
| 41 | func TestProviderFailureSurvivesCleanupAndColdExport(t *testing.T) { |
| 42 | for _, async := range []bool{false, true} { |
| 43 | t.Run(map[bool]string{false: "synchronous", true: "desktop-send"}[async], func(t *testing.T) { |
| 44 | for _, broken := range []bool{false, true} { |
| 45 | t.Run(map[bool]string{false: "valid-evidence", true: "unencodable-evidence"}[broken], func(t *testing.T) { |
| 46 | testProviderFailureColdExport(t, async, broken) |
| 47 | }) |
| 48 | } |
| 49 | }) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func TestSendTimeoutSurvivesCleanupAndColdExport(t *testing.T) { |
| 54 | for _, async := range []bool{false, true} { |
| 55 | for _, broken := range []bool{false, true} { |
| 56 | t.Run(fmt.Sprintf("async=%v/broken=%v", async, broken), func(t *testing.T) { |
| 57 | testProviderFailureColdExport(t, async, broken, &provider.RequestSendTimeoutError{Budget: 300 * time.Second}) |
| 58 | }) |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | func testProviderFailureColdExport(t *testing.T, async, broken bool, causes ...error) { |
| 64 | service, err := session.NewService("local", session.NewFilesystemPersistence(t.TempDir())) |
| 65 | if err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "provider-diagnostic"}) |
| 69 | if err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | transport := &diagnosticFailureTransport{} |
| 73 | wantKind, wantCode, wantErrorCode, evidence, wantCalls := "transport_protocol", "PROTOCOL_ERROR", "http2_protocol", "PROTOCOL_ERROR", 1 |
| 74 | if len(causes) > 0 { |
| 75 | transport.cause = causes[0] |
| 76 | // An unfinished upload is resent once; both attempts are evidence. |
| 77 | wantKind, wantCode, wantErrorCode, evidence, wantCalls = "request_send_timeout", "", "request_send_timeout", "request_send_timeout", 2 |
| 78 | } |
| 79 | p, err := openai.New(provider.Config{Name: "test", Protocol: "openai", Model: "test-model", APIKey: "private-key", BaseURL: "https://provider.test/v1", HTTPClient: &http.Client{Transport: transport}}) |
| 80 | if err != nil { |
| 81 | t.Fatal(err) |
| 82 | } |
| 83 | exec := agent.New(p, tool.NewRegistry(), agent.NewSession("stable system"), agent.Options{}, event.Discard) |
| 84 | done := make(chan event.Event, 1) |
| 85 | sink := event.FuncSink(func(e event.Event) { |
| 86 | if e.Kind == event.TurnDone { |
| 87 | done <- e |
| 88 | } |
| 89 | }) |
| 90 | c := newOwnedTestController(t, Options{Runner: exec, Executor: exec, Sink: sink, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true}) |
| 91 | if broken { |
| 92 | transport.beforeFailure = func() { |
| 93 | _, turnID, _ := c.currentTurnToken() |
| 94 | c.recordProviderRequest(turnID, provider.RequestObservation{ID: ^uint64(0), Phase: "request_started", |
| 95 | StartedAt: time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)}) |
| 96 | } |
| 97 | } |
| 98 | if async { |
| 99 | c.Send("hello") |
| 100 | if terminal := waitTurnDoneEvent(t, done); terminal.Err == nil { |
| 101 | t.Fatal("expected transport failure") |
| 102 | } |
| 103 | waitIdleAdmission(t, c) |
| 104 | } else if err := c.RunTurn(t.Context(), "hello"); err == nil { |
| 105 | t.Fatal("expected transport failure") |
| 106 | } |
| 107 | if transport.calls != wantCalls { |
| 108 | t.Fatalf("request count=%d", transport.calls) |
| 109 | } |
| 110 | var recovery *provider.InterruptedTurnRecovery |
| 111 | for _, m := range c.sessionEventStore().Snapshot().Projection.Messages { |
| 112 | if m.InterruptedTurn != nil { |
| 113 | recovery = m.InterruptedTurn |
| 114 | } |
| 115 | } |
| 116 | if recovery == nil || recovery.TerminalStatus != "failed" || recovery.FailureDiagnostic == nil || recovery.FailureDiagnostic.Kind != wantKind || recovery.FailureDiagnostic.TransportCode != wantCode { |
| 117 | t.Fatalf("cleanup lost failure: %+v", recovery) |
| 118 | } |
| 119 | commits := terminationCommitHistory(t, c) |
| 120 | count, terminals := 0, 0 |
| 121 | for _, commit := range commits { |
| 122 | for _, e := range commit.Events { |
| 123 | if e.Kind == "turn/end" { |
| 124 | terminals++ |
| 125 | } |
| 126 | if e.Kind != "diagnostic/provider" { |
| 127 | continue |
| 128 | } |
| 129 | count++ |
| 130 | if !e.Optional || commit.Events[len(commit.Events)-1].Kind != "turn/end" { |
| 131 | t.Fatal("diagnostic is not optional and atomic with termination") |
| 132 | } |
| 133 | var payload struct { |
| 134 | Failure *provider.FailureDiagnostic |
| 135 | Requests []providerDiagnostic |
| 136 | Dropped *uint64 |
| 137 | Truncated bool |
| 138 | } |
| 139 | if err := json.Unmarshal(e.Payload, &payload); err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | if payload.Failure == nil || payload.Failure.Kind != wantKind || payload.Failure.TransportCode != wantCode || len(payload.Requests) != wantCalls { |
| 143 | t.Fatalf("incomplete durable evidence: %s", e.Payload) |
| 144 | } |
| 145 | if bytes.Contains(e.Payload, []byte(`"transportError"`)) { |
| 146 | t.Fatal("persisted duplicate transport error prose") |
| 147 | } |
| 148 | if payload.Dropped == nil || *payload.Dropped != 0 || payload.Truncated { |
| 149 | t.Fatalf("fresh turn lost completeness: %s", e.Payload) |
| 150 | } |
| 151 | for _, r := range payload.Requests { |
| 152 | if r.Host != "provider.test" || r.RequestPath != "/v1/chat/completions" || r.Phase != "request_error" || r.TransportCode != wantCode || r.ErrorCode != wantErrorCode || r.RequestBytes <= 0 || r.SendTimeoutMs != 300000 { |
| 153 | t.Fatalf("request evidence: %+v", r) |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | wantCount := 1 |
| 159 | if broken { |
| 160 | wantCount = 0 |
| 161 | } |
| 162 | if count != wantCount || terminals != 1 { |
| 163 | t.Fatalf("diagnostic count=%d, terminal count=%d", count, terminals) |
| 164 | } |
| 165 | ref := runtime.Ref() |
| 166 | c.Close() |
| 167 | <-c.closeFinalized |
| 168 | if err := service.CloseAll(context.Background()); err != nil { |
| 169 | t.Fatal(err) |
| 170 | } |
| 171 | snapshot, err := service.Query().CaptureDiagnosticSnapshot(t.Context(), ref) |
| 172 | if err != nil { |
| 173 | t.Fatal(err) |
| 174 | } |
| 175 | var out bytes.Buffer |
| 176 | if err := WriteColdSessionDiagnostics(t.Context(), &out, service.Query(), snapshot, GoalDiagnosticMetadata{}, nil); err != nil { |
| 177 | t.Fatal(err) |
| 178 | } |
| 179 | if !json.Valid(out.Bytes()) || !strings.Contains(out.String(), evidence) || strings.Contains(out.String(), "diagnostic/provider") == broken || strings.Contains(out.String(), "private-key") { |
| 180 | t.Fatalf("invalid cold export: %s", out.String()) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func TestProviderDiagnosticEventIsBoundedAndTurnScoped(t *testing.T) { |
| 185 | c := &Controller{} |
| 186 | c.beginProviderDiagnosticTurn("current") |
| 187 | for id := uint64(1); id <= 130; id++ { |
| 188 | c.recordProviderRequest("current", provider.RequestObservation{ID: id, Phase: "request_started", ProtocolFallbackReason: "INTERNAL_ERROR"}) |
| 189 | } |
| 190 | c.recordProviderRequest("other", provider.RequestObservation{ID: 131, Phase: "request_started"}) |
| 191 | e, err := c.providerDiagnosticEvent(event.Event{TurnID: "current", Err: context.Canceled}) |
| 192 | if err != nil { |
| 193 | t.Fatal(err) |
| 194 | } |
| 195 | var payload struct { |
| 196 | SchemaVersion int |
| 197 | Failure *provider.FailureDiagnostic |
| 198 | Requests []providerDiagnostic |
| 199 | Dropped uint64 |
| 200 | Truncated bool |
| 201 | } |
| 202 | if err := json.Unmarshal(e.Payload, &payload); err != nil { |
| 203 | t.Fatal(err) |
| 204 | } |
| 205 | if !e.Optional || payload.SchemaVersion != 2 { |
| 206 | t.Fatal("compatibility evidence must remain an optional versioned extension") |
| 207 | } |
| 208 | if len(payload.Requests) != 127 || payload.Failure.Kind != provider.FailureKindCancelled || payload.Dropped != 3 || !payload.Truncated { |
| 209 | t.Fatalf("bounded evidence: %+v", payload) |
| 210 | } |
| 211 | for _, request := range payload.Requests { |
| 212 | if request.ProtocolFallbackReason != "INTERNAL_ERROR" { |
| 213 | t.Fatal("lost compatibility selection evidence") |
| 214 | } |
| 215 | if request.TurnID != "current" { |
| 216 | t.Fatal("cross-turn evidence") |
| 217 | } |
| 218 | } |
| 219 | if e, err := c.providerDiagnosticEvent(event.Event{TurnID: "unused"}); err != nil || e != nil { |
| 220 | t.Fatal("invented evidence for an unobserved turn") |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | func TestTerminationPreservesFailureWithoutChangingModelContext(t *testing.T) { |
| 225 | for _, status := range []string{"failed", "interrupted", ""} { |
| 226 | t.Run(status, func(t *testing.T) { |
| 227 | recovery := &provider.InterruptedTurnRecovery{Pending: true, TerminalStatus: status} |
| 228 | if status == "failed" { |
| 229 | recovery.FailureDiagnostic = &provider.FailureDiagnostic{Kind: "transport_protocol", TransportCode: "PROTOCOL_ERROR"} |
| 230 | recovery.Cause = "connection error: PROTOCOL_ERROR" |
| 231 | } |
| 232 | user := provider.Message{ID: "user", Role: provider.RoleUser, Content: "hello"} |
| 233 | local := provider.Message{ID: "local", Role: provider.RoleTool, LocalOnly: true, InterruptedTurn: recovery} |
| 234 | before := []provider.Message{user, local} |
| 235 | got := planCancelledMessages(before, 0, user, time.Time{}, func(provider.Message) bool { return true }, nil) |
| 236 | oldBytes, _ := json.Marshal(provider.ModelMessages(before)) |
| 237 | newBytes, _ := json.Marshal(provider.ModelMessages(got)) |
| 238 | if !bytes.Equal(oldBytes, newBytes) { |
| 239 | t.Fatal("diagnostics changed model-visible bytes") |
| 240 | } |
| 241 | after := got[len(got)-1].InterruptedTurn |
| 242 | if after.TerminalStatus != status || after.Cause != recovery.Cause || (after.FailureDiagnostic == nil) != (recovery.FailureDiagnostic == nil) { |
| 243 | t.Fatalf("lost terminal metadata: %+v", after) |
| 244 | } |
| 245 | if after.FailureDiagnostic != nil { |
| 246 | after.FailureDiagnostic.Kind = "changed" |
| 247 | if recovery.FailureDiagnostic.Kind == "changed" { |
| 248 | t.Fatal("aliased original diagnostic") |
| 249 | } |
| 250 | } |
| 251 | }) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | func TestProviderDiagnosticEventOmitsErrorProse(t *testing.T) { |
| 256 | for _, err := range []error{ |
| 257 | &provider.RequestFailure{Err: &url.Error{Op: "Post", URL: "https://user:password@provider.test/v1/chat?arbitrary=private-query#private-fragment", Err: http2.ConnectionError(http2.ErrCodeProtocol)}}, |
| 258 | &provider.RequestFailure{Err: errors.New("private free-form error " + strings.Repeat("中文", 1200))}, |
| 259 | &provider.RequestFailure{Err: &provider.APIError{Status: 400, Body: "private request body"}}, |
| 260 | } { |
| 261 | c := &Controller{} |
| 262 | e, encodeErr := c.providerDiagnosticEvent(event.Event{TurnID: "turn", Status: event.TurnFailed, Err: err}) |
| 263 | if encodeErr != nil || e == nil { |
| 264 | t.Fatalf("missing structured evidence: %v", encodeErr) |
| 265 | } |
| 266 | for _, unwanted := range []string{`"transportError"`, "private", "password", "user:", "中文"} { |
| 267 | if bytes.Contains(e.Payload, []byte(unwanted)) { |
| 268 | t.Fatalf("persisted error prose %q: %s", unwanted, e.Payload) |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 |