返回 DeepSeek-Reasonix
compact_overflow_prefix_test.go
根目录 / internal / agent / compact_overflow_prefix_test.go
1 package agent
2
3 import (
4 "context"
5 "strings"
6 "testing"
7
8 "reasonix/internal/provider"
9 )
10
11 type overflowSummaryProvider struct {
12 requests []provider.Request
13 }
14
15 func (p *overflowSummaryProvider) Name() string { return "overflow-summary" }
16
17 func (p *overflowSummaryProvider) ContextBudgetPolicy() provider.ContextBudgetPolicy {
18 return provider.ContextBudgetPolicy{
19 WindowMode: provider.ContextWindowShared,
20 LimitMode: provider.OutputLimitAlways,
21 }
22 }
23
24 func (p *overflowSummaryProvider) Stream(_ context.Context, req provider.Request) (<-chan provider.Chunk, error) {
25 p.requests = append(p.requests, req)
26 return chunks(
27 provider.Chunk{Type: provider.ChunkText, Text: "compact durable summary"},
28 provider.Chunk{Type: provider.ChunkDone},
29 ), nil
30 }
31
32 func TestOverflowSummarizesLargestAdmissibleContiguousPrefix(t *testing.T) {
33 sess := foldableSessionOverForce(120)
34 prov := &overflowSummaryProvider{}
35 a := agentOverForceWindow(t, prov, sess, 60_000)
36 msgs := sess.Snapshot()
37 head, plannedEnd, ok := a.planFoldRegion(msgs, true, false)
38 if !ok {
39 t.Fatal("fixture has no foldable prefix")
40 }
41 safeEnd := a.maximumSafeSummaryPrefixEnd(msgs, head, plannedEnd, "")
42 if safeEnd <= head || safeEnd >= plannedEnd {
43 t.Fatalf("safe fold end = %d, want a non-empty prefix smaller than planned end %d", safeEnd, plannedEnd)
44 }
45
46 if err := prepareContext(context.Background(), a, CompactionTriggerOverflow); err != nil {
47 t.Fatalf("overflow recovery: %v", err)
48 }
49 if len(prov.requests) != 1 {
50 t.Fatalf("summary requests = %d, want 1", len(prov.requests))
51 }
52 req := prov.requests[0]
53 if got, max := a.estimatedRequestTokens(req), a.effectiveContextWindow()-a.summaryOutputBudget()-protocolReserveTokens; got > max {
54 t.Fatalf("summary request tokens = %d, exceeds admissible input %d", got, max)
55 }
56 if receipt := a.sess.compactionState.LastReceipt; receipt == nil || receipt.CoveredCount != safeEnd {
57 t.Fatalf("receipt = %+v, want covered prefix %d", receipt, safeEnd)
58 }
59 if current := a.contextManager().currentPrepared(); current.InputTokens >= a.hardInputCeiling() {
60 t.Fatalf("recovered projection tokens = %d, hard ceiling = %d", current.InputTokens, a.hardInputCeiling())
61 }
62 }
63
64 func TestMaximumSafeSummaryPrefixKeepsToolPairsTogether(t *testing.T) {
65 // A 10k window leaves 7244 prompt tokens after the scaled 2500-token
66 // summary budget and protocol reserve. The initial boundary splits the tool
67 // results, so it must retreat across the whole assistant/tool group.
68 msgs := []provider.Message{
69 {Role: provider.RoleSystem, Content: "system"},
70 {Role: provider.RoleUser, Content: "old task"},
71 {Role: provider.RoleAssistant, ToolCalls: []provider.ToolCall{{ID: "call-1", Name: "read", Arguments: `{}`}}},
72 {Role: provider.RoleTool, ToolCallID: "call-1", Name: "read", Content: strings.Repeat("first result payload. ", 150)},
73 {Role: provider.RoleTool, ToolCallID: "call-1", Name: "read", Content: strings.Repeat("second result payload. ", 1500)},
74 {Role: provider.RoleUser, Content: "recent task"},
75 }
76 a := &Agent{
77 agentConfig: agentConfig{contextWindow: 10_000},
78 svc: agentServices{prov: &overflowSummaryProvider{}},
79 sess: sessionRuntime{conversation: &Session{Messages: msgs}},
80 }
81 end := a.maximumSafeSummaryPrefixEnd(msgs, 1, len(msgs)-1, "")
82 if end != 2 {
83 t.Fatalf("fold boundary = %d, want 2 so the assistant call and both results stay in the tail", end)
84 }
85 }
86
87 // opaqueWindowProvider declares no ContextBudgetPolicy (Unknown window mode)
88 // and is never admitted, reproducing the #9572 shape: a freshly switched-to
89 // gateway whose summary request used to bypass the safe-prefix cap entirely.
90 type opaqueWindowProvider struct {
91 requests []provider.Request
92 }
93
94 func (p *opaqueWindowProvider) Name() string { return "opaque-window" }
95
96 func (p *opaqueWindowProvider) Stream(_ context.Context, req provider.Request) (<-chan provider.Chunk, error) {
97 p.requests = append(p.requests, req)
98 return chunks(
99 provider.Chunk{Type: provider.ChunkText, Text: "compact durable summary"},
100 provider.Chunk{Type: provider.ChunkDone},
101 ), nil
102 }
103
104 func TestPressureSummaryCappedByConfiguredWindowWithoutAdmission(t *testing.T) {
105 sess := foldableSessionOverForce(120)
106 prov := &opaqueWindowProvider{}
107 a := agentOverForceWindow(t, prov, sess, 60_000)
108 if err := prepareContext(context.Background(), a, CompactionTriggerPressure); err != nil {
109 t.Fatalf("pressure maintenance: %v", err)
110 }
111 if len(prov.requests) != 1 {
112 t.Fatalf("summary requests = %d, want 1", len(prov.requests))
113 }
114 req := prov.requests[0]
115 if got, max := a.estimatedRequestTokens(req), a.effectiveContextWindow()-a.summaryOutputBudget()-protocolReserveTokens; got > max {
116 t.Fatalf("summary request tokens = %d, exceeds configured-window cap %d", got, max)
117 }
118 }
119
120 func TestPressureSummaryCappedByLearnedWindowAfterSessionReset(t *testing.T) {
121 sess := foldableSessionOverForce(120)
122 prov := &opaqueWindowProvider{}
123 a := agentOverForceWindow(t, prov, sess, 60_000)
124 a.contextWindow = 0
125 a.sess.output.learned.Store(&learnedContextBudget{windowTokens: 60_000})
126 a.storeAdmission(contextAdmission{ObservedWindow: 60_000})
127 a.SetSession(sess)
128 if got := a.lastAdmission().ObservedWindow; got != 0 {
129 t.Fatalf("session reset retained observed window %d", got)
130 }
131
132 msgs := sess.Snapshot()
133 head, plannedEnd, ok := a.planFoldRegion(msgs, true, false)
134 if !ok {
135 t.Fatal("fixture has no foldable prefix")
136 }
137 safeEnd := a.maximumSafeSummaryPrefixEnd(msgs, head, plannedEnd, "")
138 if safeEnd <= head || safeEnd >= plannedEnd {
139 t.Fatalf("safe fold end = %d, want a non-empty prefix smaller than planned end %d", safeEnd, plannedEnd)
140 }
141 request := a.summaryRequest(msgs[head:safeEnd], "")
142 if got, max := a.estimatedRequestTokens(request), a.effectiveContextWindow()-a.summaryOutputBudget()-protocolReserveTokens; got > max {
143 t.Fatalf("summary request tokens = %d, exceeds learned-window cap %d", got, max)
144 }
145 }
146
147 func smallWindowPressureSession() *Session {
148 return &Session{Messages: []provider.Message{
149 {Role: provider.RoleSystem, Content: "sys"},
150 {Role: provider.RoleUser, Content: strings.Repeat("x", 20_000)},
151 {Role: provider.RoleAssistant, Content: strings.Repeat("y", 12_000)},
152 {Role: provider.RoleUser, Content: "recent"},
153 }}
154 }
155
156 func TestPressureSummaryScalesOutputBudgetForSmallWindow(t *testing.T) {
157 const window = 10_000
158 prov := &opaqueWindowProvider{}
159 sess := smallWindowPressureSession()
160 a := agentOverForceWindow(t, prov, sess, window)
161 est := a.estimatedVisibleRequestTokens(a.modelVisibleMessages())
162 if est < a.compactTrigger() || est >= a.hardInputCeiling() {
163 t.Fatalf("fixture tokens = %d, want pressure range [%d, %d)", est, a.compactTrigger(), a.hardInputCeiling())
164 }
165 if err := prepareContext(context.Background(), a, CompactionTriggerPressure); err != nil {
166 t.Fatalf("small-window pressure maintenance: %v", err)
167 }
168 if len(prov.requests) != 1 {
169 t.Fatalf("summary requests = %d, want 1", len(prov.requests))
170 }
171 req := prov.requests[0]
172 if req.MaxTokens != window/4 {
173 t.Fatalf("summary max tokens = %d, want scaled budget %d", req.MaxTokens, window/4)
174 }
175 if got := a.estimatedRequestTokens(req) + req.MaxTokens + protocolReserveTokens; got > window {
176 t.Fatalf("summary request total = %d, exceeds small window %d", got, window)
177 }
178 }
179
180 func TestPressureNoSafePrefixRecordsBudgetReason(t *testing.T) {
181 const window = 10_000
182 prov := &opaqueWindowProvider{}
183 a := agentOverForceWindow(t, prov, smallWindowPressureSession(), window)
184
185 _, err := a.contextManager().Prepare(context.Background(), ContextPreparePolicy{
186 Trigger: CompactionTriggerPressure, Instructions: strings.Repeat("preserve this focus ", window),
187 })
188 if err != nil {
189 t.Fatalf("pressure maintenance should soft-skip: %v", err)
190 }
191 if len(prov.requests) != 0 {
192 t.Fatalf("summary requests = %d, want none when no prefix fits", len(prov.requests))
193 }
194 receipt := a.sess.compactionState.LastReceipt
195 if receipt == nil || receipt.Status != "blocked" || !strings.Contains(receipt.Reason, "no balanced prefix leaves enough room") {
196 t.Fatalf("receipt = %+v, want precise summary-budget reason", receipt)
197 }
198 }
199
199 lines GO