diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 8b38bcd..9497d81 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -46,6 +46,8 @@ The final stage verifies the complete repository. ## Stage 1: Add supervised stdout result capture +**Status: Complete.** + **Purpose:** Capture native stdout products without applying diagnostic redaction or the diagnostic-size limit to their bytes. diff --git a/internal/adapters/subprocess/diagnostics.go b/internal/adapters/subprocess/diagnostics.go index eba5c91..9afeca9 100644 --- a/internal/adapters/subprocess/diagnostics.go +++ b/internal/adapters/subprocess/diagnostics.go @@ -215,7 +215,10 @@ func (w *diagnosticWriter) reachLimit() error { w.logs.mu.Lock() if w.logs.limit == nil { w.logs.limit = limit - w.logs.limits <- limit + select { + case w.logs.limits <- limit: + default: + } } w.logs.mu.Unlock() return limit diff --git a/internal/adapters/subprocess/result.go b/internal/adapters/subprocess/result.go new file mode 100644 index 0000000..3ab9d13 --- /dev/null +++ b/internal/adapters/subprocess/result.go @@ -0,0 +1,58 @@ +package subprocess + +import ( + "fmt" + "io" + "sync" +) + +// boundedResultWriter preserves result bytes and reports failures to the process +// supervisor. Its target remains owned by the caller. +type boundedResultWriter struct { + target io.Writer + limit int64 + owner string + abort chan<- error + written int64 + mu sync.Mutex + err error +} + +func (w *boundedResultWriter) Write(data []byte) (int, error) { + remaining := w.limit - w.written + if remaining < 0 { + remaining = 0 + } + accepted := data + if int64(len(accepted)) > remaining { + accepted = accepted[:remaining] + } + n, err := w.target.Write(accepted) + w.written += int64(n) + if err == nil && n != len(accepted) { + err = io.ErrShortWrite + } + if err != nil { + err = fmt.Errorf("%s stdout result capture: %w", w.owner, err) + } else if len(accepted) != len(data) { + err = fmt.Errorf("stdout result capture for %s exceeded %d bytes", w.owner, w.limit) + } + if err != nil { + w.mu.Lock() + if w.err == nil { + w.err = err + select { + case w.abort <- err: + default: + } + } + w.mu.Unlock() + } + return n, err +} + +func (w *boundedResultWriter) Err() error { + w.mu.Lock() + defer w.mu.Unlock() + return w.err +} diff --git a/internal/adapters/subprocess/result_test.go b/internal/adapters/subprocess/result_test.go new file mode 100644 index 0000000..47ab573 --- /dev/null +++ b/internal/adapters/subprocess/result_test.go @@ -0,0 +1,138 @@ +package subprocess + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestRunCapturesResultSeparatelyFromDiagnostics(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + const secret = "synthetic-result-secret" + dir := t.TempDir() + var result bytes.Buffer + req := RunRequest{ + Executable: exe, Args: []string{"-test.run=^TestSubprocessHelper$", "--", "echoenv"}, + EnvOverrides: map[string]string{"GO_WANT_SUBPROCESS_HELPER": "1", "SUBPROCESS_HELPER_ENV_KEY": "API_KEY", "API_KEY": secret}, + StdoutResult: &result, StdoutResultLimit: 1024, + StdoutLogPath: filepath.Join(dir, "stdout.log"), StderrLogPath: filepath.Join(dir, "stderr.log"), + } + runResult, err := Run(context.Background(), req) + if err == nil || strings.Contains(err.Error(), secret) || !strings.Contains(err.Error(), "") { + t.Fatalf("error = %v", err) + } + if result.String() != secret { + t.Fatalf("result = %q", result.String()) + } + if runResult.StdoutLogPath != "" { + t.Fatalf("stdout log = %q", runResult.StdoutLogPath) + } + if _, err := os.Stat(req.StdoutLogPath); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("stdout log exists: %v", err) + } + stderr, err := os.ReadFile(req.StderrLogPath) + if err != nil || strings.Contains(string(stderr), secret) || !strings.Contains(string(stderr), "") { + t.Fatalf("stderr = %q, %v", stderr, err) + } +} + +func TestRunResultBudget(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + limit int64 + want string + overflow bool + }{ + {"exact", 6, "hello\n", false}, {"overflow", 5, "hello", true}, + } { + t.Run(tc.name, func(t *testing.T) { + var result bytes.Buffer + req := RunRequest{Executable: exe, Args: []string{"-test.run=^TestSubprocessHelper$", "--", "success"}, EnvOverrides: map[string]string{"GO_WANT_SUBPROCESS_HELPER": "1", "SUBPROCESS_HELPER_STDOUT": "hello"}, DiagnosticOwner: "example adapter", StdoutResult: &result, StdoutResultLimit: tc.limit} + _, err := Run(context.Background(), req) + if (err != nil) != tc.overflow { + t.Fatalf("Run error = %v", err) + } + if tc.overflow && (!strings.Contains(err.Error(), "example adapter") || !strings.Contains(err.Error(), "stdout") || !strings.Contains(err.Error(), "5 bytes")) { + t.Fatalf("error = %v", err) + } + if result.String() != tc.want { + t.Fatalf("result = %q, want %q", result.String(), tc.want) + } + }) + } +} + +func TestRunResultPreservesBinaryBytes(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + var result bytes.Buffer + req := RunRequest{Executable: exe, Args: []string{"-test.run=^TestSubprocessHelper$", "--", "binary-result"}, EnvOverrides: map[string]string{"GO_WANT_SUBPROCESS_HELPER": "1"}, StdoutResult: &result, StdoutResultLimit: 4} + if _, err := Run(context.Background(), req); err != nil { + t.Fatal(err) + } + if !bytes.Equal(result.Bytes(), []byte{0, 255, '\n', 128}) { + t.Fatalf("result = %v", result.Bytes()) + } +} + +func TestRunResultCanExceedDiagnosticLimit(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + var result bytes.Buffer + req := RunRequest{Executable: exe, Args: []string{"-test.run=^TestSubprocessHelper$", "--", "spam"}, EnvOverrides: map[string]string{"GO_WANT_SUBPROCESS_HELPER": "1", "SUBPROCESS_HELPER_CHUNKS": "129"}, StdoutResult: &result, StdoutResultLimit: 129 * 64 * 1024} + if _, err := Run(context.Background(), req); err != nil { + t.Fatal(err) + } + if int64(result.Len()) <= MaxStdoutDiagnosticBytes || !bytes.Equal(result.Bytes(), bytes.Repeat([]byte("x"), 129*64*1024)) { + t.Fatalf("unexpected result length/content: %d", result.Len()) + } +} + +type failingResultWriter struct{ err error } + +func (w failingResultWriter) Write([]byte) (int, error) { return 0, w.err } + +func TestRunResultWriterFailureAbortsChild(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + want := errors.New("synthetic write failure") + req := RunRequest{Executable: exe, Args: []string{"-test.run=^TestSubprocessHelper$", "--", "result-wait"}, EnvOverrides: map[string]string{"GO_WANT_SUBPROCESS_HELPER": "1"}, StdoutResult: failingResultWriter{want}, StdoutResultLimit: 100, Timeout: 8 * time.Second} + start := time.Now() + _, err = Run(context.Background(), req) + if !errors.Is(err, want) { + t.Fatalf("error = %v, want writer error", err) + } + if time.Since(start) > 5*time.Second { + t.Fatalf("child was not terminated promptly") + } +} + +func TestResultWriterReportsShortWrite(t *testing.T) { + w := &boundedResultWriter{target: shortResultWriter{}, limit: 5, abort: make(chan error, 1)} + if _, err := w.Write([]byte("abc")); !errors.Is(err, io.ErrShortWrite) { + t.Fatalf("error = %v", err) + } +} + +type shortResultWriter struct{} + +func (shortResultWriter) Write(p []byte) (int, error) { return len(p) - 1, nil } diff --git a/internal/adapters/subprocess/run.go b/internal/adapters/subprocess/run.go index 2504e27..0464f32 100644 --- a/internal/adapters/subprocess/run.go +++ b/internal/adapters/subprocess/run.go @@ -3,6 +3,7 @@ package subprocess import ( "context" "fmt" + "io" "os" "os/exec" "strings" @@ -20,6 +21,8 @@ type RunRequest struct { Timeout time.Duration StdoutLogPath string StderrLogPath string + StdoutResult io.Writer + StdoutResultLimit int64 } // RunResult captures subprocess execution details. @@ -51,7 +54,11 @@ func Run(ctx context.Context, req RunRequest) (RunResult, error) { defer cancel() childEnv := buildChildEnvironment(os.Environ(), req.EnvOverrides) - logs, err := openLogWriters(req.StdoutLogPath, req.StderrLogPath, req.diagnosticOwner(), sensitiveEnvironmentValues(childEnv, req.SensitiveEnvNames)) + stdoutLogPath := req.StdoutLogPath + if req.StdoutResult != nil { + stdoutLogPath = "" + } + logs, err := openLogWriters(stdoutLogPath, req.StderrLogPath, req.diagnosticOwner(), sensitiveEnvironmentValues(childEnv, req.SensitiveEnvNames)) if err != nil { return RunResult{}, err } @@ -61,6 +68,11 @@ func Run(ctx context.Context, req RunRequest) (RunResult, error) { cmd.Dir = req.WorkingDir cmd.Env = childEnv cmd.Stdout = logs.Stdout + var resultWriter *boundedResultWriter + if req.StdoutResult != nil { + resultWriter = &boundedResultWriter{target: req.StdoutResult, limit: req.StdoutResultLimit, owner: req.diagnosticOwner(), abort: logs.limits} + cmd.Stdout = resultWriter + } cmd.Stderr = logs.Stderr outcome := executeOwnedCommand(runCtx, cmd, logs.Limits()) cleanupErr := joinErrors(outcome.cleanupErr, logs.Flush()) @@ -68,18 +80,28 @@ func Run(ctx context.Context, req RunRequest) (RunResult, error) { if captureLimit == nil { captureLimit = logs.Limit() } - result := RunResult{ExitCode: outcome.exitCode, StartedAt: outcome.startedAt, CompletedAt: outcome.completedAt, StdoutLogPath: req.StdoutLogPath, StderrLogPath: req.StderrLogPath} + result := RunResult{ExitCode: outcome.exitCode, StartedAt: outcome.startedAt, CompletedAt: outcome.completedAt, StdoutLogPath: stdoutLogPath, StderrLogPath: req.StderrLogPath} result.Duration = result.CompletedAt.Sub(result.StartedAt) result.TimedOut = outcome.reason == executionDeadline result.Canceled = outcome.reason == executionCanceled - if outcome.reason == executionNaturalExit && outcome.waitErr == nil && cleanupErr == nil { + var resultErr error + if resultWriter != nil { + resultErr = resultWriter.Err() + } + if outcome.reason == executionNaturalExit && outcome.waitErr == nil && cleanupErr == nil && resultErr == nil && captureLimit == nil { return result, nil } stderrTail := logs.stderr.Tail() diagnostics := buildDiagnostics(req, result, stderrTail) + if resultErr != nil { + if cause := joinErrors(outcome.waitErr, cleanupErr); cause != nil { + return result, fmt.Errorf("%w (%s): %w", resultErr, diagnostics, cause) + } + return result, fmt.Errorf("%w (%s)", resultErr, diagnostics) + } if captureLimit != nil { if cause := joinErrors(outcome.waitErr, cleanupErr); cause != nil { return result, fmt.Errorf("%w (%s): %w", captureLimit, diagnostics, cause) @@ -115,7 +137,7 @@ func buildDiagnostics(req RunRequest, result RunResult, stderrTail string) strin result.ExitCode, result.TimedOut, result.Canceled, - req.StdoutLogPath, + result.StdoutLogPath, req.StderrLogPath, ) if strings.TrimSpace(stderrTail) == "" { diff --git a/internal/adapters/subprocess/run_test.go b/internal/adapters/subprocess/run_test.go index d4e710b..0bb6204 100644 --- a/internal/adapters/subprocess/run_test.go +++ b/internal/adapters/subprocess/run_test.go @@ -604,6 +604,13 @@ func TestSubprocessHelper(t *testing.T) { } switch mode { + case "binary-result": + _, _ = os.Stdout.Write([]byte{0, 255, '\n', 128}) + os.Exit(0) + case "result-wait": + _, _ = os.Stdout.WriteString("result") + time.Sleep(10 * time.Second) + os.Exit(0) case "success": _, _ = os.Stdout.WriteString(os.Getenv("SUBPROCESS_HELPER_STDOUT") + "\n") _, _ = os.Stderr.WriteString(os.Getenv("SUBPROCESS_HELPER_STDERR") + "\n")