Handle process signals through cooperative cancellation
This commit is contained in:
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/cli"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
@@ -11,11 +13,32 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
os.Exit(run())
|
||||
}
|
||||
|
||||
func run() int {
|
||||
app, err := cli.NewApplication(buildinfo.Version(), cli.Options{})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
return 1
|
||||
}
|
||||
ctx, stop := interruptContext()
|
||||
defer stop()
|
||||
outcome := app.Execute(ctx, os.Args[1:], commandkit.Streams{Out: os.Stdout, Err: os.Stderr})
|
||||
return outcome.Status
|
||||
}
|
||||
|
||||
func interruptContext() (context.Context, func()) {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
// Restore ordinary signal handling while cooperative cleanup runs.
|
||||
stop()
|
||||
close(done)
|
||||
}()
|
||||
return ctx, func() {
|
||||
stop()
|
||||
<-done
|
||||
}
|
||||
outcome := app.Execute(context.Background(), os.Args[1:], commandkit.Streams{Out: os.Stdout, Err: os.Stderr})
|
||||
os.Exit(outcome.Status)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,10 @@ or [migration guidance](native-migration.md) for older callers.
|
||||
Use an argument vector with explicit paths appropriate to the deployment.
|
||||
Absolute paths avoid dependence on a service's working directory. Keep stdout
|
||||
and stderr separate, and choose caller cancellation/deadline behavior.
|
||||
On the executable, the first SIGINT or SIGTERM requests cooperative cancellation;
|
||||
started work can drain and available capture can be finalized. A subsequent signal
|
||||
uses ordinary process handling and may interrupt cleanup. No shutdown deadline is
|
||||
implied, and callers should not assume non-cooperative extensions will stop.
|
||||
|
||||
Validate the application and pipeline offline:
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@ declares commands without configuration discovery, engine creation, provider
|
||||
calls, or run-storage allocation. The executable and `RunWithOptions` supply
|
||||
identity from ReleaseKit's native buildinfo accessor; `RunWithOptions` is a
|
||||
convenience execution entry point, not a manual dispatcher.
|
||||
The executable supplies a signal-cancelled context and restores ordinary signal
|
||||
handling after the first interrupt or termination request; embedded applications
|
||||
continue to use their caller-supplied contexts.
|
||||
|
||||
The constructor wires:
|
||||
|
||||
|
||||
@@ -138,6 +138,12 @@ available evidence. Publication, required capture, and presentation are separate
|
||||
boundaries: later failure does not undo completed publication.
|
||||
[CLI Reference](cli.md#completion-report) owns the completion value and outcomes.
|
||||
|
||||
The executable treats the first SIGINT or SIGTERM as a cooperative cancellation
|
||||
request. It restores ordinary signal handling during cleanup so a subsequent
|
||||
signal can terminate the process. There is no shutdown deadline or guarantee
|
||||
that collaborators which ignore cancellation will stop; forced termination may
|
||||
leave capture incomplete. Embedded application callers retain their own contexts.
|
||||
|
||||
### Acceptance And Fallback
|
||||
|
||||
PromptKit owns transient retries and structural repair. Application semantic
|
||||
|
||||
@@ -266,6 +266,12 @@ the selected single failure-finalization boundary preserves genuine causes.
|
||||
|
||||
### CAT-010 — Process Signals Do Not Reach Cooperative Cancellation
|
||||
|
||||
**Status:** Resolved. The executable routes the first SIGINT/SIGTERM to its
|
||||
application context and restores ordinary signal handling during cleanup.
|
||||
Offline subprocess tests observe provider cancellation, joined work, terminal
|
||||
evidence, no retry/fallback, and subsequent-signal termination with held delivery.
|
||||
Embedded callers retain their contexts; no cleanup deadline is introduced.
|
||||
|
||||
**Assessment:** Static executable integration weakness; original P3.
|
||||
|
||||
**Source:** [CONC-001](04-concurrency.md#conc-001--process-signals-bypass-cooperative-cancellation-and-cleanup).
|
||||
@@ -281,7 +287,7 @@ does not imply SIGKILL handling or a new shutdown deadline guarantee.
|
||||
**Subsequent decision:** [Discussion Item 3](discussion.md#3-process-signals-and-cooperative-cancellation)
|
||||
selects cooperative cancellation on the first SIGINT/SIGTERM and ordinary
|
||||
termination on a subsequent signal, with no application shutdown deadline.
|
||||
Signal handling stays at the executable boundary; implementation remains pending.
|
||||
Signal handling stays at the executable boundary.
|
||||
|
||||
### CAT-011 — Extreme Accepted Context Radius Can Empty Evidence
|
||||
|
||||
|
||||
@@ -613,6 +613,13 @@ race tests. Update CLI/state internals, not CommandKit-owned syntax.
|
||||
|
||||
## Stage 21 — Connect Executable Signals To Cancellation
|
||||
|
||||
**Completed.** The executable routes the first SIGINT/SIGTERM into the existing
|
||||
context and restores ordinary handling for a subsequent signal, joining its
|
||||
signal helper before exit. Offline subprocess tests exercise in-flight provider
|
||||
cancellation, terminal evidence, no fallback/retry, and a held-delivery second
|
||||
signal. Repeated process tests and the prescribed executable/CLI checks pass.
|
||||
No shutdown deadline or embedded process-wide handler was added.
|
||||
|
||||
**Coverage:** CAT-010. **Prerequisites:** Stages 10, 17, 20.
|
||||
|
||||
Pass a SIGINT/SIGTERM-cancelled context from cmd/notarius/main.go to app.Execute.
|
||||
|
||||
224
internal/cli/native_signal_unix_test.go
Normal file
224
internal/cli/native_signal_unix_test.go
Normal file
@@ -0,0 +1,224 @@
|
||||
//go:build unix
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestExecutableSignalsCancelAndDrainProviderWork(t *testing.T) {
|
||||
binary := buildNativeExecutable(t)
|
||||
for _, scenario := range []struct {
|
||||
first os.Signal
|
||||
secondSignal bool
|
||||
}{{os.Interrupt, false}, {syscall.SIGTERM, false}, {os.Interrupt, true}} {
|
||||
t.Run(fmt.Sprintf("first=%s/second-signal=%t", scenario.first, scenario.secondSignal), func(t *testing.T) {
|
||||
secondSignal := scenario.secondSignal
|
||||
started, canceled := make(chan struct{}, 1), make(chan struct{}, 1)
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
|
||||
calls.Add(1)
|
||||
_, _ = io.Copy(io.Discard, request.Body)
|
||||
started <- struct{}{}
|
||||
<-request.Context().Done()
|
||||
canceled <- struct{}{}
|
||||
}))
|
||||
defer server.Close()
|
||||
root := t.TempDir()
|
||||
configPath, inputPath := filepath.Join(root, "config.yml"), filepath.Join(root, "input.json")
|
||||
configuration := fmt.Sprintf(`version: 6
|
||||
output: {directory: output}
|
||||
debug: {directory: debug}
|
||||
pipelines:
|
||||
demo:
|
||||
input: {module: seriatim}
|
||||
chunk: {module: generic}
|
||||
llm_profile: local-fake
|
||||
mode: permissive
|
||||
max_additional_turns: 0
|
||||
artifacts:
|
||||
spells:
|
||||
extract: {module: dnd/spells}
|
||||
promptkit:
|
||||
profiles:
|
||||
- id: local-fake
|
||||
endpoint: %q
|
||||
model: fake-model
|
||||
api_key_required: false
|
||||
`, server.URL+"/v1")
|
||||
if err := os.WriteFile(configPath, []byte(configuration), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(inputPath, []byte(`{"metadata":{"id":"source"},"segments":[{"id":1,"start":0,"end":1,"speaker":"GM","text":"The party rests."}]}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
command := exec.CommandContext(ctx, binary, "run", "demo", "--config", configPath, "--input-file", inputPath, "--cache", "bypass", "--llm-transient-retries=0", "--debug")
|
||||
var stdout, stderr bytes.Buffer
|
||||
command.Stdout = &stdout
|
||||
var reader, writer *os.File
|
||||
if secondSignal {
|
||||
var err error
|
||||
reader, writer, err = os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reader.Close()
|
||||
defer writer.Close()
|
||||
command.Stderr = writer
|
||||
} else {
|
||||
command.Stderr = &stderr
|
||||
}
|
||||
if err := command.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- command.Wait() }()
|
||||
joined := false
|
||||
defer func() {
|
||||
if !joined {
|
||||
_ = command.Process.Kill()
|
||||
<-done
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case <-started:
|
||||
case err := <-done:
|
||||
joined = true
|
||||
t.Fatalf("child exited before provider request: %v stdout=%s stderr=%s", err, &stdout, &stderr)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("provider request did not start")
|
||||
}
|
||||
if secondSignal {
|
||||
// Fill the output pipe only after the provider request starts, then
|
||||
// restore blocking mode so terminal delivery holds the child open.
|
||||
fd := int(writer.Fd())
|
||||
if err := syscall.SetNonblock(fd, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
buffer := make([]byte, 4096)
|
||||
for {
|
||||
_, err := syscall.Write(fd, buffer)
|
||||
if errors.Is(err, syscall.EAGAIN) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := syscall.SetNonblock(fd, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := command.Process.Signal(scenario.first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-canceled:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("provider request did not cancel")
|
||||
}
|
||||
if secondSignal {
|
||||
exited, err := waitForTerminalCapture(ctx, filepath.Join(root, "debug"), done)
|
||||
if exited {
|
||||
joined = true
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := command.Process.Signal(syscall.SIGTERM); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var processErr error
|
||||
select {
|
||||
case processErr = <-done:
|
||||
joined = true
|
||||
case <-ctx.Done():
|
||||
t.Fatal("child did not terminate")
|
||||
}
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(processErr, &exit) {
|
||||
t.Fatalf("child error = %v, want non-success", processErr)
|
||||
}
|
||||
if secondSignal {
|
||||
status, ok := exit.Sys().(syscall.WaitStatus)
|
||||
if !ok || !status.Signaled() || status.Signal() != syscall.SIGTERM {
|
||||
t.Fatalf("child status = %v, want SIGTERM", exit.Sys())
|
||||
}
|
||||
} else {
|
||||
terminal := readTerminalCapture(t, filepath.Join(root, "debug"))
|
||||
if terminal["error"] == "" || strings.Contains(stdout.String(), "Success") {
|
||||
t.Fatalf("terminal=%v stdout=%s stderr=%s", terminal, &stdout, &stderr)
|
||||
}
|
||||
outcome := terminal["outcome"].(map[string]any)
|
||||
if outcome["published"] != false || outcome["fallback_count"] != float64(0) {
|
||||
t.Fatalf("terminal outcome = %v", outcome)
|
||||
}
|
||||
}
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("provider calls = %d, want one without retry", calls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func terminalCapturePath(root string) string {
|
||||
entries, _ := os.ReadDir(root)
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
name := filepath.Join(root, entry.Name(), "outcome.json")
|
||||
if _, err := os.Stat(name); err == nil {
|
||||
return name
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func waitForTerminalCapture(ctx context.Context, root string, done <-chan error) (bool, error) {
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
if terminalCapturePath(root) != "" {
|
||||
return false, nil
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
return true, fmt.Errorf("child exited before held terminal delivery: %w", err)
|
||||
case <-ctx.Done():
|
||||
return false, fmt.Errorf("terminal capture was not written: %w", ctx.Err())
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readTerminalCapture(t *testing.T, root string) map[string]any {
|
||||
t.Helper()
|
||||
path := terminalCapturePath(root)
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read terminal capture %q: %v", path, err)
|
||||
}
|
||||
var result map[string]any
|
||||
if err := json.Unmarshal(content, &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user