Avoid unnecessary reads when validating Scriptorium outputs

This commit is contained in:
2026-11-26 13:51:06 +00:00
parent 72eb597a72
commit 0a43b67847
3 changed files with 70 additions and 10 deletions

View File

@@ -11,7 +11,7 @@ are retained as scope decisions.
## Finding 1: Avoid full-file allocation for post-capture size checks ## Finding 1: Avoid full-file allocation for post-capture size checks
Status: Pending consideration. Status: Complete.
Priority: P3 — bounded memory and redundant I/O optimization; no demonstrated Priority: P3 — bounded memory and redundant I/O optimization; no demonstrated
incorrect result or release-blocking defect. incorrect result or release-blocking defect.
@@ -69,6 +69,21 @@ Retain focused tests for empty, oversized, nonregular, and failed outputs, and
valid/invalid preview JSON. Review the implementation's buffering directly; valid/invalid preview JSON. Review the implementation's buffering directly;
timing thresholds, allocator-count contracts, and benchmark gates are unnecessary. timing thresholds, allocator-count contracts, and benchmark gates are unnecessary.
### Resolution and verification
Generation validates the closed captured file with `os.Stat`, checking regular
file type, nonempty size, and the existing maximum without reading its payload.
Its post-capture validation uses O(1) extra memory. Preview performs one bounded
read and checks both nonempty content and JSON validity on that buffer.
Streaming limits, write/close error propagation, and stage-owned payload checks
and promotion remain unchanged.
Sparse-file tests cover empty, nonempty, exact-limit, and oversized outputs;
missing/nonregular output checks and an empty-preview case complement the
existing successful, invalid, and failed subprocess cases. Verification passed:
`go test ./...`, race-enabled Scriptorium/subprocess tests, Scriptorium package
vet, and `git diff --check` using Go 1.27.4.
## Stage-by-stage disposition ## Stage-by-stage disposition
| Stage | Algorithmic assessment | | Stage | Algorithmic assessment |
@@ -87,5 +102,5 @@ timing thresholds, allocator-count contracts, and benchmark gates are unnecessar
| 12 — Documentation | No algorithm implemented. Documentation introduces no additional algorithmic requirement relevant to this audit. | | 12 — Documentation | No algorithm implemented. Documentation introduces no additional algorithmic requirement relevant to this audit. |
No newly implemented quadratic-time algorithm or additional correctness defect No newly implemented quadratic-time algorithm or additional correctness defect
was identified within this scope. Finding 1 warrants consideration as a small, was identified within this scope. Finding 1 has been addressed by the
behavior-preserving follow-up. behavior-preserving follow-up described above.

View File

@@ -202,13 +202,13 @@ func (r *SubprocessRunner) RenderArtifact(ctx context.Context, req RenderArtifac
if runErr != nil { if runErr != nil {
return result, fmt.Errorf("run scriptorium render (binary=%q): %w", req.Binary, runErr) return result, fmt.Errorf("run scriptorium render (binary=%q): %w", req.Binary, runErr)
} }
if err := validateNonEmptyOutput(req.OutputPath); err != nil {
return result, fmt.Errorf("validate scriptorium render output %q: %w", req.OutputPath, err)
}
data, err := fileops.ReadFileBounded(req.OutputPath, MaxOutputFileBytes) data, err := fileops.ReadFileBounded(req.OutputPath, MaxOutputFileBytes)
if err != nil { if err != nil {
return result, fmt.Errorf("read scriptorium render output %q: %w", req.OutputPath, err) return result, fmt.Errorf("read scriptorium render output %q: %w", req.OutputPath, err)
} }
if len(data) == 0 {
return result, fmt.Errorf("validate scriptorium render output %q: file is empty", req.OutputPath)
}
if !json.Valid(data) { if !json.Valid(data) {
return result, fmt.Errorf("validate scriptorium render output %q: invalid JSON", req.OutputPath) return result, fmt.Errorf("validate scriptorium render output %q: invalid JSON", req.OutputPath)
} }
@@ -370,11 +370,17 @@ func writeInvocationConfig(path string, payload invocationPayload) error {
} }
func validateNonEmptyOutput(path string) error { func validateNonEmptyOutput(path string) error {
data, err := fileops.ReadFileBounded(path, MaxOutputFileBytes) info, err := os.Stat(path)
if err != nil { if err != nil {
return fmt.Errorf("scriptorium artifact output exceeds or cannot be read within %d-byte limit: %w", MaxOutputFileBytes, err) return fmt.Errorf("stat scriptorium artifact output: %w", err)
} }
if len(data) == 0 { if !info.Mode().IsRegular() {
return fmt.Errorf("scriptorium artifact output is not a regular file")
}
if info.Size() > MaxOutputFileBytes {
return fmt.Errorf("scriptorium artifact output exceeds %d-byte limit", MaxOutputFileBytes)
}
if info.Size() == 0 {
return fmt.Errorf("file is empty") return fmt.Errorf("file is empty")
} }
return nil return nil

View File

@@ -183,7 +183,7 @@ func TestSubprocessRunnerRunExitCodeFourReturnsValidationFailureAndPreservesOutp
} }
func TestSubprocessRunnerRenderRejectsInvalidOrFailedPreview(t *testing.T) { func TestSubprocessRunnerRenderRejectsInvalidOrFailedPreview(t *testing.T) {
for _, mode := range []string{"render_invalid", "render_failure"} { for _, mode := range []string{"render_empty", "render_invalid", "render_failure"} {
t.Run(mode, func(t *testing.T) { t.Run(mode, func(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1") t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
t.Setenv("SCRIPTORIUM_HELPER_MODE", mode) t.Setenv("SCRIPTORIUM_HELPER_MODE", mode)
@@ -196,6 +196,43 @@ func TestSubprocessRunnerRenderRejectsInvalidOrFailedPreview(t *testing.T) {
} }
} }
func TestValidateCapturedOutputProperties(t *testing.T) {
for _, tc := range []struct {
name string
size int64
valid bool
}{
{"empty", 0, false},
{"nonempty", 1, true},
{"at limit", MaxOutputFileBytes, true},
{"over limit", MaxOutputFileBytes + 1, false},
} {
t.Run(tc.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "output")
file, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
// Sparse fixtures exercise size boundaries without loading payloads.
truncateErr := file.Truncate(tc.size)
closeErr := file.Close()
if truncateErr != nil || closeErr != nil {
t.Fatalf("prepare output: truncate=%v close=%v", truncateErr, closeErr)
}
if err := validateNonEmptyOutput(path); (err == nil) != tc.valid {
t.Fatalf("validate output of size %d: %v", tc.size, err)
}
})
}
dir := t.TempDir()
if err := validateNonEmptyOutput(dir); err == nil {
t.Fatal("accepted directory as output")
}
if err := validateNonEmptyOutput(filepath.Join(dir, "missing")); err == nil {
t.Fatal("accepted missing output")
}
}
func TestSubprocessRunnerRunExitCodeTwoIsNotContentValidation(t *testing.T) { func TestSubprocessRunnerRunExitCodeTwoIsNotContentValidation(t *testing.T) {
t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1") t.Setenv("GO_WANT_SCRIPTORIUM_HELPER", "1")
t.Setenv("SCRIPTORIUM_HELPER_MODE", "fail_exit2_with_output") t.Setenv("SCRIPTORIUM_HELPER_MODE", "fail_exit2_with_output")
@@ -351,6 +388,8 @@ func TestScriptoriumSubprocessHelper(t *testing.T) {
case "render_invalid": case "render_invalid":
_, _ = os.Stdout.WriteString("{broken") _, _ = os.Stdout.WriteString("{broken")
os.Exit(0) os.Exit(0)
case "render_empty":
os.Exit(0)
case "render_failure": case "render_failure":
_, _ = os.Stderr.WriteString("preview failed") _, _ = os.Stderr.WriteString("preview failed")
os.Exit(1) os.Exit(1)