Capture subprocess results separately from diagnostics
This commit is contained in:
@@ -46,6 +46,8 @@ The final stage verifies the complete repository.
|
|||||||
|
|
||||||
## Stage 1: Add supervised stdout result capture
|
## Stage 1: Add supervised stdout result capture
|
||||||
|
|
||||||
|
**Status: Complete.**
|
||||||
|
|
||||||
**Purpose:** Capture native stdout products without applying diagnostic
|
**Purpose:** Capture native stdout products without applying diagnostic
|
||||||
redaction or the diagnostic-size limit to their bytes.
|
redaction or the diagnostic-size limit to their bytes.
|
||||||
|
|
||||||
|
|||||||
@@ -215,7 +215,10 @@ func (w *diagnosticWriter) reachLimit() error {
|
|||||||
w.logs.mu.Lock()
|
w.logs.mu.Lock()
|
||||||
if w.logs.limit == nil {
|
if w.logs.limit == nil {
|
||||||
w.logs.limit = limit
|
w.logs.limit = limit
|
||||||
w.logs.limits <- limit
|
select {
|
||||||
|
case w.logs.limits <- limit:
|
||||||
|
default:
|
||||||
|
}
|
||||||
}
|
}
|
||||||
w.logs.mu.Unlock()
|
w.logs.mu.Unlock()
|
||||||
return limit
|
return limit
|
||||||
|
|||||||
58
internal/adapters/subprocess/result.go
Normal file
58
internal/adapters/subprocess/result.go
Normal file
@@ -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
|
||||||
|
}
|
||||||
138
internal/adapters/subprocess/result_test.go
Normal file
138
internal/adapters/subprocess/result_test.go
Normal file
@@ -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(), "<redacted>") {
|
||||||
|
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), "<redacted>") {
|
||||||
|
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 }
|
||||||
@@ -3,6 +3,7 @@ package subprocess
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -20,6 +21,8 @@ type RunRequest struct {
|
|||||||
Timeout time.Duration
|
Timeout time.Duration
|
||||||
StdoutLogPath string
|
StdoutLogPath string
|
||||||
StderrLogPath string
|
StderrLogPath string
|
||||||
|
StdoutResult io.Writer
|
||||||
|
StdoutResultLimit int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// RunResult captures subprocess execution details.
|
// RunResult captures subprocess execution details.
|
||||||
@@ -51,7 +54,11 @@ func Run(ctx context.Context, req RunRequest) (RunResult, error) {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
childEnv := buildChildEnvironment(os.Environ(), req.EnvOverrides)
|
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 {
|
if err != nil {
|
||||||
return RunResult{}, err
|
return RunResult{}, err
|
||||||
}
|
}
|
||||||
@@ -61,6 +68,11 @@ func Run(ctx context.Context, req RunRequest) (RunResult, error) {
|
|||||||
cmd.Dir = req.WorkingDir
|
cmd.Dir = req.WorkingDir
|
||||||
cmd.Env = childEnv
|
cmd.Env = childEnv
|
||||||
cmd.Stdout = logs.Stdout
|
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
|
cmd.Stderr = logs.Stderr
|
||||||
outcome := executeOwnedCommand(runCtx, cmd, logs.Limits())
|
outcome := executeOwnedCommand(runCtx, cmd, logs.Limits())
|
||||||
cleanupErr := joinErrors(outcome.cleanupErr, logs.Flush())
|
cleanupErr := joinErrors(outcome.cleanupErr, logs.Flush())
|
||||||
@@ -68,18 +80,28 @@ func Run(ctx context.Context, req RunRequest) (RunResult, error) {
|
|||||||
if captureLimit == nil {
|
if captureLimit == nil {
|
||||||
captureLimit = logs.Limit()
|
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.Duration = result.CompletedAt.Sub(result.StartedAt)
|
||||||
result.TimedOut = outcome.reason == executionDeadline
|
result.TimedOut = outcome.reason == executionDeadline
|
||||||
result.Canceled = outcome.reason == executionCanceled
|
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
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
stderrTail := logs.stderr.Tail()
|
stderrTail := logs.stderr.Tail()
|
||||||
diagnostics := buildDiagnostics(req, result, stderrTail)
|
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 captureLimit != nil {
|
||||||
if cause := joinErrors(outcome.waitErr, cleanupErr); cause != nil {
|
if cause := joinErrors(outcome.waitErr, cleanupErr); cause != nil {
|
||||||
return result, fmt.Errorf("%w (%s): %w", captureLimit, diagnostics, cause)
|
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.ExitCode,
|
||||||
result.TimedOut,
|
result.TimedOut,
|
||||||
result.Canceled,
|
result.Canceled,
|
||||||
req.StdoutLogPath,
|
result.StdoutLogPath,
|
||||||
req.StderrLogPath,
|
req.StderrLogPath,
|
||||||
)
|
)
|
||||||
if strings.TrimSpace(stderrTail) == "" {
|
if strings.TrimSpace(stderrTail) == "" {
|
||||||
|
|||||||
@@ -604,6 +604,13 @@ func TestSubprocessHelper(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch mode {
|
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":
|
case "success":
|
||||||
_, _ = os.Stdout.WriteString(os.Getenv("SUBPROCESS_HELPER_STDOUT") + "\n")
|
_, _ = os.Stdout.WriteString(os.Getenv("SUBPROCESS_HELPER_STDOUT") + "\n")
|
||||||
_, _ = os.Stderr.WriteString(os.Getenv("SUBPROCESS_HELPER_STDERR") + "\n")
|
_, _ = os.Stderr.WriteString(os.Getenv("SUBPROCESS_HELPER_STDERR") + "\n")
|
||||||
|
|||||||
Reference in New Issue
Block a user