Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion cmd/agynd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ var version = "dev"
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// SIGCONT is the runner's wake after hibernation. It has to be asked for:
// as a container's init, agynd never sees a signal it has no handler for.
wake := make(chan os.Signal, 1)
signal.Notify(wake, syscall.SIGCONT)
defer signal.Stop(wake)

cfg, err := config.FromEnv()
if err != nil {
Expand All @@ -29,7 +34,7 @@ func main() {
}
defer agynd.Close()

if err := agynd.Run(ctx); err != nil {
if err := agynd.Run(ctx, wake); err != nil {
if errors.Is(err, context.Canceled) {
log.Printf("daemon stopped: %v", err)
return
Expand Down
71 changes: 49 additions & 22 deletions internal/daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -107,7 +108,14 @@ type Daemon struct {

processing atomic.Bool
processingWake chan struct{}
syncMu sync.Mutex
// wakeSync asks Run for an inbox read after a wake from hibernation. One
// pending read is as good as any number, so it holds one.
wakeSync chan struct{}
syncMu sync.Mutex

// Left unset outside tests: the real clocks and the real tick.
clocks func() clockReading
keepaliveInterval time.Duration
}

type platformConn interface {
Expand All @@ -129,12 +137,14 @@ type claudeClient interface {

type runnersClient interface {
TouchWorkload(ctx context.Context, workloadID string) error
ReportWorkloadIdle(ctx context.Context, workloadID string) error
}

type messageSubscriber interface {
Run(ctx context.Context) error
Started() <-chan struct{}
Wake() <-chan struct{}
Resubscribe()
}

type messageConsumer interface {
Expand Down Expand Up @@ -491,17 +501,22 @@ func (d *Daemon) Close() {
}
}

func (d *Daemon) Run(ctx context.Context) error {
// Run serves the inbox until ctx ends. wake carries the runner's SIGCONT, its
// cue that the workload has been woken from hibernation; nil never fires.
func (d *Daemon) Run(ctx context.Context, wake <-chan os.Signal) error {
// Before either mode. A sandbox is the workload persistent shells exist
// for, but the server is cheap and the alternative is a second place where
// a shell's environment could differ.
startShellServer(ctx)

if d.sdk == config.ModeHolder {
return runHolder(ctx, d.agents, d.cfg.EnvironmentID, d.cfg.WorkDir)
return runHolder(ctx, wake, d.agents, d.cfg.EnvironmentID, d.cfg.WorkDir)
}
d.ensureProcessingWake()
go d.runKeepalive(ctx)
if d.wakeSync == nil {
d.wakeSync = make(chan struct{}, 1)
}
go d.runKeepalive(ctx, wake)

go func() {
if err := d.subscriber.Run(ctx); err != nil && ctx.Err() == nil {
Expand Down Expand Up @@ -562,34 +577,38 @@ func (d *Daemon) Run(ctx context.Context) error {
scheduleFailureRetry(operation, err)
return nil
}

if err := d.syncMessages(ctx); err != nil {
if terminalErr := handleSyncFailure("initial sync messages", err); terminalErr != nil {
return terminalErr
syncInbox := func(operation string) error {
if err := d.syncMessages(ctx); err != nil {
return handleSyncFailure(operation, err)
}
} else {
clearRetry()
return nil
}

if err := syncInbox("initial sync messages"); err != nil {
return err
}

for {
select {
case <-ctx.Done():
return operationError(opProcessSignalShutdown, 0, ctx.Err())
case <-d.wakeSync:
// Woken from hibernation. What arrived while the workload slept is
// in the inbox, and the stream that would have announced it died
// with the sleep, so the inbox is read once without waiting on a
// notification. The items are processed as a normal turn; nothing
// is replayed to the agent CLI.
if err := syncInbox("wake sync messages"); err != nil {
return err
}
case <-d.subscriber.Wake():
if err := d.syncMessages(ctx); err != nil {
if terminalErr := handleSyncFailure("sync messages", err); terminalErr != nil {
return terminalErr
}
} else {
clearRetry()
if err := syncInbox("sync messages"); err != nil {
return err
}
case <-retry:
if err := d.syncMessages(ctx); err != nil {
if terminalErr := handleSyncFailure("sync messages retry", err); terminalErr != nil {
return terminalErr
}
} else {
clearRetry()
if err := syncInbox("sync messages retry"); err != nil {
return err
}
}
}
Expand Down Expand Up @@ -793,7 +812,15 @@ func (d *Daemon) syncMessages(ctx context.Context) error {
if err := d.ensureMCPReady(ctx); err != nil {
return fmt.Errorf("wait for MCP servers before processing message %s: %w", message.ID, err)
}
return d.handleMessage(ctx, message)
if err := d.handleMessage(ctx, message); err != nil {
return err
}
// The turn is over: every handler acks the item as its last act and
// returns nil only once it has. The report follows the ack, never
// precedes it, so a workload is never frozen between finishing an
// item and acknowledging it.
d.reportWorkloadIdle(ctx)
return nil
}); err != nil {
var pageFetchErr *platform.PageFetchError
if !errors.As(err, &pageFetchErr) {
Expand Down
95 changes: 82 additions & 13 deletions internal/daemon/daemon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"

Expand Down Expand Up @@ -41,10 +42,11 @@ func testConfig(sdk string) config.Config {
}

type fakeMessageSubscriber struct {
runStarted chan struct{}
releaseRun chan struct{}
wake chan struct{}
runOnce sync.Once
runStarted chan struct{}
releaseRun chan struct{}
wake chan struct{}
runOnce sync.Once
resubscribed atomic.Int32
}

func newFakeMessageSubscriber() *fakeMessageSubscriber {
Expand Down Expand Up @@ -77,6 +79,10 @@ func (f *fakeMessageSubscriber) Wake() <-chan struct{} {
return f.wake
}

func (f *fakeMessageSubscriber) Resubscribe() {
f.resubscribed.Add(1)
}

type fakeMessageConsumer struct {
mu sync.Mutex
errors []error
Expand Down Expand Up @@ -182,6 +188,10 @@ func (r *recordingRunnersClient) TouchWorkload(_ context.Context, _ string) erro
return nil
}

func (r *recordingRunnersClient) ReportWorkloadIdle(_ context.Context, _ string) error {
return nil
}

type blockingMessageConsumer struct {
started chan struct{}
release chan struct{}
Expand Down Expand Up @@ -339,7 +349,7 @@ func TestRunStartsKeepaliveAndSubscriberBeforeInitialSync(t *testing.T) {

errCh := make(chan error, 1)
go func() {
errCh <- daemon.Run(ctx)
errCh <- daemon.Run(ctx, nil)
}()

select {
Expand Down Expand Up @@ -385,7 +395,7 @@ func TestRunInitialSyncProceedsWhenSubscriberNotReady(t *testing.T) {

errCh := make(chan error, 1)
go func() {
errCh <- daemon.Run(ctx)
errCh <- daemon.Run(ctx, nil)
}()

select {
Expand Down Expand Up @@ -424,7 +434,7 @@ func TestRunWrapsShutdownCancellation(t *testing.T) {

errCh := make(chan error, 1)
go func() {
errCh <- daemon.Run(ctx)
errCh <- daemon.Run(ctx, nil)
}()

select {
Expand Down Expand Up @@ -465,7 +475,7 @@ func TestRunRetriesSyncAfterFailure(t *testing.T) {

errCh := make(chan error, 1)
go func() {
errCh <- daemon.Run(ctx)
errCh <- daemon.Run(ctx, nil)
}()

deadline := time.After(1500 * time.Millisecond)
Expand All @@ -484,6 +494,65 @@ func TestRunRetriesSyncAfterFailure(t *testing.T) {
}
}

// A wake from hibernation reopens the subscription and reads the inbox once:
// what arrived during the sleep is in the inbox, and the stream that would
// have announced it is dead on the far side.
func TestRunWakeResubscribesAndReadsInbox(t *testing.T) {
subscriber := newFakeMessageSubscriber()
consumer := &fakeMessageConsumer{}
wake := make(chan os.Signal, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
daemon := &Daemon{
cfg: config.Config{AgentID: uuid.MustParse(testAgentID)},
runners: &fakeRunnersClient{},
subscriber: subscriber,
consumer: consumer,
}

errCh := make(chan error, 1)
go func() {
errCh <- daemon.Run(ctx, wake)
}()

deadline := time.After(500 * time.Millisecond)
for consumer.Calls() < 1 {
select {
case err := <-errCh:
t.Fatalf("Run returned before the initial sync: %v", err)
case <-deadline:
t.Fatal("initial sync did not run")
case <-time.After(10 * time.Millisecond):
}
}
if got := subscriber.resubscribed.Load(); got != 0 {
t.Fatalf("resubscribed %d times before any wake", got)
}

wake <- syscall.SIGCONT

deadline = time.After(500 * time.Millisecond)
for consumer.Calls() < 2 {
select {
case err := <-errCh:
t.Fatalf("Run returned on wake: %v", err)
case <-deadline:
t.Fatalf("expected an inbox read on wake, got %d sync calls", consumer.Calls())
case <-time.After(10 * time.Millisecond):
}
}
if got := subscriber.resubscribed.Load(); got != 1 {
t.Fatalf("expected one resubscribe on wake, got %d", got)
}

cancel()
select {
case <-errCh:
case <-time.After(500 * time.Millisecond):
t.Fatal("Run did not stop")
}
}

func TestRunReturnsTerminalCodexTurnFailureWithoutRetry(t *testing.T) {
subscriber := newFakeMessageSubscriber()
consumer := &handlingMessageConsumer{message: platform.Message{ID: "msg-1", ThreadID: "thread-1", Body: "hello"}}
Expand All @@ -506,7 +575,7 @@ func TestRunReturnsTerminalCodexTurnFailureWithoutRetry(t *testing.T) {

errCh := make(chan error, 1)
go func() {
errCh <- daemon.Run(ctx)
errCh <- daemon.Run(ctx, nil)
}()

deadline := time.After(500 * time.Millisecond)
Expand Down Expand Up @@ -578,7 +647,7 @@ func TestRunRetriesTransientCodexStreamFailure(t *testing.T) {

errCh := make(chan error, 1)
go func() {
errCh <- daemon.Run(ctx)
errCh <- daemon.Run(ctx, nil)
}()

select {
Expand Down Expand Up @@ -679,7 +748,7 @@ func TestRunRetriesReadbackTransportFailure(t *testing.T) {

errCh := make(chan error, 1)
go func() {
errCh <- d.Run(ctx)
errCh <- d.Run(ctx, nil)
}()

waitForStartTurn := func() {
Expand Down Expand Up @@ -814,7 +883,7 @@ func runHolderModeAndAssertWorkDir(t *testing.T, cfg config.Config, expectedWork
ctx, cancel := context.WithCancel(context.Background())
errCh := make(chan error, 1)
go func() {
errCh <- daemon.Run(ctx)
errCh <- daemon.Run(ctx, nil)
}()

waitForWorkDir(t, errCh, expectedWorkDir)
Expand Down Expand Up @@ -856,7 +925,7 @@ func runHolderModeAndAssertChdir(t *testing.T, cfg config.Config, expectedWorkDi
defer cancel()
errCh := make(chan error, 1)
go func() {
errCh <- daemon.Run(ctx)
errCh <- daemon.Run(ctx, nil)
}()

select {
Expand Down
15 changes: 12 additions & 3 deletions internal/daemon/holder.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

var holderChdir = os.Chdir

func runHolder(ctx context.Context, client initScriptsClient, environmentID string, workDir string) error {
func runHolder(ctx context.Context, wake <-chan os.Signal, client initScriptsClient, environmentID string, workDir string) error {
workDir = strings.TrimSpace(workDir)
if workDir == "" {
return fmt.Errorf("holder work dir is required")
Expand All @@ -26,6 +26,15 @@ func runHolder(ctx context.Context, client initScriptsClient, environmentID stri
return err
}
}
<-ctx.Done()
return operationError(opProcessSignalShutdown, 0, ctx.Err())
for {
select {
case <-ctx.Done():
return operationError(opProcessSignalShutdown, 0, ctx.Err())
case <-wake:
// A sandbox holds no subscription and runs no turn, and its gateway
// connection reopens itself on the next call: the wake is noted and
// nothing else.
log.Printf("wake signal received; holder has nothing to resubscribe")
}
}
}
Loading
Loading