返回 DeepSeek-Reasonix
no_deliverable_test.go
根目录 / internal / agent / no_deliverable_test.go
1 package agent
2
3 import (
4 "context"
5 "errors"
6 "reflect"
7 "strings"
8 "testing"
9
10 "reasonix/internal/event"
11 "reasonix/internal/provider"
12 "reasonix/internal/tool"
13 )
14
15 func TestNoDeliverableRecoveryDoesNotResetAfterTools(t *testing.T) {
16 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
17 reasoningOnlyStop("I should execute."),
18 {toolCallChunk("read-once", "read_file", `{}`), {Type: provider.ChunkDone}},
19 reasoningOnlyStop("I should answer."),
20 {{Type: provider.ChunkText, Text: "next user turn"}, {Type: provider.ChunkDone}},
21 }}
22 reg := tool.NewRegistry()
23 reg.Add(fakeReadFileTool{})
24 var summaries []*event.ResponseSummary
25 a := New(prov, reg, NewSession("stable system"), Options{ModelRef: "p/test"}, event.FuncSink(func(e event.Event) {
26 if e.StreamAttempt.Response != nil {
27 summaries = append(summaries, e.StreamAttempt.Response)
28 }
29 }))
30 if err := a.Run(t.Context(), "read and answer"); !errors.Is(err, provider.ErrNoDeliverableOutput) {
31 t.Fatalf("Run = %v", err)
32 }
33 if prov.call != 3 || countUserMessagesContaining(a.Session(), "visible answer") != 1 {
34 t.Fatalf("recovery restarted after a tool: calls=%d", prov.call)
35 }
36 // The recovery is append-only; original prompt and reasoning stay intact.
37 prefix := prov.requests[0].Messages
38 if !reflect.DeepEqual(prefix, prov.requests[1].Messages[:len(prefix)]) {
39 t.Fatal("recovery rewrote the provider-visible prefix")
40 }
41 if summaries[0].FinishReason != "stop" || summaries[0].TextBytes != 0 || summaries[0].ReasoningBytes == 0 ||
42 summaries[0].ModelRef != "p/test" || !summaries[0].StreamComplete {
43 t.Fatalf("incomplete response diagnostics: %+v", summaries[0])
44 }
45 // Only the reply to the recovery prompt is attributed to it; later rounds
46 // in the same Run are ordinary responses.
47 if got := []int{summaries[0].RecoveryAttempts, summaries[1].RecoveryAttempts, summaries[2].RecoveryAttempts}; !reflect.DeepEqual(got, []int{0, 1, 0}) {
48 t.Fatalf("recovery attribution = %v, want [0 1 0]", got)
49 }
50 toolResults := 0
51 for _, m := range a.Session().Snapshot() {
52 if m.Role == provider.RoleTool && m.ToolCallID == "read-once" {
53 toolResults++
54 }
55 }
56 if toolResults != 1 {
57 t.Fatalf("tool replayed or lost: results=%d", toolResults)
58 }
59 if err := a.Run(t.Context(), "continue"); err != nil || prov.call != 4 {
60 t.Fatalf("new user turn unavailable: calls=%d, err=%v", prov.call, err)
61 }
62 }
63
64 func TestNoDeliverableRecoveryHonorsCancellationAndBudget(t *testing.T) {
65 for _, cancel := range []bool{false, true} {
66 t.Run(map[bool]string{false: "budget", true: "cancel"}[cancel], func(t *testing.T) {
67 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{{
68 {Type: provider.ChunkReasoning, Text: "thinking"},
69 {Type: provider.ChunkUsage, Usage: &provider.Usage{PromptTokens: 8, CompletionTokens: 2, TotalTokens: 10, FinishReason: "stop"}},
70 {Type: provider.ChunkDone},
71 }}}
72 ctx, stop := context.WithCancel(t.Context())
73 defer stop()
74 opts := Options{}
75 if !cancel {
76 opts.TaskBudget = TaskBudget{Tokens: 1}
77 }
78 a := New(prov, tool.NewRegistry(), NewSession(""), opts, event.FuncSink(func(e event.Event) {
79 if cancel && e.Kind == event.StreamAttempt && e.StreamAttempt.Action == event.StreamAttemptCommit {
80 stop()
81 }
82 }))
83 err := a.Run(ctx, "answer")
84 var budget *taskBudgetPause
85 if cancel && !errors.Is(err, context.Canceled) || !cancel && !errors.As(err, &budget) {
86 t.Fatalf("Run=%v", err)
87 }
88 if prov.call != 1 || sessionHasUserMessageContaining(a.Session(), "visible answer") {
89 t.Fatalf("recovery bypassed stop: calls=%d", prov.call)
90 }
91 })
92 }
93 }
94
95 func TestCancelAfterCommittedAnswerEndsRunCancelled(t *testing.T) {
96 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
97 {{Type: provider.ChunkText, Text: "complete answer"}, {Type: provider.ChunkDone}},
98 {{Type: provider.ChunkText, Text: "must not run"}, {Type: provider.ChunkDone}},
99 }}
100 ctx, stop := context.WithCancel(t.Context())
101 defer stop()
102 a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, event.FuncSink(func(e event.Event) {
103 if e.Kind == event.StreamAttempt && e.StreamAttempt.Action == event.StreamAttemptCommit {
104 stop()
105 }
106 }))
107 if err := a.Run(ctx, "answer"); !errors.Is(err, context.Canceled) {
108 t.Fatalf("Run=%v, want cancellation to win after commit", err)
109 }
110 if prov.call != 1 || lastAssistantContent(a.Session()) != "complete answer" {
111 t.Fatalf("calls=%d, committed answer=%q", prov.call, lastAssistantContent(a.Session()))
112 }
113 }
114
115 func TestNoDeliverableBudgetSpentDuringRecoveryPauses(t *testing.T) {
116 stop := func() []provider.Chunk {
117 return []provider.Chunk{
118 {Type: provider.ChunkReasoning, Text: "thinking"},
119 {Type: provider.ChunkUsage, Usage: &provider.Usage{PromptTokens: 8, CompletionTokens: 2, TotalTokens: 10, FinishReason: "stop"}},
120 {Type: provider.ChunkDone},
121 }
122 }
123 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{stop(), stop()}}
124 // The first stop stays under budget; the recovery round crosses it.
125 a := New(prov, tool.NewRegistry(), NewSession(""), Options{TaskBudget: TaskBudget{Tokens: 15}}, event.Discard)
126 err := a.Run(t.Context(), "answer")
127 var budget *taskBudgetPause
128 if !errors.As(err, &budget) || errors.Is(err, provider.ErrNoDeliverableOutput) || prov.call != 2 {
129 t.Fatalf("Run=%v, calls=%d, want resumable budget pause", err, prov.call)
130 }
131 }
132
133 func TestNoDeliverableFailsWithoutProviderSpecificPolicy(t *testing.T) {
134 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
135 reasoningOnlyStop("thinking"),
136 reasoningOnlyStop("still thinking"),
137 }}
138 a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, event.Discard)
139 err := a.Run(t.Context(), "answer")
140 if !errors.Is(err, provider.ErrNoDeliverableOutput) || prov.call != 2 {
141 t.Fatalf("Run=%v, calls=%d", err, prov.call)
142 }
143 if d := provider.DiagnoseFailure(err); d == nil || d.Kind != "no_deliverable_output" {
144 t.Fatalf("failure classification=%+v", d)
145 }
146 if provider.ClassifyRecovery(err).Retryable {
147 t.Fatal("transport recovery must not restart the exhausted turn")
148 }
149 // Host diagnostics must never become model-visible context.
150 for _, req := range prov.requests {
151 for _, m := range req.Messages {
152 if strings.Contains(m.Content, "recoveryAttempts") || strings.Contains(m.Content, "streamComplete") {
153 t.Fatal("diagnostics leaked into prompt")
154 }
155 }
156 }
157 }
158
159 type failureMarkerRecorder struct {
160 settlementRecorder
161 err error
162 }
163
164 func (r *failureMarkerRecorder) RecordSessionMessages(ctx context.Context, reason string, messages []provider.Message) error {
165 if reason == "no-deliverable-output" {
166 return r.err
167 }
168 return r.settlementRecorder.RecordSessionMessages(ctx, reason, messages)
169 }
170
171 func TestNoDeliverableFailureMarkerPersistenceWins(t *testing.T) {
172 saveErr := errors.New("fixture storage unavailable")
173 recorder := &failureMarkerRecorder{
174 settlementRecorder: settlementRecorder{accepted: make(map[string]provider.Message)},
175 err: saveErr,
176 }
177 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
178 reasoningOnlyStop("thinking"),
179 reasoningOnlyStop("still thinking"),
180 }}
181 a := New(prov, tool.NewRegistry(), NewSession(""), Options{SessionCheckpointer: recorder}, event.Discard)
182 if err := a.Run(t.Context(), "answer"); !errors.Is(err, saveErr) || prov.call != 2 {
183 t.Fatalf("storage failure was hidden or retried: err=%v calls=%d", err, prov.call)
184 }
185 }
186
186 lines GO