From 4ea3f6bed88bce725aa9acc4a31896aad2ac696d Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Fri, 30 Oct 2026 01:45:14 +0100 Subject: [PATCH 1/3] Report the turn boundary to Runners A turn used to end in silence. The keepalive stops when the agent CLI goes quiet, and Runners learned of it only when the activity sweep found the workload past its keepalive grace, which is how long any decision that waits on an idle agent -- hibernation first among them -- had to wait as well. After the turn's inbox items are acked, agynd now calls ReportWorkloadIdle. The call flips the workload's agent_state to idle at once, and is the moment the Orchestrator may hibernate the workload: between one turn and the next, if the inbox is still empty when it looks. The report follows the ack and never precedes it, so the ack is the last word of a turn and a workload is never frozen between finishing an item and acknowledging it. Every handler acks as its last act and returns nil only once it has; the report sits behind that return, where it is the same for codex, claude and agn. A report that never arrives costs nothing but latency, because the sweep reaches the same state on its own schedule, so a failure is logged and never fatal. In holder mode there is no turn, so there is no report; a sandbox's idleness is the Terminal Proxy's to observe. The RPC is on the Gateway's RunnersGateway since agynio/api#199. The repository commits no generated code; CI generates the bindings from the BSR module, as before. --- internal/daemon/daemon.go | 11 +- internal/daemon/daemon_test.go | 4 + internal/daemon/keepalive.go | 22 ++++ internal/daemon/keepalive_test.go | 26 +++- internal/daemon/turnboundary_test.go | 170 +++++++++++++++++++++++++++ internal/platform/runners.go | 15 +++ internal/platform/runners_test.go | 41 +++++++ test/e2e/agynd_daemon_test.go | 4 + 8 files changed, 290 insertions(+), 3 deletions(-) create mode 100644 internal/daemon/turnboundary_test.go diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 42f4de9..5d6f219 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -129,6 +129,7 @@ type claudeClient interface { type runnersClient interface { TouchWorkload(ctx context.Context, workloadID string) error + ReportWorkloadIdle(ctx context.Context, workloadID string) error } type messageSubscriber interface { @@ -793,7 +794,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) { diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index caecd01..88963be 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -182,6 +182,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{} diff --git a/internal/daemon/keepalive.go b/internal/daemon/keepalive.go index 627e6a3..c493d29 100644 --- a/internal/daemon/keepalive.go +++ b/internal/daemon/keepalive.go @@ -11,6 +11,7 @@ import ( const ( workloadKeepaliveInterval = 10 * time.Second workloadKeepaliveTimeout = 5 * time.Second + workloadIdleReportTimeout = 5 * time.Second ) func (d *Daemon) runKeepalive(ctx context.Context) { @@ -42,6 +43,27 @@ func (d *Daemon) runKeepalive(ctx context.Context) { } } +// reportWorkloadIdle tells Runners the turn is over, once its inbox items are +// acked. The call flips the workload's agent_state to idle at once rather than +// after the keepalive grace, and is the moment the Orchestrator may hibernate +// the workload: between one turn and the next, if the inbox is still empty when +// it looks. A report that never arrives costs nothing but latency, because the +// activity sweep reaches the same state on its own schedule, so a failure is +// logged and never fatal. In holder mode there is no turn, and so no report. +func (d *Daemon) reportWorkloadIdle(ctx context.Context) { + workloadID := strings.TrimSpace(d.cfg.WorkloadID) + if workloadID == "" { + return + } + reportCtx, cancel := context.WithTimeout(ctx, workloadIdleReportTimeout) + err := d.runners.ReportWorkloadIdle(reportCtx, workloadID) + err = operationContextErr(reportCtx, err) + cancel() + if err != nil && ctx.Err() == nil { + log.Printf("report workload %s idle failed: %v", workloadID, err) + } +} + func (d *Daemon) touchActiveWorkload(ctx context.Context, workloadID string) (bool, error) { if !d.processing.Load() { return false, nil diff --git a/internal/daemon/keepalive_test.go b/internal/daemon/keepalive_test.go index b5b31e0..8b64d94 100644 --- a/internal/daemon/keepalive_test.go +++ b/internal/daemon/keepalive_test.go @@ -12,8 +12,10 @@ import ( ) type fakeRunnersClient struct { - touchCalls []string - err error + touchCalls []string + err error + reportCalls []string + reportErr error } func (f *fakeRunnersClient) TouchWorkload(_ context.Context, workloadID string) error { @@ -21,6 +23,11 @@ func (f *fakeRunnersClient) TouchWorkload(_ context.Context, workloadID string) return f.err } +func (f *fakeRunnersClient) ReportWorkloadIdle(_ context.Context, workloadID string) error { + f.reportCalls = append(f.reportCalls, workloadID) + return f.reportErr +} + func TestTouchActiveWorkloadCallsTouch(t *testing.T) { fake := &fakeRunnersClient{} daemon := &Daemon{ @@ -82,6 +89,21 @@ func TestTouchActiveWorkloadSkipsWhenIdle(t *testing.T) { t.Fatalf("unexpected touch calls: %v", fake.touchCalls) } } + +// Without a workload there is nothing to report on, as there is nothing to +// touch. +func TestReportWorkloadIdleSkipsWhenMissingWorkloadID(t *testing.T) { + fake := &fakeRunnersClient{} + daemon := &Daemon{ + cfg: config.Config{AgentID: uuid.MustParse(testAgentID), WorkloadID: ""}, + runners: fake, + } + daemon.reportWorkloadIdle(context.Background()) + if len(fake.reportCalls) != 0 { + t.Fatalf("unexpected report calls: %v", fake.reportCalls) + } +} + func TestTouchActiveWorkloadSkipsWhenMissingWorkloadID(t *testing.T) { fake := &fakeRunnersClient{} daemon := &Daemon{ diff --git a/internal/daemon/turnboundary_test.go b/internal/daemon/turnboundary_test.go new file mode 100644 index 0000000..cc57f57 --- /dev/null +++ b/internal/daemon/turnboundary_test.go @@ -0,0 +1,170 @@ +package daemon + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + agentsv1 "github.com/agynio/agynd-cli/.gen/go/agynio/api/agents/v1" + gatewayv1 "github.com/agynio/agynd-cli/.gen/go/agynio/api/gateway/v1" + "github.com/agynio/agynd-cli/internal/config" + "github.com/agynio/agynd-cli/internal/platform" + claude "github.com/agynio/claude-sdk-go" + "github.com/google/uuid" + "google.golang.org/grpc" +) + +// turnLog records what the daemon told the platform, in the order it said it. +type turnLog struct { + mu sync.Mutex + entries []string +} + +func (l *turnLog) add(entry string) { + l.mu.Lock() + defer l.mu.Unlock() + l.entries = append(l.entries, entry) +} + +func (l *turnLog) Entries() []string { + l.mu.Lock() + defer l.mu.Unlock() + return append([]string(nil), l.entries...) +} + +// An inbox that logs its acks. +type loggingInboxClient struct { + gatewayv1.AgentsGatewayClient + log *turnLog + ackErr error +} + +func (c *loggingInboxClient) AckInboxItems(context.Context, *agentsv1.AckInboxItemsRequest, ...grpc.CallOption) (*agentsv1.AckInboxItemsResponse, error) { + if c.ackErr != nil { + return nil, c.ackErr + } + c.log.add("ack") + return &agentsv1.AckInboxItemsResponse{}, nil +} + +// A runners client that logs its idle reports, with the workload they name. +type loggingRunnersClient struct { + log *turnLog + reportErr error +} + +func (c *loggingRunnersClient) TouchWorkload(context.Context, string) error { + return nil +} + +func (c *loggingRunnersClient) ReportWorkloadIdle(_ context.Context, workloadID string) error { + c.log.add("report " + workloadID) + return c.reportErr +} + +func newTurnBoundaryDaemon(log *turnLog, inbox *loggingInboxClient, runners *loggingRunnersClient) *Daemon { + return &Daemon{ + sdk: SDKClaude, + cfg: config.Config{ + AgentID: uuid.MustParse(testAgentID), + AgentInstanceID: uuid.MustParse(testAgentInstanceID), + WorkloadID: "workload-1", + }, + threads: platform.NewThreads(&fakeClaudeThreadsClient{}), + agentInbox: platform.NewAgents(inbox), + runners: runners, + claude: &fakeClaudeClient{result: &claude.TurnResult{Response: "hello"}}, + agent: &agentsv1.Agent{}, + consumer: &handlingMessageConsumer{message: platform.Message{ + ID: "msg-1", + InboxItemID: "item-1", + ThreadID: "thread-1", + Body: "hello", + }}, + } +} + +func assertTurnLog(t *testing.T, log *turnLog, want ...string) { + t.Helper() + got := log.Entries() + if len(got) != len(want) { + t.Fatalf("expected %v, got %v", want, got) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("expected %v, got %v", want, got) + } + } +} + +// The ack is the last word of a turn and the report follows it: Runners learns +// the turn is over the moment it is, and never while the item is still +// outstanding, so the workload cannot be frozen between finishing an item and +// acknowledging it. +func TestTurnEndsWithTheAckAndThenTheIdleReport(t *testing.T) { + log := &turnLog{} + daemon := newTurnBoundaryDaemon(log, &loggingInboxClient{log: log}, &loggingRunnersClient{log: log}) + + if err := daemon.syncMessages(context.Background()); err != nil { + t.Fatalf("expected the turn to succeed, got %v", err) + } + assertTurnLog(t, log, "ack", "report workload-1") +} + +// A report that fails costs nothing but latency: the activity sweep reaches the +// same state on its own. The turn has already succeeded and stays that way. +func TestFailedIdleReportDoesNotFailTheTurn(t *testing.T) { + log := &turnLog{} + runners := &loggingRunnersClient{log: log, reportErr: errors.New("gateway unavailable")} + daemon := newTurnBoundaryDaemon(log, &loggingInboxClient{log: log}, runners) + + if err := daemon.syncMessages(context.Background()); err != nil { + t.Fatalf("expected the turn to succeed despite the report, got %v", err) + } + assertTurnLog(t, log, "ack", "report workload-1") +} + +// No ack, no report: a turn whose item is still outstanding is not over. +func TestNoIdleReportWhenTheAckFails(t *testing.T) { + log := &turnLog{} + ackErr := errors.New("gateway unavailable") + daemon := newTurnBoundaryDaemon(log, &loggingInboxClient{log: log, ackErr: ackErr}, &loggingRunnersClient{log: log}) + + err := daemon.syncMessages(context.Background()) + if !errors.Is(err, ackErr) { + t.Fatalf("expected the ack failure, got %v", err) + } + assertTurnLog(t, log) +} + +// In holder mode there is no turn, so there is no report; a sandbox's idleness +// is the Terminal Proxy's to observe. +func TestHolderModeReportsNoIdle(t *testing.T) { + stubHolderChdir(t) + runners := &fakeRunnersClient{} + daemon := &Daemon{ + sdk: config.ModeHolder, + cfg: config.Config{WorkDir: t.TempDir(), WorkloadID: "workload-1"}, + runners: runners, + } + + ctx, cancel := context.WithCancel(context.Background()) + errCh := make(chan error, 1) + go func() { errCh <- daemon.Run(ctx) }() + + time.Sleep(50 * time.Millisecond) + cancel() + select { + case err := <-errCh: + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + case <-time.After(time.Second): + t.Fatal("holder did not stop after cancellation") + } + if len(runners.reportCalls) != 0 { + t.Fatalf("expected no idle report from a holder, got %v", runners.reportCalls) + } +} diff --git a/internal/platform/runners.go b/internal/platform/runners.go index 7e241a5..6d095e1 100644 --- a/internal/platform/runners.go +++ b/internal/platform/runners.go @@ -62,6 +62,21 @@ func (r *Runners) TouchWorkload(ctx context.Context, workloadID string) error { return nil } +// ReportWorkloadIdle tells Runners the agent has finished a turn. Where +// TouchWorkload says the agent is busy, this says it has stopped being, the +// moment it is true rather than a keepalive grace later. +func (r *Runners) ReportWorkloadIdle(ctx context.Context, workloadID string) error { + workloadID = strings.TrimSpace(workloadID) + if workloadID == "" { + return fmt.Errorf("workload id is required") + } + _, err := r.client.ReportWorkloadIdle(ctx, &runnersv1.ReportWorkloadIdleRequest{Id: workloadID}) + if err != nil { + return fmt.Errorf("report workload idle: %w", err) + } + return nil +} + func workloadFromProto(workload *runnersv1.Workload) (Workload, error) { if workload == nil { return Workload{}, fmt.Errorf("workload is required") diff --git a/internal/platform/runners_test.go b/internal/platform/runners_test.go index da70432..7dab916 100644 --- a/internal/platform/runners_test.go +++ b/internal/platform/runners_test.go @@ -26,6 +26,9 @@ type fakeRunnersGatewayClient struct { touchReq *runnersv1.TouchWorkloadRequest touchErr error + + reportReq *runnersv1.ReportWorkloadIdleRequest + reportErr error } func (f *fakeRunnersGatewayClient) ListWorkloadsByThread(ctx context.Context, in *runnersv1.ListWorkloadsByThreadRequest, opts ...grpc.CallOption) (*runnersv1.ListWorkloadsByThreadResponse, error) { @@ -44,6 +47,14 @@ func (f *fakeRunnersGatewayClient) TouchWorkload(ctx context.Context, in *runner return &runnersv1.TouchWorkloadResponse{}, nil } +func (f *fakeRunnersGatewayClient) ReportWorkloadIdle(ctx context.Context, in *runnersv1.ReportWorkloadIdleRequest, opts ...grpc.CallOption) (*runnersv1.ReportWorkloadIdleResponse, error) { + f.reportReq = in + if f.reportErr != nil { + return nil, f.reportErr + } + return &runnersv1.ReportWorkloadIdleResponse{}, nil +} + func TestWorkloadFromProtoValid(t *testing.T) { createdAt := time.Date(2024, 6, 1, 12, 0, 0, 0, time.UTC) removedAt := time.Date(2024, 6, 1, 13, 0, 0, 0, time.UTC) @@ -191,6 +202,36 @@ func TestRunnersTouchWorkloadWrapsError(t *testing.T) { } } +func TestRunnersReportWorkloadIdle(t *testing.T) { + fake := &fakeRunnersGatewayClient{} + client := NewRunners(fake) + if err := client.ReportWorkloadIdle(context.Background(), "workload-1"); err != nil { + t.Fatalf("expected no error, got %v", err) + } + if fake.reportReq == nil || fake.reportReq.GetId() != "workload-1" { + t.Fatalf("unexpected report request: %+v", fake.reportReq) + } +} + +func TestRunnersReportWorkloadIdleValidation(t *testing.T) { + client := NewRunners(&fakeRunnersGatewayClient{}) + if err := client.ReportWorkloadIdle(context.Background(), " "); err == nil { + t.Fatal("expected error for missing workload id") + } +} + +func TestRunnersReportWorkloadIdleWrapsError(t *testing.T) { + fake := &fakeRunnersGatewayClient{reportErr: fmt.Errorf("rpc failed")} + client := NewRunners(fake) + err := client.ReportWorkloadIdle(context.Background(), "workload-1") + if err == nil { + t.Fatal("expected error, got nil") + } + if !strings.Contains(err.Error(), "report workload idle") { + t.Fatalf("missing operation context: %v", err) + } +} + func TestWorkloadFromProtoRemovedAtNil(t *testing.T) { createdAt := time.Date(2024, 6, 1, 12, 0, 0, 0, time.UTC) proto := &runnersv1.Workload{ diff --git a/test/e2e/agynd_daemon_test.go b/test/e2e/agynd_daemon_test.go index 0c0f818..4ac94af 100644 --- a/test/e2e/agynd_daemon_test.go +++ b/test/e2e/agynd_daemon_test.go @@ -372,6 +372,10 @@ func (s agyndRunnersGatewayStub) TouchWorkload(context.Context, *runnersv1.Touch return &runnersv1.TouchWorkloadResponse{}, nil } +func (s agyndRunnersGatewayStub) ReportWorkloadIdle(context.Context, *runnersv1.ReportWorkloadIdleRequest) (*runnersv1.ReportWorkloadIdleResponse, error) { + return &runnersv1.ReportWorkloadIdleResponse{}, nil +} + func (s *agyndGatewayStub) assertInitialized(t *testing.T) { t.Helper() s.mu.Lock() From 1a3d7b477e50d0a7104659d4974a31a0788ff64f Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Sat, 31 Oct 2026 12:09:59 +0100 Subject: [PATCH 2/3] Reconnect when the workload wakes from hibernation (#201) A hibernated workload resumes with every connection it held dead on the far side, which cannot tell a frozen peer from a vanished one. The Notifications stream is the one that would wait on its dead peer until TCP gave up, so on a wake the subscription is dropped and reopened, the inbox is read once -- what arrived during the sleep is in it, and the stream that would have announced it died with the sleep -- and a turn in flight is touched now rather than at the next tick. Nothing is replayed to the agent CLI. Two things say the workload has been woken. The runner sends SIGCONT to the container's init once the guest's clock is set, which a process without a handler never sees, so agynd asks for it. And the clock says so on its own: the runner sets the wall clock after every restore while the monotonic clock slept through the pause, so the keepalive compares the two between ticks, and a wall clock more than a tick ahead is a restore. The signal makes the wake prompt; the clock makes it certain. The keepalive loop handles the wake rather than Run, which is inside the turn for as long as a turn takes. The runner signals twice, a few seconds apart, and the clock confirms what the signal announced; a repeat within two ticks of a handled wake finds it handled and does nothing, and one pending inbox read is as good as any number. The two ticks are measured on the wall clock, because the monotonic one does not move across a sleep and two wakes with a sleep between them must both count. A wake that lands while the subscriber is waiting out a failure cuts the wait short: the wait was for the failure, and a wake is not one. --- cmd/agynd/main.go | 7 +- internal/daemon/daemon.go | 60 ++-- internal/daemon/daemon_test.go | 91 +++++- internal/daemon/holder.go | 15 +- internal/daemon/holder_test.go | 38 ++- internal/daemon/keepalive.go | 64 +++- internal/daemon/wake.go | 79 +++++ internal/daemon/wake_test.go | 387 +++++++++++++++++++++++++ internal/subscriber/subscriber.go | 64 +++- internal/subscriber/subscriber_test.go | 131 +++++++++ 10 files changed, 878 insertions(+), 58 deletions(-) create mode 100644 internal/daemon/wake.go create mode 100644 internal/daemon/wake_test.go diff --git a/cmd/agynd/main.go b/cmd/agynd/main.go index d1b3284..4cd6dda 100644 --- a/cmd/agynd/main.go +++ b/cmd/agynd/main.go @@ -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 { @@ -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 diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 42f4de9..21061cf 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -12,6 +12,7 @@ import ( "net" "net/http" "net/url" + "os" "strings" "sync" "sync/atomic" @@ -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 { @@ -135,6 +143,7 @@ type messageSubscriber interface { Run(ctx context.Context) error Started() <-chan struct{} Wake() <-chan struct{} + Resubscribe() } type messageConsumer interface { @@ -491,17 +500,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 { @@ -562,34 +576,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 } } } diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index caecd01..6cf7156 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -10,6 +10,7 @@ import ( "strings" "sync" "sync/atomic" + "syscall" "testing" "time" @@ -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 { @@ -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 @@ -339,7 +345,7 @@ func TestRunStartsKeepaliveAndSubscriberBeforeInitialSync(t *testing.T) { errCh := make(chan error, 1) go func() { - errCh <- daemon.Run(ctx) + errCh <- daemon.Run(ctx, nil) }() select { @@ -385,7 +391,7 @@ func TestRunInitialSyncProceedsWhenSubscriberNotReady(t *testing.T) { errCh := make(chan error, 1) go func() { - errCh <- daemon.Run(ctx) + errCh <- daemon.Run(ctx, nil) }() select { @@ -424,7 +430,7 @@ func TestRunWrapsShutdownCancellation(t *testing.T) { errCh := make(chan error, 1) go func() { - errCh <- daemon.Run(ctx) + errCh <- daemon.Run(ctx, nil) }() select { @@ -465,7 +471,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) @@ -484,6 +490,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"}} @@ -506,7 +571,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) @@ -578,7 +643,7 @@ func TestRunRetriesTransientCodexStreamFailure(t *testing.T) { errCh := make(chan error, 1) go func() { - errCh <- daemon.Run(ctx) + errCh <- daemon.Run(ctx, nil) }() select { @@ -679,7 +744,7 @@ func TestRunRetriesReadbackTransportFailure(t *testing.T) { errCh := make(chan error, 1) go func() { - errCh <- d.Run(ctx) + errCh <- d.Run(ctx, nil) }() waitForStartTurn := func() { @@ -814,7 +879,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) @@ -856,7 +921,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 { diff --git a/internal/daemon/holder.go b/internal/daemon/holder.go index bc18bd8..b677918 100644 --- a/internal/daemon/holder.go +++ b/internal/daemon/holder.go @@ -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") @@ -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") + } + } } diff --git a/internal/daemon/holder_test.go b/internal/daemon/holder_test.go index c637d85..c0106d3 100644 --- a/internal/daemon/holder_test.go +++ b/internal/daemon/holder_test.go @@ -5,6 +5,7 @@ import ( "errors" "os" "path/filepath" + "syscall" "testing" "time" @@ -25,7 +26,7 @@ func TestRunHolderRunsEnvironmentInitScripts(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() errCh := make(chan error, 1) - go func() { errCh <- runHolder(ctx, fake, "env-1", workDir) }() + go func() { errCh <- runHolder(ctx, nil, fake, "env-1", workDir) }() waitForFile(t, errCh, filepath.Join(workDir, "installed.txt")) @@ -64,7 +65,7 @@ func TestRunHolderWithoutEnvironmentSkipsInitScripts(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) errCh := make(chan error, 1) - go func() { errCh <- runHolder(ctx, fake, "", t.TempDir()) }() + go func() { errCh <- runHolder(ctx, nil, fake, "", t.TempDir()) }() time.Sleep(50 * time.Millisecond) cancel() @@ -87,12 +88,43 @@ func TestRunHolderFailsWhenInitScriptsCannotBeFetched(t *testing.T) { listErr := errors.New("gateway unavailable") fake := &fakeInitScriptsClient{err: listErr} - err := runHolder(context.Background(), fake, "env-1", t.TempDir()) + err := runHolder(context.Background(), nil, fake, "env-1", t.TempDir()) if !errors.Is(err, listErr) { t.Fatalf("expected the list error, got %v", err) } } +// A wake is nothing to a sandbox: no subscription to reopen, no turn to keep +// alive. The holder takes the signal and holds on. +func TestRunHolderHoldsThroughWake(t *testing.T) { + stubHolderChdir(t) + wake := make(chan os.Signal, 1) + + ctx, cancel := context.WithCancel(context.Background()) + errCh := make(chan error, 1) + go func() { errCh <- runHolder(ctx, wake, &fakeInitScriptsClient{}, "", t.TempDir()) }() + + // The second send only lands once the holder has taken the first. + wake <- syscall.SIGCONT + select { + case wake <- syscall.SIGCONT: + case err := <-errCh: + t.Fatalf("holder returned on wake: %v", err) + case <-time.After(time.Second): + t.Fatal("holder did not take the wake") + } + + cancel() + select { + case err := <-errCh: + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + case <-time.After(time.Second): + t.Fatal("holder did not stop after cancellation") + } +} + func stubHolderChdir(t *testing.T) { t.Helper() original := holderChdir diff --git a/internal/daemon/keepalive.go b/internal/daemon/keepalive.go index 627e6a3..5a09e42 100644 --- a/internal/daemon/keepalive.go +++ b/internal/daemon/keepalive.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log" + "os" "strings" "time" ) @@ -13,31 +14,72 @@ const ( workloadKeepaliveTimeout = 5 * time.Second ) -func (d *Daemon) runKeepalive(ctx context.Context) { +// runKeepalive is the daemon's heartbeat. It touches the workload once a tick +// while a turn runs, which is what keeps the idle timeout off a busy agent, +// and it is where a wake from hibernation is noticed and acted on, whether the +// runner's SIGCONT announces it or the clock does. It handles the wake rather +// than Run because Run is inside the turn for as long as a turn takes, and a +// wake that lands mid-turn must not wait for the turn to end. +func (d *Daemon) runKeepalive(ctx context.Context, wake <-chan os.Signal) { workloadID := strings.TrimSpace(d.cfg.WorkloadID) if workloadID == "" { log.Printf("workload keepalive disabled: missing WORKLOAD_ID") - return } - - if _, err := d.touchActiveWorkload(ctx, workloadID); err != nil && ctx.Err() == nil { - log.Printf("workload keepalive failed: %v", err) + touch := func() { + if workloadID == "" { + return + } + if _, err := d.touchActiveWorkload(ctx, workloadID); err != nil && ctx.Err() == nil { + log.Printf("workload keepalive failed: %v", err) + } } + touch() - ticker := time.NewTicker(workloadKeepaliveInterval) + interval := d.keepaliveInterval + if interval <= 0 { + interval = workloadKeepaliveInterval + } + ticker := time.NewTicker(interval) defer ticker.Stop() + + watch := newWakeWatch(d.clocks) + woken := func(cause string) { + // Idempotent, and coalesced: the runner signals twice, the clock + // confirms what the signal announced, and each repeat finds the wake + // already handled. One pending inbox read is as good as any number. + if !watch.admit() { + log.Printf("wake by %s repeats one already handled", cause) + return + } + log.Printf("woken from hibernation by %s; reopening the subscription and reading the inbox", cause) + // Every connection is dead on the far side. The stream is the one + // that would otherwise wait on its dead peer until TCP gave up, so it + // is dropped and reopened; the unary calls fail and reconnect on their + // own. What arrived while the workload slept is in the inbox, which + // Run reads once asked. A turn in flight gets its keepalive now rather + // than at the next tick. Nothing is replayed to the agent CLI. + d.subscriber.Resubscribe() + select { + case d.wakeSync <- struct{}{}: + default: + } + touch() + } + for { select { case <-ctx.Done(): return case <-d.processingWake: - if _, err := d.touchActiveWorkload(ctx, workloadID); err != nil && ctx.Err() == nil { - log.Printf("workload keepalive failed: %v", err) - } + touch() + case <-wake: + woken("signal") case <-ticker.C: - if _, err := d.touchActiveWorkload(ctx, workloadID); err != nil && ctx.Err() == nil { - log.Printf("workload keepalive failed: %v", err) + if jump := watch.tick(); jump > interval { + log.Printf("wall clock moved %s further than monotonic time between ticks", jump) + woken("clock") } + touch() } } } diff --git a/internal/daemon/wake.go b/internal/daemon/wake.go new file mode 100644 index 0000000..8e44cf1 --- /dev/null +++ b/internal/daemon/wake.go @@ -0,0 +1,79 @@ +package daemon + +import "time" + +// A hibernated workload resumes with every connection it held dead on the far +// side, which cannot tell a frozen peer from a vanished one. Two things tell +// agynd it has been woken. The runner sends SIGCONT to the container's init +// once the guest's clock is set, twice a few seconds apart, because a signal +// in the first half second after a resume can go missing. And the clock itself +// says so: the runner sets the wall clock after every restore while the +// monotonic clock slept through the pause, so between two ticks of the +// keepalive the wall clock has moved further than the monotonic one by the +// length of the sleep. The signal makes the wake prompt; the clock makes it +// certain. + +// wakeRepeatWindow is how long after a handled wake another sign of one counts +// as a repeat of it rather than a wake of its own. The runner's second signal +// follows its first by a few seconds and the clock is read once a tick; two +// ticks cover both with room for a late tick. It is measured on the wall +// clock, which unlike the monotonic one moves across a sleep, so two wakes +// with a sleep between them are never taken for one however close together +// they are in running time. +const wakeRepeatWindow = 2 * workloadKeepaliveInterval + +// clockReading is one look at both clocks: the wall clock, which the runner +// sets, and the monotonic clock, which sleeps through a pause. +type clockReading struct { + wall time.Time + mono time.Duration +} + +var clockEpoch = time.Now() + +// readClocks takes both readings from a single time.Now. A Time carries both: +// Sub uses the monotonic reading when it has one, so the wall reading is kept +// apart by stripping it with Round(0). Compared as they come, the two could +// never differ. +func readClocks() clockReading { + now := time.Now() + return clockReading{wall: now.Round(0), mono: now.Sub(clockEpoch)} +} + +// wakeWatch notices a wake from the clocks and tells a wake from the repeats +// of one. It belongs to the keepalive loop alone. +type wakeWatch struct { + clocks func() clockReading + last clockReading + handled time.Time +} + +func newWakeWatch(clocks func() clockReading) *wakeWatch { + if clocks == nil { + clocks = readClocks + } + return &wakeWatch{clocks: clocks, last: clocks()} +} + +// tick reports how far the wall clock has got ahead of the monotonic clock +// since the previous tick: nothing while the workload runs, the length of the +// sleep after a restore. +func (w *wakeWatch) tick() time.Duration { + now := w.clocks() + jump := now.wall.Sub(w.last.wall) - (now.mono - w.last.mono) + w.last = now + return jump +} + +// admit reports whether a sign of a wake is a wake of its own rather than a +// repeat of the last one handled, and counts it as handled when it is. +func (w *wakeWatch) admit() bool { + now := w.clocks() + if !w.handled.IsZero() { + if since := now.wall.Sub(w.handled); since >= 0 && since < wakeRepeatWindow { + return false + } + } + w.handled = now.wall + return true +} diff --git a/internal/daemon/wake_test.go b/internal/daemon/wake_test.go new file mode 100644 index 0000000..173fa22 --- /dev/null +++ b/internal/daemon/wake_test.go @@ -0,0 +1,387 @@ +package daemon + +import ( + "context" + "os" + "sync" + "sync/atomic" + "syscall" + "testing" + "time" + + "github.com/agynio/agynd-cli/internal/config" + "github.com/agynio/agynd-cli/internal/platform" + "github.com/google/uuid" +) + +// scriptedClocks hands out the given readings in order and the last one after +// that. +func scriptedClocks(readings ...clockReading) func() clockReading { + next := 0 + return func() clockReading { + reading := readings[next] + if next < len(readings)-1 { + next++ + } + return reading + } +} + +func wallAt(d time.Duration) time.Time { + return time.Unix(1_800_000_000, 0).Add(d) +} + +// Between two ticks of a running workload the clocks move together. After a +// restore the wall clock has been set ahead by the sleep while the monotonic +// clock has not, and the tick that first sees it reports the sleep, once. +func TestWakeWatchTickReportsTheSleep(t *testing.T) { + watch := newWakeWatch(scriptedClocks( + clockReading{wall: wallAt(0), mono: 0}, + clockReading{wall: wallAt(10 * time.Second), mono: 10 * time.Second}, + clockReading{wall: wallAt(20*time.Second + time.Hour), mono: 20 * time.Second}, + clockReading{wall: wallAt(30*time.Second + time.Hour), mono: 30 * time.Second}, + )) + if got := watch.tick(); got != 0 { + t.Fatalf("expected no jump while running, got %s", got) + } + if got := watch.tick(); got != time.Hour { + t.Fatalf("expected the hour slept, got %s", got) + } + if got := watch.tick(); got != 0 { + t.Fatalf("expected the sleep reported once, got %s again", got) + } +} + +// The runner's second signal and the clock's own detection follow a wake +// within a tick or two of it; all of them are the wake already handled. A +// wake far enough on in wall time is a wake of its own, and so is one behind a +// wall clock that was stepped back. +func TestWakeWatchAdmitFoldsRepeatsOfAWake(t *testing.T) { + watch := newWakeWatch(scriptedClocks( + clockReading{wall: wallAt(0), mono: 0}, + clockReading{wall: wallAt(time.Hour), mono: time.Second}, + clockReading{wall: wallAt(time.Hour + 3*time.Second), mono: 4 * time.Second}, + clockReading{wall: wallAt(time.Hour + wakeRepeatWindow - time.Millisecond), mono: 5 * time.Second}, + clockReading{wall: wallAt(time.Hour + wakeRepeatWindow), mono: 6 * time.Second}, + clockReading{wall: wallAt(time.Hour + wakeRepeatWindow + time.Second), mono: 7 * time.Second}, + clockReading{wall: wallAt(time.Minute), mono: 8 * time.Second}, + )) + if !watch.admit() { + t.Fatal("expected the first wake admitted") + } + if watch.admit() { + t.Fatal("expected the signal's repeat folded into the wake") + } + if watch.admit() { + t.Fatal("expected a repeat at the edge of the window folded into the wake") + } + if !watch.admit() { + t.Fatal("expected a wake at the end of the window admitted") + } + if watch.admit() { + t.Fatal("expected a repeat of the second wake folded into it") + } + if !watch.admit() { + t.Fatal("expected a wake behind a wall clock stepped back admitted") + } +} + +// fakeClocks reads like a guest's clocks: the monotonic one follows the test's +// own, and the wall one follows it too until the test moves it ahead, which is +// what a restore followed by the runner's clock set looks like from inside. +type fakeClocks struct { + start time.Time + ahead atomic.Int64 + reads atomic.Int64 +} + +func newFakeClocks() *fakeClocks { + return &fakeClocks{start: time.Now()} +} + +func (f *fakeClocks) read() clockReading { + f.reads.Add(1) + mono := time.Since(f.start) + return clockReading{wall: f.start.Round(0).Add(mono + time.Duration(f.ahead.Load())), mono: mono} +} + +// sleep is a hibernation of d as seen from inside: the wall clock is set ahead +// by it and the monotonic clock is not. +func (f *fakeClocks) sleep(d time.Duration) { + f.ahead.Add(int64(d)) +} + +// waitForReads returns once the keepalive loop has read the clocks n more +// times, which is n more ticks, each after whatever the loop handled before it. +func (f *fakeClocks) waitForReads(t *testing.T, n int64) { + t.Helper() + target := f.reads.Load() + n + deadline := time.After(2 * time.Second) + for f.reads.Load() < target { + select { + case <-deadline: + t.Fatalf("the keepalive loop stopped ticking at %d reads", f.reads.Load()) + case <-time.After(time.Millisecond): + } + } +} + +// A consumer whose first sync is a turn that lasts until the test ends it; the +// syncs after it return at once. +type turnInFlightConsumer struct { + started chan struct{} + release chan struct{} + mu sync.Mutex + calls int +} + +func newTurnInFlightConsumer() *turnInFlightConsumer { + return &turnInFlightConsumer{started: make(chan struct{}), release: make(chan struct{})} +} + +func (c *turnInFlightConsumer) Sync(ctx context.Context, _ string, _ string, _ func(platform.Message) error) error { + c.mu.Lock() + c.calls++ + first := c.calls == 1 + c.mu.Unlock() + if first { + close(c.started) + select { + case <-ctx.Done(): + return ctx.Err() + case <-c.release: + } + } + return nil +} + +func (c *turnInFlightConsumer) Calls() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.calls +} + +func waitForSyncCalls(t *testing.T, errCh <-chan error, calls func() int, want int, what string) { + t.Helper() + deadline := time.After(2 * time.Second) + for calls() < want { + select { + case err := <-errCh: + t.Fatalf("Run returned before %s: %v", what, err) + case <-deadline: + t.Fatalf("expected %d sync calls after %s, got %d", want, what, calls()) + case <-time.After(5 * time.Millisecond): + } + } +} + +func stopRun(t *testing.T, cancel context.CancelFunc, errCh <-chan error) { + t.Helper() + cancel() + select { + case <-errCh: + case <-time.After(time.Second): + t.Fatal("Run did not stop") + } +} + +// A wake mid-turn resumes the keepalive at once: the turn in flight is touched +// on the wake rather than at the next tick, over whatever connection the touch +// now gets. The subscription is reopened and an inbox read is asked for. +func TestKeepaliveWakeTouchesTheTurnInFlight(t *testing.T) { + subscriber := newFakeMessageSubscriber() + runners := &recordingRunnersClient{touched: make(chan struct{}, 1)} + daemon := &Daemon{ + cfg: config.Config{AgentID: uuid.MustParse(testAgentID), WorkloadID: "workload-1"}, + runners: runners, + subscriber: subscriber, + processingWake: make(chan struct{}, 1), + wakeSync: make(chan struct{}, 1), + } + daemon.processing.Store(true) + wake := make(chan os.Signal, 1) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan struct{}) + go func() { + defer close(done) + daemon.runKeepalive(ctx, wake) + }() + + // The touch the loop opens with, for a turn already running. + select { + case <-runners.touched: + case <-time.After(time.Second): + t.Fatal("expected the opening touch") + } + + wake <- syscall.SIGCONT + select { + case <-runners.touched: + case <-time.After(time.Second): + t.Fatal("expected the turn in flight touched on the wake") + } + if got := subscriber.resubscribed.Load(); got != 1 { + t.Fatalf("expected the subscription reopened once, got %d", got) + } + select { + case <-daemon.wakeSync: + default: + t.Fatal("expected an inbox read asked for") + } + + cancel() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("keepalive loop did not stop") + } +} + +// A wake that lands mid-turn is handled while the turn runs: the subscription +// is reopened then, not when the turn ends. The inbox read waits for the turn, +// because the daemon runs one turn at a time, and follows it. +func TestRunWakeMidTurnResubscribesBeforeTheTurnEnds(t *testing.T) { + subscriber := newFakeMessageSubscriber() + consumer := newTurnInFlightConsumer() + 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) + }() + + select { + case <-consumer.started: + case err := <-errCh: + t.Fatalf("Run returned before the turn: %v", err) + case <-time.After(time.Second): + t.Fatal("the turn did not start") + } + + wake <- syscall.SIGCONT + deadline := time.After(time.Second) + for subscriber.resubscribed.Load() < 1 { + select { + case <-deadline: + t.Fatal("expected the subscription reopened while the turn was in flight") + case <-time.After(5 * time.Millisecond): + } + } + if got := consumer.Calls(); got != 1 { + t.Fatalf("expected the turn still in flight alone, got %d sync calls", got) + } + + close(consumer.release) + waitForSyncCalls(t, errCh, consumer.Calls, 2, "the turn ended") + if got := subscriber.resubscribed.Load(); got != 1 { + t.Fatalf("expected one resubscribe for one wake, got %d", got) + } + + stopRun(t, cancel, errCh) +} + +// The signal can go missing; the clock cannot. A wall clock that moved more +// than a tick further than monotonic time between two ticks is a restore, and +// wakes the daemon as the signal would. A second sleep later is a second wake. +func TestRunClockJumpWakes(t *testing.T) { + subscriber := newFakeMessageSubscriber() + consumer := &fakeMessageConsumer{} + clocks := newFakeClocks() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + daemon := &Daemon{ + cfg: config.Config{AgentID: uuid.MustParse(testAgentID)}, + runners: &fakeRunnersClient{}, + subscriber: subscriber, + consumer: consumer, + clocks: clocks.read, + keepaliveInterval: 10 * time.Millisecond, + } + + errCh := make(chan error, 1) + go func() { + errCh <- daemon.Run(ctx, nil) + }() + waitForSyncCalls(t, errCh, consumer.Calls, 1, "start") + + // Ticks with the clocks in step are not a wake. + clocks.waitForReads(t, 3) + if got := subscriber.resubscribed.Load(); got != 0 { + t.Fatalf("resubscribed %d times with the clocks in step", got) + } + + clocks.sleep(time.Hour) + waitForSyncCalls(t, errCh, consumer.Calls, 2, "the clock jumped") + if got := subscriber.resubscribed.Load(); got != 1 { + t.Fatalf("expected one resubscribe for the jump, got %d", got) + } + + clocks.sleep(time.Hour) + waitForSyncCalls(t, errCh, consumer.Calls, 3, "the clock jumped again") + if got := subscriber.resubscribed.Load(); got != 2 { + t.Fatalf("expected a second resubscribe for a second sleep, got %d", got) + } + + stopRun(t, cancel, errCh) +} + +// One wake, three signs of it: the runner's two signals a few seconds apart and +// the clock's detection at the next tick. One reconnect, one inbox read. +func TestRunWakeRepeatsAreCoalesced(t *testing.T) { + subscriber := newFakeMessageSubscriber() + consumer := &fakeMessageConsumer{} + clocks := newFakeClocks() + 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, + clocks: clocks.read, + keepaliveInterval: 10 * time.Millisecond, + } + + errCh := make(chan error, 1) + go func() { + errCh <- daemon.Run(ctx, wake) + }() + waitForSyncCalls(t, errCh, consumer.Calls, 1, "start") + + // The runner sets the clock, then signals, then signals again. + clocks.sleep(time.Hour) + wake <- syscall.SIGCONT + wake <- syscall.SIGCONT + // The second send landed once the first was taken; the loop takes the + // second before its next tick, so a few ticks later both are handled and + // the clock has had its say. + for len(wake) > 0 { + time.Sleep(time.Millisecond) + } + clocks.waitForReads(t, 3) + + waitForSyncCalls(t, errCh, consumer.Calls, 2, "the wake") + if got := subscriber.resubscribed.Load(); got != 1 { + t.Fatalf("expected one resubscribe for one wake, got %d", got) + } + // And it stays that way: no read piles up behind the first. + clocks.waitForReads(t, 3) + if got := consumer.Calls(); got != 2 { + t.Fatalf("expected one inbox read for one wake, got %d", got-1) + } + if got := subscriber.resubscribed.Load(); got != 1 { + t.Fatalf("expected the resubscribe count to stay at one, got %d", got) + } + + stopRun(t, cancel, errCh) +} diff --git a/internal/subscriber/subscriber.go b/internal/subscriber/subscriber.go index 985007e..2c9eca6 100644 --- a/internal/subscriber/subscriber.go +++ b/internal/subscriber/subscriber.go @@ -24,6 +24,8 @@ type Subscriber struct { ready chan struct{} readyOnce sync.Once wake chan struct{} + dropMu sync.Mutex + drop context.CancelFunc } type notificationsClient interface { @@ -41,13 +43,20 @@ func (s *Subscriber) Run(ctx context.Context) error { if ctx.Err() != nil { return ctx.Err() } - stream, err := s.client.Subscribe(ctx) + // A context per attempt, so Resubscribe can end the stream it carries, + // or the wait before the next one, without ending Run. + attemptCtx, endAttempt := context.WithCancel(ctx) + s.setDrop(endAttempt) + stream, err := s.client.Subscribe(attemptCtx) if err != nil { - log.Printf("subscriber: subscribe failed: %v", err) - if err := waitWithBackoff(ctx, backoff); err != nil { + if attemptCtx.Err() == nil { + log.Printf("subscriber: subscribe failed: %v", err) + } + backoff, err = s.waitOut(ctx, attemptCtx, backoff) + endAttempt() + if err != nil { return err } - backoff = nextBackoff(backoff) continue } s.readyOnce.Do(func() { close(s.ready) }) @@ -57,17 +66,26 @@ func (s *Subscriber) Run(ctx context.Context) error { resp, err := stream.Recv() if err != nil { if ctx.Err() != nil { + endAttempt() return ctx.Err() } + if attemptCtx.Err() != nil { + // The daemon's own doing, not a failure: reopen without + // the backoff a failure earns. + log.Printf("subscriber: stream dropped; resubscribing") + endAttempt() + break + } if errors.Is(err, io.EOF) { log.Printf("subscriber: stream closed") } else { log.Printf("subscriber: stream recv failed: %v", err) } - if err := waitWithBackoff(ctx, backoff); err != nil { + backoff, err = s.waitOut(ctx, attemptCtx, backoff) + endAttempt() + if err != nil { return err } - backoff = nextBackoff(backoff) break } envelope := resp.GetEnvelope() @@ -91,6 +109,22 @@ func (s *Subscriber) Run(ctx context.Context) error { } } +// waitOut sleeps out a failure's backoff under the attempt's context and +// returns the backoff the next failure gets: doubled, or back at the start when +// Resubscribe cut the wait short, because a wake is not another failure. The +// error is ctx's own, once Run itself is done. +func (s *Subscriber) waitOut(ctx, attemptCtx context.Context, backoff time.Duration) (time.Duration, error) { + err := waitWithBackoff(attemptCtx, backoff) + if ctx.Err() != nil { + return 0, ctx.Err() + } + if err != nil { + log.Printf("subscriber: resubscribing") + return time.Second, nil + } + return nextBackoff(backoff), nil +} + func (s *Subscriber) Started() <-chan struct{} { return s.started } @@ -103,6 +137,24 @@ func (s *Subscriber) Wake() <-chan struct{} { return s.wake } +// Resubscribe ends the open stream so Run reopens it, or ends the wait after +// a failure so Run opens one now. After a wake from hibernation the far side +// of the stream is gone, and Recv would otherwise wait on it until TCP gave +// up. +func (s *Subscriber) Resubscribe() { + s.dropMu.Lock() + defer s.dropMu.Unlock() + if s.drop != nil { + s.drop() + } +} + +func (s *Subscriber) setDrop(drop context.CancelFunc) { + s.dropMu.Lock() + defer s.dropMu.Unlock() + s.drop = drop +} + func waitWithBackoff(ctx context.Context, delay time.Duration) error { if delay <= 0 { return nil diff --git a/internal/subscriber/subscriber_test.go b/internal/subscriber/subscriber_test.go index e8cbe5d..f57bfb2 100644 --- a/internal/subscriber/subscriber_test.go +++ b/internal/subscriber/subscriber_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "io" + "sync" "testing" "time" @@ -195,6 +196,136 @@ func TestSubscriberWithoutThreadWakesOnAnyThread(t *testing.T) { waitForRun(t, done) } +// A stream whose Recv ends with its context, as a gRPC stream's does. +type wakeStream struct { + done <-chan struct{} + responses chan *notificationsv1.SubscribeResponse +} + +func (s *wakeStream) Recv() (*notificationsv1.SubscribeResponse, error) { + select { + case <-s.done: + return nil, context.Canceled + case resp := <-s.responses: + return resp, nil + } +} + +type wakeNotifications struct { + mu sync.Mutex + streams []*wakeStream + failures int // subscribe attempts that fail before one succeeds + attempts int +} + +func (f *wakeNotifications) Subscribe(ctx context.Context) (platform.SubscribeStream, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.attempts++ + if f.failures > 0 { + f.failures-- + return nil, errors.New("gateway unavailable") + } + stream := &wakeStream{done: ctx.Done(), responses: make(chan *notificationsv1.SubscribeResponse, 1)} + f.streams = append(f.streams, stream) + return stream, nil +} + +func (f *wakeNotifications) Streams() []*wakeStream { + f.mu.Lock() + defer f.mu.Unlock() + return append([]*wakeStream(nil), f.streams...) +} + +func (f *wakeNotifications) Attempts() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.attempts +} + +// Resubscribe ends the stream and Run reopens it at once: the drop is the +// daemon's own, after a wake from hibernation, not a failure to back off from. +func TestSubscriberResubscribeReopensStream(t *testing.T) { + client := &wakeNotifications{} + sub := New(client, "") + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + done <- sub.Run(ctx) + }() + + select { + case <-sub.Ready(): + case <-time.After(200 * time.Millisecond): + t.Fatal("expected the first stream") + } + sub.Resubscribe() + + // Well inside the first backoff, which a deliberate drop does not wait. + deadline := time.After(500 * time.Millisecond) + for len(client.Streams()) < 2 { + select { + case <-deadline: + t.Fatalf("expected a second stream, got %d", len(client.Streams())) + case <-time.After(10 * time.Millisecond): + } + } + streams := client.Streams() + select { + case <-streams[0].done: + default: + t.Fatal("expected the first stream to be dropped") + } + + streams[1].responses <- makeMessageCreated("1f5a4e5c-350a-4f3a-8dda-0ef049b89d09") + select { + case <-sub.Wake(): + case <-time.After(200 * time.Millisecond): + t.Fatal("expected a wake from the reopened stream") + } + + cancel() + waitForRun(t, done) +} + +// A wake can land while the subscriber is waiting out a failure. The wait is +// for the failure, and the wake is not one: Resubscribe cuts it short and the +// stream is opened at once. +func TestSubscriberResubscribeCutsTheBackoffShort(t *testing.T) { + client := &wakeNotifications{failures: 1} + sub := New(client, "") + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + done <- sub.Run(ctx) + }() + + deadline := time.After(500 * time.Millisecond) + for client.Attempts() < 1 { + select { + case <-deadline: + t.Fatal("expected the first subscribe attempt") + case <-time.After(5 * time.Millisecond): + } + } + // Now inside the one-second backoff the failure earned. + sub.Resubscribe() + + select { + case <-sub.Ready(): + case <-time.After(500 * time.Millisecond): + t.Fatalf("expected the stream opened at once, got %d attempts", client.Attempts()) + } + if got := client.Attempts(); got != 2 { + t.Fatalf("expected the retry to be the second attempt, got %d", got) + } + + cancel() + waitForRun(t, done) +} + func TestNextBackoffProgression(t *testing.T) { tests := []struct { name string From 8fd06d1a024356652522a1ffdb27e7cf75a26a49 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Sat, 31 Oct 2026 12:14:47 +0100 Subject: [PATCH 3/3] Run the holder test with the wake channel Run now takes --- internal/daemon/turnboundary_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/daemon/turnboundary_test.go b/internal/daemon/turnboundary_test.go index cc57f57..9660fd1 100644 --- a/internal/daemon/turnboundary_test.go +++ b/internal/daemon/turnboundary_test.go @@ -152,7 +152,7 @@ func TestHolderModeReportsNoIdle(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) errCh := make(chan error, 1) - go func() { errCh <- daemon.Run(ctx) }() + go func() { errCh <- daemon.Run(ctx, nil) }() time.Sleep(50 * time.Millisecond) cancel()