| 1 | package engine |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "runtime" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | func TestHeadBufferBoundsAndDrains(t *testing.T) { |
| 16 | t.Run("under and exact limit", func(t *testing.T) { |
| 17 | b := newHeadBuffer(10) |
| 18 | n, err := b.Write([]byte("hello")) |
| 19 | if err != nil || n != 5 { |
| 20 | t.Fatalf("Write = (%d, %v), want (5, nil)", n, err) |
| 21 | } |
| 22 | n, err = b.Write([]byte("world")) |
| 23 | if err != nil || n != 5 { |
| 24 | t.Fatalf("Write = (%d, %v), want (5, nil)", n, err) |
| 25 | } |
| 26 | if b.Truncated() || b.Total() != 10 || string(b.Bytes()) != "helloworld" { |
| 27 | t.Fatalf("state = truncated:%v total:%d bytes:%q", b.Truncated(), b.Total(), b.Bytes()) |
| 28 | } |
| 29 | }) |
| 30 | |
| 31 | t.Run("overflow drains without error and caps allocation", func(t *testing.T) { |
| 32 | const limit = 16 |
| 33 | b := newHeadBuffer(limit) |
| 34 | payload := bytes.Repeat([]byte("abcdefghij"), 100) // 1000 bytes |
| 35 | for off := 0; off < len(payload); off += 7 { |
| 36 | end := min(off+7, len(payload)) |
| 37 | n, err := b.Write(payload[off:end]) |
| 38 | if err != nil || n != end-off { |
| 39 | t.Fatalf("Write(%d) = (%d, %v)", end-off, n, err) |
| 40 | } |
| 41 | } |
| 42 | if !b.Truncated() { |
| 43 | t.Fatal("Truncated() = false, want true") |
| 44 | } |
| 45 | if b.Total() != int64(len(payload)) { |
| 46 | t.Fatalf("Total() = %d, want %d", b.Total(), len(payload)) |
| 47 | } |
| 48 | if !bytes.Equal(b.Bytes(), payload[:limit]) { |
| 49 | t.Fatalf("Bytes() = %q, want %q", b.Bytes(), payload[:limit]) |
| 50 | } |
| 51 | if cap(b.Bytes()) > limit { |
| 52 | t.Fatalf("cap(Bytes()) = %d > limit %d", cap(b.Bytes()), limit) |
| 53 | } |
| 54 | }) |
| 55 | |
| 56 | t.Run("zero limit drains all", func(t *testing.T) { |
| 57 | b := newHeadBuffer(0) |
| 58 | n, err := b.Write([]byte("abc")) |
| 59 | if err != nil || n != 3 { |
| 60 | t.Fatalf("Write = (%d, %v), want (3, nil)", n, err) |
| 61 | } |
| 62 | if !b.Truncated() || b.Total() != 3 || len(b.Bytes()) != 0 { |
| 63 | t.Fatalf("state = truncated:%v total:%d bytes:%q", b.Truncated(), b.Total(), b.Bytes()) |
| 64 | } |
| 65 | }) |
| 66 | } |
| 67 | |
| 68 | func TestTailBufferBoundsAndRetainsLatest(t *testing.T) { |
| 69 | t.Run("under and exact limit", func(t *testing.T) { |
| 70 | b := newTailBuffer(8) |
| 71 | _, _ = b.Write([]byte("abcd")) |
| 72 | _, _ = b.Write([]byte("efgh")) |
| 73 | if b.Truncated() || b.Total() != 8 || string(b.Bytes()) != "abcdefgh" { |
| 74 | t.Fatalf("state = truncated:%v total:%d bytes:%q", b.Truncated(), b.Total(), b.Bytes()) |
| 75 | } |
| 76 | }) |
| 77 | |
| 78 | t.Run("ring retains exact trailing bytes across varied chunk sizes", func(t *testing.T) { |
| 79 | for _, limit := range []int{1, 5, 13, 64} { |
| 80 | b := newTailBuffer(limit) |
| 81 | var full bytes.Buffer |
| 82 | chunkSizes := []int{1, 2, 3, 4, 7, 11, 17, 29, 3, 1, 5, 19, 100} |
| 83 | ch := byte('a') |
| 84 | for _, sz := range chunkSizes { |
| 85 | chunk := make([]byte, sz) |
| 86 | for i := range chunk { |
| 87 | chunk[i] = ch |
| 88 | ch = 'a' + (ch-'a'+1)%26 |
| 89 | } |
| 90 | n, err := b.Write(chunk) |
| 91 | if err != nil || n != sz { |
| 92 | t.Fatalf("limit=%d Write(%d) = (%d, %v)", limit, sz, n, err) |
| 93 | } |
| 94 | full.Write(chunk) |
| 95 | all := full.Bytes() |
| 96 | want := all |
| 97 | wantTrunc := false |
| 98 | if len(all) > limit { |
| 99 | want = all[len(all)-limit:] |
| 100 | wantTrunc = true |
| 101 | } |
| 102 | if b.Truncated() != wantTrunc { |
| 103 | t.Fatalf("limit=%d total=%d Truncated()=%v, want %v", limit, len(all), b.Truncated(), wantTrunc) |
| 104 | } |
| 105 | if b.Total() != int64(len(all)) { |
| 106 | t.Fatalf("limit=%d Total()=%d, want %d", limit, b.Total(), len(all)) |
| 107 | } |
| 108 | if got := b.Bytes(); !bytes.Equal(got, want) { |
| 109 | t.Fatalf("limit=%d total=%d Bytes()=%q, want %q", limit, len(all), got, want) |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | }) |
| 114 | |
| 115 | t.Run("single write larger than limit", func(t *testing.T) { |
| 116 | b := newTailBuffer(5) |
| 117 | n, err := b.Write([]byte("0123456789")) |
| 118 | if err != nil || n != 10 { |
| 119 | t.Fatalf("Write = (%d, %v), want (10, nil)", n, err) |
| 120 | } |
| 121 | if !b.Truncated() || b.Total() != 10 || string(b.Bytes()) != "56789" { |
| 122 | t.Fatalf("state = truncated:%v total:%d bytes:%q", b.Truncated(), b.Total(), b.Bytes()) |
| 123 | } |
| 124 | }) |
| 125 | |
| 126 | t.Run("zero limit drains all", func(t *testing.T) { |
| 127 | b := newTailBuffer(0) |
| 128 | n, err := b.Write([]byte("abc")) |
| 129 | if err != nil || n != 3 { |
| 130 | t.Fatalf("Write = (%d, %v), want (3, nil)", n, err) |
| 131 | } |
| 132 | if !b.Truncated() || b.Total() != 3 || len(b.Bytes()) != 0 { |
| 133 | t.Fatalf("state = truncated:%v total:%d bytes:%q", b.Truncated(), b.Total(), b.Bytes()) |
| 134 | } |
| 135 | }) |
| 136 | } |
| 137 | |
| 138 | func makeFloodStub(t *testing.T, script string) string { |
| 139 | t.Helper() |
| 140 | if runtime.GOOS == "windows" { |
| 141 | t.Skip("POSIX shell fixture") |
| 142 | } |
| 143 | path := filepath.Join(t.TempDir(), "python3-flood-stub.sh") |
| 144 | if err := os.WriteFile(path, []byte(script), 0o755); err != nil { |
| 145 | t.Fatalf("write stub: %v", err) |
| 146 | } |
| 147 | return path |
| 148 | } |
| 149 | |
| 150 | // TestRunStdoutLimitDrainsWithoutDeadlockAndErrors verifies that a subprocess |
| 151 | // emitting far more than the OS pipe buffer and MaxStdoutBytes is drained |
| 152 | // without stalling, stays capped in memory, and fails with ErrStdoutLimitExceeded. |
| 153 | func TestRunStdoutLimitDrainsWithoutDeadlockAndErrors(t *testing.T) { |
| 154 | // Write 256 KiB (> 64 KiB pipe buffer) starting with a known marker. |
| 155 | stub := makeFloodStub(t, `#!/bin/sh |
| 156 | printf 'HEAD_MARKER:' |
| 157 | dd if=/dev/zero bs=4096 count=64 2>/dev/null | tr '\0' 'X' |
| 158 | exit "${STUB_EXIT_CODE:-0}" |
| 159 | `) |
| 160 | cache := stageCache(t) |
| 161 | |
| 162 | for _, tc := range []struct { |
| 163 | name string |
| 164 | exitCode string |
| 165 | wantCode int |
| 166 | }{ |
| 167 | {"clean exit overflow", "0", 0}, |
| 168 | {"non-zero exit overflow", "2", 2}, |
| 169 | } { |
| 170 | t.Run(tc.name, func(t *testing.T) { |
| 171 | t.Setenv("STUB_EXIT_CODE", tc.exitCode) |
| 172 | started := time.Now() |
| 173 | res, err := Run(context.Background(), RunOptions{ |
| 174 | PythonPath: stub, |
| 175 | CacheDir: cache, |
| 176 | Timeout: 5 * time.Second, |
| 177 | MaxStdoutBytes: 1024, |
| 178 | }) |
| 179 | if time.Since(started) > 3*time.Second { |
| 180 | t.Fatalf("Run took %s; oversized stdout may have stalled pipe", time.Since(started)) |
| 181 | } |
| 182 | if !errors.Is(err, ErrStdoutLimitExceeded) { |
| 183 | t.Fatalf("Run error = %v, want ErrStdoutLimitExceeded", err) |
| 184 | } |
| 185 | if res == nil { |
| 186 | t.Fatal("Run result is nil; want bounded result alongside overflow error") |
| 187 | } |
| 188 | if !res.StdoutTruncated { |
| 189 | t.Fatal("StdoutTruncated = false, want true") |
| 190 | } |
| 191 | if len(res.Stdout) != 1024 { |
| 192 | t.Fatalf("len(Stdout) = %d, want 1024", len(res.Stdout)) |
| 193 | } |
| 194 | if !strings.HasPrefix(string(res.Stdout), "HEAD_MARKER:XXXX") { |
| 195 | t.Fatalf("Stdout prefix = %q, want HEAD_MARKER:XXXX...", res.Stdout[:24]) |
| 196 | } |
| 197 | if res.ExitCode != tc.wantCode { |
| 198 | t.Fatalf("ExitCode = %d, want %d", res.ExitCode, tc.wantCode) |
| 199 | } |
| 200 | if tc.wantCode != 0 && !strings.Contains(err.Error(), "exit code 2") { |
| 201 | t.Fatalf("error %q did not preserve non-zero exit code", err) |
| 202 | } |
| 203 | }) |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | // TestRunStderrLimitRetainsTailWithoutFailingCleanRun verifies that verbose |
| 208 | // stderr exceeding MaxStderrBytes is drained without stalling, keeps the |
| 209 | // trailing diagnostics (including strict-exit receipts), and does not turn a |
| 210 | // healthy exit-0 run into an error. |
| 211 | func TestRunStderrLimitRetainsTailWithoutFailingCleanRun(t *testing.T) { |
| 212 | stub := makeFloodStub(t, `#!/bin/sh |
| 213 | printf 'clean report\n' |
| 214 | dd if=/dev/zero bs=4096 count=64 2>/dev/null | tr '\0' 'E' >&2 |
| 215 | printf '\n[last30days] strict-exit: degraded sources: x\nFINAL_MARKER\n' >&2 |
| 216 | exit "${STUB_EXIT_CODE:-0}" |
| 217 | `) |
| 218 | cache := stageCache(t) |
| 219 | |
| 220 | t.Run("exit 0 succeeds with bounded stderr tail", func(t *testing.T) { |
| 221 | t.Setenv("STUB_EXIT_CODE", "0") |
| 222 | res, err := Run(context.Background(), RunOptions{ |
| 223 | PythonPath: stub, |
| 224 | CacheDir: cache, |
| 225 | Timeout: 5 * time.Second, |
| 226 | MaxStderrBytes: 1024, |
| 227 | }) |
| 228 | if err != nil { |
| 229 | t.Fatalf("Run: %v", err) |
| 230 | } |
| 231 | if string(res.Stdout) != "clean report\n" || res.StdoutTruncated { |
| 232 | t.Fatalf("stdout = %q (truncated=%v), want clean report", res.Stdout, res.StdoutTruncated) |
| 233 | } |
| 234 | if !res.StderrTruncated { |
| 235 | t.Fatal("StderrTruncated = false, want true") |
| 236 | } |
| 237 | if len(res.Stderr) != 1024 { |
| 238 | t.Fatalf("len(Stderr) = %d, want 1024", len(res.Stderr)) |
| 239 | } |
| 240 | if !strings.HasSuffix(string(res.Stderr), "[last30days] strict-exit: degraded sources: x\nFINAL_MARKER\n") { |
| 241 | t.Fatalf("stderr tail lost final markers: %q", res.Stderr[len(res.Stderr)-80:]) |
| 242 | } |
| 243 | }) |
| 244 | |
| 245 | t.Run("exit 3 preserves strict-exit receipt in bounded stderr tail", func(t *testing.T) { |
| 246 | t.Setenv("STUB_EXIT_CODE", "3") |
| 247 | res, err := Run(context.Background(), RunOptions{ |
| 248 | PythonPath: stub, |
| 249 | CacheDir: cache, |
| 250 | Timeout: 5 * time.Second, |
| 251 | MaxStderrBytes: 1024, |
| 252 | }) |
| 253 | if err == nil { |
| 254 | t.Fatal("expected error for exit code 3") |
| 255 | } |
| 256 | if res == nil || res.ExitCode != 3 || !res.StderrTruncated || len(res.Stderr) != 1024 { |
| 257 | t.Fatalf("unexpected result: %+v", res) |
| 258 | } |
| 259 | if !strings.Contains(string(res.Stderr), "[last30days] strict-exit: degraded sources: x") { |
| 260 | t.Fatalf("stderr tail lost strict-exit receipt: %q", res.Stderr) |
| 261 | } |
| 262 | }) |
| 263 | } |
| 264 |