Files
pipelines/internal/claudehost/automation_lifecycle_test.go
T

199 lines
6.3 KiB
Go

package claudehost
import (
"context"
"encoding/json"
"errors"
"net"
"os"
"strings"
"syscall"
"testing"
"time"
)
func automationHost(t *testing.T) *host {
t.Helper()
dir, err := os.MkdirTemp("/tmp", "phcron")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.RemoveAll(dir) })
now := time.Now()
h := &host{dir: dir, id: "native-cron", paths: PathsFor(dir, "native-cron"),
idle: 50 * time.Millisecond, spoolLimit: 512,
pending: map[string]int64{}, modelReqs: map[string]string{}, modeReqs: map[string]string{},
changed: make(chan struct{}), stopped: make(chan struct{}), claudeEnd: make(chan struct{}),
activity: now, detached: now}
// A real subprocess sends the native SDK callback, waits for the host ACK,
// and remains alive without any Pipelines client attached.
script := `printf '%s\n' '{"type":"control_request","request_id":"observer","request":{"subtype":"hook_callback","callback_id":"pipelines-native-session-automations-v1","input":{"session_id":"native-cron","hook_event_name":"Stop","session_crons":[{"id":"future"}]}}}'; IFS= read -r ack; printf '%s\n' '{"type":"result"}'; sleep 30`
if err := h.start([]string{"/bin/sh", "-c", script}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { h.shutdown("automation test cleanup") })
go h.accept()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
h.mu.Lock()
ready := h.automations != nil && !h.busy && len(h.pending) == 0 && len(h.lines) >= 2
h.mu.Unlock()
if ready {
return h
}
time.Sleep(time.Millisecond)
}
t.Fatal("native observer did not receive its ACK while detached")
return nil
}
func TestNativeAutomationRetainsDetachedCLIUntilEmptySnapshot(t *testing.T) {
h := automationHost(t)
go h.watchIdle()
time.Sleep(180 * time.Millisecond)
select {
case <-h.stopped:
t.Fatal("idle cleanup killed a CLI with a future native automation")
default:
}
if err := syscall.Kill(h.cmd.Process.Pid, 0); err != nil {
t.Fatal("the real native subprocess exited:", err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
status, err := ReadStatus(ctx, h.paths.Socket)
if err != nil || status.Automations == nil || len(status.Automations.IDs) != 1 {
t.Fatalf("detached native snapshot: %+v, %v", status, err)
}
h.appendLine([]byte(`{"type":"control_request","request_id":"empty","request":{"subtype":"hook_callback","callback_id":"pipelines-native-session-automations-v1","input":{"session_id":"native-cron","hook_event_name":"Stop","session_crons":[]}}}`))
select {
case <-h.stopped:
case <-time.After(2 * time.Second):
t.Fatal("a known empty native snapshot did not allow idle cleanup")
}
}
func TestAutomationStatusDoesNotStealAttachmentAndSurvivesSpoolTrim(t *testing.T) {
h := automationHost(t)
client, _, err := Attach(h.paths.Socket, 0, time.Second)
if err != nil {
t.Fatal(err)
}
defer client.Close()
go func() {
for {
if _, err := client.Recv(); err != nil {
return
}
}
}()
h.mu.Lock()
attached := h.active
h.mu.Unlock()
for range 8 {
line, _ := json.Marshal(map[string]any{"type": "system", "subtype": "fixture", "padding": strings.Repeat("x", 300)})
h.appendLine(line)
h.mu.Lock()
h.acked = h.end
h.compactLocked()
h.mu.Unlock()
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
status, err := ReadStatus(ctx, h.paths.Socket)
if err != nil || status == nil || status.Base == 0 || status.Automations == nil || len(status.Automations.IDs) != 1 || len(status.Pending) != 0 {
t.Fatalf("trimmed native status: %+v, %v", status, err)
}
h.mu.Lock()
unchanged := h.active == attached
h.mu.Unlock()
if !unchanged {
t.Fatal("read-only status displaced the active delivery client")
}
}
func TestAutomationObserverLeavesPermissionsPendingAndMissingMetadataUnknown(t *testing.T) {
h := automationHost(t)
h.appendLine([]byte(`{"type":"control_request","request_id":"permission","request":{"subtype":"can_use_tool","tool_name":"Bash"}}`))
h.appendLine([]byte(`{"type":"control_request","request_id":"missing","request":{"subtype":"hook_callback","callback_id":"pipelines-native-session-automations-v1","input":{"session_id":"native-cron","hook_event_name":"Stop"}}}`))
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
status, err := ReadStatus(ctx, h.paths.Socket)
if err != nil || status.Automations != nil || len(status.Pending) != 1 || status.Pending[0].ID != "permission" {
t.Fatalf("observer consumed permission or retained absent metadata: %+v, %v", status, err)
}
}
func TestReadAutomationStatusCancelsAfterConnectionEstablished(t *testing.T) {
dir, err := os.MkdirTemp("/tmp", "phstatus")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
listener, err := net.Listen("unix", dir+"/host.sock")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
read := make(chan struct{})
done := make(chan struct{})
go func() {
defer close(done)
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
var frame Frame
_ = json.NewDecoder(conn).Decode(&frame)
close(read)
_, _ = conn.Read(make([]byte, 1))
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
result := make(chan error, 1)
go func() { _, err := ReadStatus(ctx, dir+"/host.sock"); result <- err }()
<-read
cancel()
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Fatalf("cancellation was not propagated: %v", err)
}
case <-time.After(500 * time.Millisecond):
t.Fatal("status read ignored cancellation after connecting")
}
<-done
}
func TestReadAutomationStatusRejectsOversizedReply(t *testing.T) {
dir, err := os.MkdirTemp("/tmp", "phlimit")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
listener, err := net.Listen("unix", dir+"/host.sock")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
done := make(chan struct{})
go func() {
defer close(done)
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
var frame Frame
_ = json.NewDecoder(conn).Decode(&frame)
_, _ = conn.Write([]byte(strings.Repeat("x", (4<<20)+1)))
}()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if status, err := ReadStatus(ctx, dir+"/host.sock"); err == nil || status != nil {
t.Fatal("accepted an oversized status reply")
}
<-done
}