225 lines
6.0 KiB
Go
225 lines
6.0 KiB
Go
|
|
//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
|
||
|
|
}
|