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