Wait for subprocess output before releasing resources

This commit is contained in:
2026-12-01 20:20:41 +00:00
parent eb100e54f2
commit da4de023ad
6 changed files with 120 additions and 12 deletions

View File

@@ -29,7 +29,8 @@ Each `pipeline.audita.credentials` value is an exact ConfigKit secret reference.
Narratio forwards selected names and captured values in the child environment
and registers them for captured-stream redaction. It does not discover backend
credentials or scrub files created by Audita. The configured timeout and parent
cancellation bound subprocess execution.
cancellation initiate subprocess shutdown; completion can take longer while
process output finishes.
The corrected transcript is the only canonical polish output. It must be valid
JSON with a top-level `segments` array within Narratio's 64 MiB limit. Exit zero

View File

@@ -12,7 +12,8 @@ Narratio invokes Seriatim as a subprocess in these modes:
- `seriatim trim`
- `seriatim render`
The configured timeout and parent cancellation bound each invocation. Internal
The configured timeout and parent cancellation initiate subprocess shutdown;
completion can take longer while process output finishes. Internal
runner composition is documented in
[the adapter implementation guide](../internal/adapters.md).

View File

@@ -99,7 +99,9 @@ in-memory backend without changing package state.
for remaining group members and uses bounded graceful then forceful termination.
Cancellation, deadlines, and
diagnostic limits use the same terminal disposal path without losing their
original result classification. Child environments contain only the execution
original result classification. Escalation is bounded, but the command waiter
and output copying are joined before logs are flushed or ownership returns;
blocked I/O may prolong shutdown and workspace lock ownership. Child environments contain only the execution
baseline and adapter-specified values; configured credentials are resolved
once by ConfigKit and passed explicitly as sensitive values. Adapters do not
re-read their named environment references. Diagnostic-only stdout and stderr

View File

@@ -202,6 +202,9 @@ power-loss/partial-write guarantee is introduced.
## Stage 5: Join subprocess completion before releasing resource ownership
**Complete:** Escalation now joins the command waiter before output and diagnostics
are released. Delayed-wait and blocked-output regressions and subprocess checks pass.
Read:
- `audit/04-concurrency.md`, lines 162–222 (CN-03).

View File

@@ -2,7 +2,6 @@ package subprocess
import (
"context"
"fmt"
"os/exec"
"time"
)
@@ -80,12 +79,7 @@ func terminateAndReap(tree ownedProcessTree, waitCh <-chan error) (waitErr, clea
case <-timer.C:
}
cleanupErr = joinErrors(cleanupErr, tree.TerminateForcefully())
forcefulTimer := time.NewTimer(forcefulTerminationWait)
defer forcefulTimer.Stop()
select {
case waitErr = <-waitCh:
return waitErr, cleanupErr
case <-forcefulTimer.C:
return nil, joinErrors(cleanupErr, fmt.Errorf("owned subprocess did not reap within %s after forceful termination", forcefulTerminationWait))
}
// Process termination and output copying are not complete until Wait returns.
// Keep ownership of command state and output writers even if I/O is delayed.
return <-waitCh, cleanupErr
}

View File

@@ -1,9 +1,13 @@
package subprocess
import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)
func TestTerminateAndReapPreservesWaitAndCleanupErrors(t *testing.T) {
@@ -31,6 +35,52 @@ func TestTerminateAndReapPreservesWaitAndCleanupErrors(t *testing.T) {
}
}
func TestTerminationJoinsDelayedWaiterAfterEscalation(t *testing.T) {
waitErr := errors.New("delayed wait failed")
forceErr := errors.New("synthetic force failure")
forced := make(chan struct{})
tree := &signalingProcessTree{forced: forced, forceErr: forceErr}
waitCh := make(chan error)
type result struct{ wait, cleanup error }
completed := make(chan result, 1)
go func() {
wait, cleanup := terminateAndReap(tree, waitCh)
completed <- result{wait, cleanup}
}()
select {
case <-forced:
case <-time.After(10 * time.Second):
t.Fatal("forceful termination was not attempted")
}
select {
case got := <-completed:
t.Fatalf("returned before waiter completed: %+v", got)
default:
}
waitCh <- waitErr
select {
case got := <-completed:
if !errors.Is(got.wait, waitErr) || !errors.Is(got.cleanup, forceErr) {
t.Fatalf("termination errors = %+v", got)
}
case <-time.After(10 * time.Second):
t.Fatal("termination did not join the released waiter")
}
}
type signalingProcessTree struct {
forced chan struct{}
forceErr error
}
func (*signalingProcessTree) Start(*exec.Cmd) error { return nil }
func (*signalingProcessTree) TerminateGracefully() error { return nil }
func (tree *signalingProcessTree) TerminateForcefully() error {
close(tree.forced)
return tree.forceErr
}
func (*signalingProcessTree) Dispose() error { return nil }
type recordingProcessTree struct {
gracefulErr error
forcefulErr error
@@ -52,3 +102,60 @@ func (tree *recordingProcessTree) TerminateForcefully() error {
}
func (*recordingProcessTree) Dispose() error { return nil }
type gatedWriter struct {
entered chan struct{}
release chan struct{}
}
func (w *gatedWriter) Write(data []byte) (int, error) {
close(w.entered)
<-w.release
return len(data), nil
}
func TestRunRetainsOutputUntilDelayedWaitCompletes(t *testing.T) {
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
writer := &gatedWriter{entered: make(chan struct{}), release: make(chan struct{})}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
finished := make(chan error, 1)
stderrPath := filepath.Join(t.TempDir(), "stderr.log")
go func() {
_, err := Run(ctx, RunRequest{
Executable: executable,
Args: []string{"-test.run=^TestSubprocessHelper$", "--", "success"},
EnvOverrides: map[string]string{"GO_WANT_SUBPROCESS_HELPER": "1", "SUBPROCESS_HELPER_STDOUT": "synthetic output"},
StdoutResult: writer,
StdoutResultLimit: 1024,
StderrLogPath: stderrPath,
})
finished <- err
}()
select {
case <-writer.entered:
case <-time.After(10 * time.Second):
t.Fatal("writer not entered")
}
cancel()
// The previous final reap timeout could return while the writer remained blocked.
// This watchdog exercises that exceptional interval without claiming a return deadline.
select {
case err := <-finished:
close(writer.release)
t.Fatalf("returned output ownership while write was active: %v", err)
case <-time.After(gracefulTerminationWait + forcefulTerminationWait + time.Second):
}
close(writer.release)
select {
case err := <-finished:
if !errors.Is(err, context.Canceled) {
t.Fatalf("error = %v, want cancellation", err)
}
case <-time.After(10 * time.Second):
t.Fatal("command did not finish after writer released")
}
}