返回 last30days-skill
output_limit.go
根目录 / mcp / internal / engine / output_limit.go
1 package engine
2
3 import (
4 "errors"
5 "io"
6 "os"
7 "sync"
8 "time"
9 )
10
11 // DefaultMaxStdoutBytes caps buffered engine stdout (16 MiB). Excess bytes are
12 // drained so child pipes never stall, and Run reports ErrStdoutLimitExceeded.
13 const DefaultMaxStdoutBytes = 16 << 20
14
15 // DefaultMaxStderrBytes caps retained engine stderr (2 MiB), preserving the
16 // trailing bytes so tracebacks and strict-exit receipts survive verbose runs.
17 const DefaultMaxStderrBytes = 2 << 20
18
19 // maxPythonProbeOutputBytes caps stdout read during `python3 -I -S -c` version
20 // probing so an adversarial or misconfigured executable on PATH cannot exhaust
21 // memory before the probe timeout fires.
22 const maxPythonProbeOutputBytes = 4 << 10
23
24 // ErrStdoutLimitExceeded is returned by Run when subprocess stdout exceeds the
25 // configured MaxStdoutBytes (or DefaultMaxStdoutBytes) ceiling.
26 var ErrStdoutLimitExceeded = errors.New("engine: subprocess stdout exceeded limit")
27
28 func resolveOutputLimit(explicit, fallback int) int {
29 if explicit > 0 {
30 return explicit
31 }
32 return fallback
33 }
34
35 // appendCapped appends src to dst while never growing backing capacity past limit.
36 func appendCapped(dst, src []byte, limit int) []byte {
37 need := len(dst) + len(src)
38 if need <= cap(dst) {
39 return append(dst, src...)
40 }
41 newCap := cap(dst) * 2
42 if newCap < need {
43 newCap = need
44 }
45 if newCap > limit {
46 newCap = limit
47 }
48 grown := make([]byte, len(dst), newCap)
49 copy(grown, dst)
50 return append(grown, src...)
51 }
52
53 // headBuffer retains up to limit leading bytes and drains any excess bytes
54 // without returning a write error so child stdout pipes never deadlock.
55 type headBuffer struct {
56 limit int
57 buf []byte
58 total int64
59 truncated bool
60 }
61
62 func newHeadBuffer(limit int) *headBuffer {
63 if limit < 0 {
64 limit = 0
65 }
66 return &headBuffer{limit: limit}
67 }
68
69 func (b *headBuffer) Write(p []byte) (int, error) {
70 n := len(p)
71 if n == 0 {
72 return 0, nil
73 }
74 b.total += int64(n)
75 remaining := b.limit - len(b.buf)
76 if remaining <= 0 {
77 b.truncated = true
78 return n, nil
79 }
80 if n <= remaining {
81 b.buf = appendCapped(b.buf, p, b.limit)
82 return n, nil
83 }
84 b.buf = appendCapped(b.buf, p[:remaining], b.limit)
85 b.truncated = true
86 return n, nil
87 }
88
89 func (b *headBuffer) Bytes() []byte { return b.buf }
90 func (b *headBuffer) Truncated() bool { return b.truncated }
91 func (b *headBuffer) Total() int64 { return b.total }
92
93 // tailBuffer retains up to limit trailing bytes using lazy linear storage
94 // while under the limit and switching to a fixed-size ring buffer on overflow.
95 // Excess bytes are always drained without write errors so child pipes never stall.
96 type tailBuffer struct {
97 limit int
98 buf []byte
99 ring []byte
100 pos int
101 total int64
102 truncated bool
103 }
104
105 func newTailBuffer(limit int) *tailBuffer {
106 if limit < 0 {
107 limit = 0
108 }
109 return &tailBuffer{limit: limit}
110 }
111
112 func (b *tailBuffer) Write(p []byte) (int, error) {
113 n := len(p)
114 if n == 0 {
115 return 0, nil
116 }
117 b.total += int64(n)
118 if b.limit == 0 {
119 b.truncated = true
120 return n, nil
121 }
122 if !b.truncated && len(b.buf)+n <= b.limit {
123 b.buf = appendCapped(b.buf, p, b.limit)
124 return n, nil
125 }
126 b.truncated = true
127 if b.ring == nil {
128 b.ring = make([]byte, b.limit)
129 if n >= b.limit {
130 copy(b.ring, p[n-b.limit:])
131 b.pos = 0
132 b.buf = nil
133 return n, nil
134 }
135 keepFromBuf := b.limit - n
136 if keepFromBuf > len(b.buf) {
137 keepFromBuf = len(b.buf)
138 }
139 copied := copy(b.ring, b.buf[len(b.buf)-keepFromBuf:])
140 copy(b.ring[copied:], p)
141 b.pos = (copied + n) % b.limit
142 b.buf = nil
143 return n, nil
144 }
145 if n >= b.limit {
146 copy(b.ring, p[n-b.limit:])
147 b.pos = 0
148 return n, nil
149 }
150 first := copy(b.ring[b.pos:], p)
151 if first < n {
152 copy(b.ring, p[first:])
153 }
154 b.pos = (b.pos + n) % b.limit
155 return n, nil
156 }
157
158 func (b *tailBuffer) Bytes() []byte {
159 if !b.truncated {
160 return b.buf
161 }
162 if b.limit == 0 || b.ring == nil {
163 return nil
164 }
165 out := make([]byte, b.limit)
166 tail := copy(out, b.ring[b.pos:])
167 copy(out[tail:], b.ring[:b.pos])
168 return out
169 }
170
171 func (b *tailBuffer) Truncated() bool { return b.truncated }
172 func (b *tailBuffer) Total() int64 { return b.total }
173
174 // outputPipes attaches explicit *os.File pipes to cmd.Stdout and cmd.Stderr so
175 // output draining is decoupled from cmd.Wait() process reaping. That lets Unix
176 // keep the child leader unreaped (pinning its PID/PGID) until both pipe
177 // draining and any process-group cleanup signals have completed.
178 type outputPipes struct {
179 stdoutR, stdoutW *os.File
180 stderrR, stderrW *os.File
181 drainDone chan struct{}
182 closeReadOnce sync.Once
183 }
184
185 func newOutputPipes() (*outputPipes, error) {
186 stdoutR, stdoutW, err := os.Pipe()
187 if err != nil {
188 return nil, err
189 }
190 stderrR, stderrW, err := os.Pipe()
191 if err != nil {
192 _ = stdoutR.Close()
193 _ = stdoutW.Close()
194 return nil, err
195 }
196 return &outputPipes{
197 stdoutR: stdoutR,
198 stdoutW: stdoutW,
199 stderrR: stderrR,
200 stderrW: stderrW,
201 drainDone: make(chan struct{}),
202 }, nil
203 }
204
205 func (p *outputPipes) closeAll() {
206 _ = p.stdoutW.Close()
207 _ = p.stderrW.Close()
208 p.closeReadPipes()
209 }
210
211 func (p *outputPipes) closeReadPipes() {
212 p.closeReadOnce.Do(func() {
213 _ = p.stdoutR.Close()
214 _ = p.stderrR.Close()
215 })
216 }
217
218 func (p *outputPipes) startDraining(stdoutDst, stderrDst io.Writer) {
219 // Close the parent's write ends immediately so EOF arrives as soon as the
220 // child process and any descendants close their inherited write ends.
221 _ = p.stdoutW.Close()
222 _ = p.stderrW.Close()
223
224 var wg sync.WaitGroup
225 wg.Add(2)
226 go func() {
227 defer wg.Done()
228 _, _ = io.Copy(stdoutDst, p.stdoutR)
229 }()
230 go func() {
231 defer wg.Done()
232 _, _ = io.Copy(stderrDst, p.stderrR)
233 }()
234 go func() {
235 wg.Wait()
236 p.closeReadPipes()
237 close(p.drainDone)
238 }()
239 }
240
241 var closedDrainCh = func() chan struct{} {
242 ch := make(chan struct{})
243 close(ch)
244 return ch
245 }()
246
247 func normalizeDrain(drainDone <-chan struct{}, closeReadPipes func()) (<-chan struct{}, func()) {
248 if drainDone == nil {
249 drainDone = closedDrainCh
250 }
251 if closeReadPipes == nil {
252 closeReadPipes = func() {}
253 }
254 return drainDone, closeReadPipes
255 }
256
257 // finishDrain waits up to waitDelay for pipe draining to reach EOF, closing
258 // the parent read ends if waitDelay expires so detached out-of-group orphans
259 // cannot hang Run indefinitely. Reports whether draining had to be cut short.
260 func finishDrain(drainDone <-chan struct{}, closeReadPipes func(), waitDelay time.Duration) bool {
261 select {
262 case <-drainDone:
263 return false
264 default:
265 }
266 if waitDelay <= 0 {
267 closeReadPipes()
268 <-drainDone
269 return true
270 }
271 timer := time.NewTimer(waitDelay)
272 defer timer.Stop()
273 select {
274 case <-drainDone:
275 return false
276 case <-timer.C:
277 closeReadPipes()
278 <-drainDone
279 return true
280 }
281 }
282
282 lines GO