Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7851: fix(daemon): don't count host sleep as idle-watchdog silence (#9201)
Multica Eveb115ec80f174
diff --git a/server/internal/daemon/cursor_background_watchdog_test.go b/server/internal/daemon/cursor_background_watchdog_test.goindex 74e5ba1bab..465d6f0824 100644--- a/server/internal/daemon/cursor_background_watchdog_test.go+++ b/server/internal/daemon/cursor_background_watchdog_test.go@@ -9,6 +9,7 @@ import ("time""github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/awakeclock")type backgroundToolBackend struct {@@ -25,7 +26,7 @@ func (b *backgroundToolBackend) Execute(ctx context.Context, _ string, _ agent.Estopped := make(chan struct{})var nativeCount atomic.Int32var nativeActivity atomic.Int64- nativeActivity.Store(time.Now().UnixNano())+ nativeActivity.Store(int64(awakeclock.Now()))nativeCount.Store(1)if !b.dropTranscript {messages <- agent.Message{Type: agent.MessageToolUse, Tool: "shell", CallID: "bg"}@@ -43,7 +44,7 @@ func (b *backgroundToolBackend) Execute(ctx context.Context, _ string, _ agent.E}select {case <-natural:- nativeActivity.Store(time.Now().UnixNano())+ nativeActivity.Store(int64(awakeclock.Now()))if !b.dropTranscript {messages <- agent.Message{Type: agent.MessageToolResult, Tool: "shell", CallID: "bg", Output: "raw launch result"}}@@ -69,12 +70,12 @@ func (b *backgroundToolBackend) Execute(ctx context.Context, _ string, _ agent.Eresults <- agent.Result{Status: "aborted"}}}()- return &agent.Session{Messages: messages, Result: results, ToolActivity: func() (int32, time.Time) { return nativeCount.Load(), time.Unix(0, nativeActivity.Load()) }, InterruptBackgroundTools: func() bool {+ return &agent.Session{Messages: messages, Result: results, ToolActivity: func() (int32, time.Duration) { return nativeCount.Load(), time.Duration(nativeActivity.Load()) }, InterruptBackgroundTools: func() bool {b.interrupts.Add(1)if b.invalid || !b.cleaned.CompareAndSwap(false, true) {return false}- nativeActivity.Store(time.Now().UnixNano())+ nativeActivity.Store(int64(awakeclock.Now()))if !b.dropTranscript {messages <- agent.Message{Type: agent.MessageToolResult, Tool: "shell", CallID: "bg", Output: "raw launch result"}}@@ -131,7 +132,7 @@ func TestBackgroundToolWatchdogShortOverride(t *testing.T) {var last, threshold atomic.Int64var tools atomic.Int32var fired atomic.Bool- last.Store(time.Now().UnixNano())+ last.Store(int64(awakeclock.Now()))tools.Store(1)calls := 0go new(Daemon).runIdleWatchdog(ctx, 10*time.Minute, time.Minute, &last, tools.Load, &fired, &threshold, cancel, make(chan agent.Message), func() bool { calls++; cancel(); return true }, nil, slog.Default())@@ -151,11 +152,11 @@ func TestBackgroundToolWatchdogNaturalExitRace(t *testing.T) {var last, threshold atomic.Int64var tools atomic.Int32var fired atomic.Bool- last.Store(time.Now().UnixNano())+ last.Store(int64(awakeclock.Now()))tools.Store(1)go new(Daemon).runIdleWatchdog(ctx, time.Minute, time.Minute, &last, tools.Load, &fired, &threshold, cancel, make(chan agent.Message), func() bool {tools.Store(0)- last.Store(time.Now().UnixNano())+ last.Store(int64(awakeclock.Now()))return false}, nil, slog.Default())synctest.Wait()@@ -173,13 +174,13 @@ func TestBackgroundToolWatchdogFreshActivityDuringRevalidation(t *testing.T) {defer cancel()var last, threshold atomic.Int64var fired atomic.Bool- last.Store(time.Now().UnixNano())+ last.Store(int64(awakeclock.Now()))refreshAtBoundary, refreshed := false, false// Match Session.ToolActivity's production callback: refreshing native// activity publishes a timestamp even when the tool count stays positive.toolState := func() int32 {if refreshAtBoundary && !refreshed {- last.Store(time.Now().UnixNano())+ last.Store(int64(awakeclock.Now()))refreshed = true}return 1diff --git a/server/internal/daemon/cursor_terminal_boundary_test.go b/server/internal/daemon/cursor_terminal_boundary_test.goindex 5477c534eb..8fe2cb57a0 100644--- a/server/internal/daemon/cursor_terminal_boundary_test.go+++ b/server/internal/daemon/cursor_terminal_boundary_test.go@@ -11,6 +11,7 @@ import ("time""github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/awakeclock")// The ordering both tests below pin is the one that loses a completed run:@@ -35,7 +36,7 @@ func TestIdleWatchdogYieldsToTerminalObservedDuringCleanup(t *testing.T) {var last, threshold atomic.Int64var fired atomic.Boolvar terminal atomic.Bool- last.Store(time.Now().UnixNano())+ last.Store(int64(awakeclock.Now()))// A held background tool: in flight, and its activity never moves.tools := func() int32 { return 1 }@@ -86,7 +87,7 @@ func (b *terminalRaceBackend) Execute(ctx context.Context, _ string, _ agent.Exevar nativeCount atomic.Int32var nativeActivity atomic.Int64nativeCount.Store(1)- nativeActivity.Store(time.Now().UnixNano())+ nativeActivity.Store(int64(awakeclock.Now()))messages <- agent.Message{Type: agent.MessageToolUse, Tool: "shell", CallID: "bg"}go func() {@@ -105,7 +106,7 @@ func (b *terminalRaceBackend) Execute(ctx context.Context, _ string, _ agent.Exereturn &agent.Session{Messages: messages,Result: results,- ToolActivity: func() (int32, time.Time) { return nativeCount.Load(), time.Unix(0, nativeActivity.Load()) },+ ToolActivity: func() (int32, time.Duration) { return nativeCount.Load(), time.Duration(nativeActivity.Load()) },TerminalObserved: b.terminal.Load,InterruptBackgroundTools: func() bool {b.interrupts.Add(1)@@ -188,7 +189,7 @@ func (b *lateTerminalBackend) Execute(ctx context.Context, _ string, _ agent.Exevar nativeCount atomic.Int32var nativeActivity atomic.Int64nativeCount.Store(1)- nativeActivity.Store(time.Now().UnixNano())+ nativeActivity.Store(int64(awakeclock.Now()))messages <- agent.Message{Type: agent.MessageToolUse, Tool: "shell", CallID: "bg"}go func() {@@ -209,7 +210,7 @@ func (b *lateTerminalBackend) Execute(ctx context.Context, _ string, _ agent.Exereturn &agent.Session{Messages: messages,Result: results,- ToolActivity: func() (int32, time.Time) { return nativeCount.Load(), time.Unix(0, nativeActivity.Load()) },+ ToolActivity: func() (int32, time.Duration) { return nativeCount.Load(), time.Duration(nativeActivity.Load()) },TerminalObserved: b.terminal.Load,// Nothing can be released: cleanup could not confirm ownership.InterruptBackgroundTools: func() bool { return false },diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex efbc812f14..9f48e3c53a 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -33,6 +33,7 @@ import ("github.com/multica-ai/multica/server/internal/selfexec""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/awakeclock""github.com/multica-ai/multica/server/pkg/protocol""github.com/multica-ai/multica/server/pkg/redact""github.com/multica-ai/multica/server/pkg/skillbundle"@@ -9369,13 +9370,15 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, prodefer drainCancel()var toolCount atomic.Int32- // lastActivityAt records (as unix nanos) when the drain loop most+ // lastActivityAt records (as awakeclock nanos) when the drain loop most// recently received a message from the backend. The idle watchdog// reads this to decide whether the agent has gone silent for too long.+ // It is an awake-time reading, not wall time, so a host suspend is never+ // charged to the agent as silence (GitHub #9024).// Initialise to the start so a backend that never emits a single// message also trips the watchdog.var lastActivityAt atomic.Int64- lastActivityAt.Store(time.Now().UnixNano())+ lastActivityAt.Store(int64(awakeclock.Now()))// inFlightTools counts tool_use messages that haven't yet been paired// with a matching tool_result. A non-zero count means the agent is// legitimately waiting on a tool (e.g. `npm install`, `docker build`)@@ -9402,7 +9405,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, procount, at := session.ToolActivity()for {previous := lastActivityAt.Load()- if at.UnixNano() <= previous || lastActivityAt.CompareAndSwap(previous, at.UnixNano()) {+ if int64(at) <= previous || lastActivityAt.CompareAndSwap(previous, int64(at)) {break}}@@ -9559,7 +9562,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro// slow downstream call (mu.Lock contention, batch resize)// can't be misattributed to backend silence.observedAt := time.Now().UTC()- lastActivityAt.Store(observedAt.UnixNano())+ lastActivityAt.Store(int64(awakeclock.Now()))switch msg.Type {case agent.MessageStatus:// Persist the session/work_dir as soon as the backend@@ -9921,7 +9924,19 @@ func idleWatchdogTickInterval(window time.Duration) time.Duration {//// Polling rate comes from idleWatchdogTickInterval, so a run is force-stopped// somewhere between its budget and budget + tick, never earlier.+//+// Budgets are measured on awakeclock, so they count only time the host was+// awake. lastActivityAt and every native tool timestamp are awakeclock+// readings. A laptop that sleeps through a run resumes with its silence+// exactly where it was before the lid closed (GitHub #9024).func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow time.Duration, lastActivityAt *atomic.Int64, inFlightTools func() int32, fired *atomic.Bool, firedThreshold *atomic.Int64, cancel context.CancelFunc, messages <-chan agent.Message, interruptBackground func() bool, terminalObserved func() bool, taskLog *slog.Logger) {+ d.runIdleWatchdogWithClock(agentCtx, window, toolWindow, lastActivityAt, inFlightTools, fired, firedThreshold, cancel, messages, interruptBackground, terminalObserved, taskLog, awakeclock.Now)+}++// runIdleWatchdogWithClock is runIdleWatchdog with the awake clock injected,+// so tests can simulate a host suspend: wall time that passes while the+// awake reading stands still.+func (d *Daemon) runIdleWatchdogWithClock(agentCtx context.Context, window, toolWindow time.Duration, lastActivityAt *atomic.Int64, inFlightTools func() int32, fired *atomic.Bool, firedThreshold *atomic.Int64, cancel context.CancelFunc, messages <-chan agent.Message, interruptBackground func() bool, terminalObserved func() bool, taskLog *slog.Logger, awakeNow func() time.Duration) {tickWindow := windowif toolWindow > 0 && toolWindow < tickWindow {tickWindow = toolWindow@@ -9945,8 +9960,8 @@ func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow ti}threshold = toolWindow}- last := time.Unix(0, lastActivityAt.Load())- idleFor := time.Since(last)+ last := lastActivityAt.Load()+ idleFor := awakeNow() - time.Duration(last)if idleFor < threshold {continue}@@ -9966,7 +9981,7 @@ func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow tireturn}if toolInFlight && interruptBackground != nil && interruptBackground() {- lastActivityAt.Store(time.Now().UnixNano())+ lastActivityAt.Store(int64(awakeNow()))taskLog.Info("tool watchdog stopped background tools; waiting for agent result")continue}@@ -9978,7 +9993,7 @@ func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow ti// callback may publish newer activity without changing the count.currentToolInFlight := inFlightTools() > 0currentActivity := lastActivityAt.Load()- if currentActivity != last.UnixNano() ||+ if currentActivity != last ||currentToolInFlight != toolInFlight || len(messages) > 0 {continue}diff --git a/server/internal/daemon/idle_watchdog_suspend_test.go b/server/internal/daemon/idle_watchdog_suspend_test.gonew file mode 100644index 0000000000..7a0ef3a3dd--- /dev/null+++ b/server/internal/daemon/idle_watchdog_suspend_test.go@@ -0,0 +1,178 @@+package daemon++import (+ "context"+ "log/slog"+ "sync"+ "sync/atomic"+ "testing"+ "testing/synctest"+ "time"++ "github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/awakeclock"+)++// hostClock simulates a host that can suspend. Bubble time stands in for+// wall time. awake() is what awakeclock reports: it freezes while the host+// sleeps and then resumes without the slept interval. wall() is the+// pre-#9024 reading, used as a control to prove that each scenario really+// lands on the bug.+type hostClock struct {+ mu sync.Mutex+ slept time.Duration+ asleep bool+ frozen time.Duration+}++func (c *hostClock) awake() time.Duration {+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.asleep {+ return c.frozen+ }+ return awakeclock.Now() - c.slept+}++func (c *hostClock) wall() time.Duration { return awakeclock.Now() }++// hostSleep suspends the host for d. Ticks that fire meanwhile model Windows,+// where the overdue tick runs as soon as the host wakes. They see the frozen+// awake reading.+func (c *hostClock) hostSleep(d time.Duration) {+ c.mu.Lock()+ c.frozen = awakeclock.Now() - c.slept+ c.asleep = true+ c.mu.Unlock()+ time.Sleep(d)+ c.mu.Lock()+ c.slept += d+ c.asleep = false+ c.mu.Unlock()+}++type suspendScenario struct {+ name string+ window time.Duration+ tools int32+ // run drives the scenario and returns at the checkpoint where awake+ // silence is still under window. next returns once awake silence has+ // passed window plus one tick.+ run, next func(c *hostClock, stamp func())+}++// GitHub #9024 and the PR review: a sleep must never count as silence, both+// when it falls inside one tick interval and when it begins right after a+// tick on a host whose overdue tick fires as soon as it wakes. A run that+// stays silent for a full window of awake time must still be force-stopped.+func TestIdleWatchdogDoesNotCountHostSuspendAsSilence(t *testing.T) {+ scenarios := []suspendScenario{+ {+ // 10m window (the OpenCode budget) and 5m ticks. Silent for 3m at+ // the 5m tick, then a 4m sleep that stays inside one tick+ // interval. The tick-gap heuristic credited none of it, so 9m of+ // awake silence read as 13m.+ name: "sleep inside one tick interval",+ window: 10 * time.Minute,+ run: func(c *hostClock, stamp func()) {+ time.Sleep(2 * time.Minute)+ stamp()+ time.Sleep(3*time.Minute + time.Second)+ c.hostSleep(4 * time.Minute)+ time.Sleep(6 * time.Minute) // awake silence: 9m1s+ },+ next: func(*hostClock, func()) { time.Sleep(6 * time.Minute) }, // 15m1s+ },+ {+ // 2h window. Silent for 1h57m, then a 2h5m sleep straight after+ // a tick, with the overdue tick firing on wake. The heuristic+ // credited only gap−tick (2h), so 1h58m read as 2h3m.+ name: "long sleep right after a tick, overdue tick on wake",+ window: 2 * time.Hour,+ tools: 1,+ run: func(c *hostClock, stamp func()) {+ time.Sleep(time.Hour + 57*time.Minute)+ c.hostSleep(2*time.Hour + 5*time.Minute)+ time.Sleep(time.Minute) // awake silence: 1h58m+ },+ next: func(*hostClock, func()) { time.Sleep(7 * time.Minute) }, // 2h5m+ },+ {+ name: "sleep far longer than the window",+ window: time.Hour,+ run: func(c *hostClock, _ func()) {+ time.Sleep(10 * time.Minute)+ c.hostSleep(3 * time.Hour)+ time.Sleep(21 * time.Minute) // awake silence: 31m+ },+ next: func(*hostClock, func()) { time.Sleep(35 * time.Minute) }, // 66m+ },+ }+ for _, sc := range scenarios {+ t.Run(sc.name, func(t *testing.T) {+ t.Run("awake clock", func(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ c := &hostClock{}+ fired, threshold := runSuspendScenario(t, sc, c, c.awake)+ sc.run(c, fired.stamp)+ synctest.Wait()+ if fired.Load() {+ t.Fatal("host suspend was counted as agent silence and force-stopped the run")+ }+ sc.next(c, fired.stamp)+ synctest.Wait()+ if !fired.Load() {+ t.Fatal("watchdog no longer stops a run silent for a full awake window")+ }+ if got := time.Duration(threshold.Load()); got != sc.window {+ t.Fatalf("threshold = %s, want %s", got, sc.window)+ }+ })+ })+ // Control: the same timeline on the wall clock fires early. If it+ // did not, the scenario would not exercise the defect.+ t.Run("wall clock control", func(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ c := &hostClock{}+ fired, _ := runSuspendScenario(t, sc, c, c.wall)+ sc.run(c, fired.stamp)+ synctest.Wait()+ if !fired.Load() {+ t.Fatal("scenario no longer reproduces the wall-clock false positive")+ }+ })+ })+ })+ }+}++type firedProbe struct {+ atomic.Bool+ stamp func()+}++func runSuspendScenario(t *testing.T, sc suspendScenario, c *hostClock, now func() time.Duration) (*firedProbe, *atomic.Int64) {+ t.Helper()+ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)+ var last, threshold atomic.Int64+ probe := &firedProbe{}+ last.Store(int64(now()))+ probe.stamp = func() { last.Store(int64(now())) }+ // Mirrors the Cursor native-tool callback, which republishes its own+ // pre-sleep stamp on every read. The CAS only moves the stamp forward.+ staleToolStamp := last.Load()+ tools := func() int32 {+ for {+ previous := last.Load()+ if staleToolStamp <= previous || last.CompareAndSwap(previous, staleToolStamp) {+ break+ }+ }+ return sc.tools+ }+ go new(Daemon).runIdleWatchdogWithClock(ctx, sc.window, sc.window, &last, tools, &probe.Bool, &threshold,+ cancel, make(chan agent.Message), nil, nil, slog.Default(), now)+ synctest.Wait()+ return probe, &threshold+}diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 1352d8a6c5..0dcb3a80f2 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -168,7 +168,9 @@ type Session struct {// transition time, independent of the best-effort transcript. Nil uses the// daemon's message-based accounting. The timestamp gives completed tools a// fresh idle budget even when their transcript message has not drained yet.- ToolActivity func() (int32, time.Time)+ // The timestamp is an awakeclock reading (see package awakeclock), the same+ // clock the idle watchdog measures, so host sleep never counts as silence.+ ToolActivity func() (int32, time.Duration)// InterruptBackgroundTools stops owned background tools at the daemon's// tool watchdog boundary without cancelling the agent. True means at least// one tool completed/was stopped and released from accounting; the watchdogdiff --git a/server/pkg/agent/cursor_background.go b/server/pkg/agent/cursor_background.goindex 21d798eff1..7c70558dbf 100644--- a/server/pkg/agent/cursor_background.go+++ b/server/pkg/agent/cursor_background.go@@ -3,10 +3,13 @@ package agentimport ("context""log/slog"+ "math""os/exec""sync""sync/atomic""time"++ "github.com/multica-ai/multica/server/pkg/awakeclock")type cursorBackgroundTool struct {@@ -48,6 +51,9 @@ func (b *cursorBackgroundTools) TerminalObserved() bool { return b.terminal.Loadfunc newCursorBackgroundTools(ctx context.Context, cmd *exec.Cmd, messages chan<- Message, logger *slog.Logger) *cursorBackgroundTools {b := &cursorBackgroundTools{ctx: ctx, cmd: cmd, messages: messages, logger: logger, stop: make(chan struct{}), done: make(chan struct{})}+ // "No tool activity yet" must sort before every awakeclock reading. Those+ // readings can be negative, so zero is not a safe sentinel.+ b.lastToolActivity.Store(math.MinInt64)go func() {defer close(b.done)// This only observes natural process exit; it never measures inactivity.@@ -67,13 +73,15 @@ func newCursorBackgroundTools(ctx context.Context, cmd *exec.Cmd, messages chan<return b}-func (b *cursorBackgroundTools) Activity() (int32, time.Time) {- return b.inFlight.Load(), time.Unix(0, b.lastToolActivity.Load())+// Activity reports in-flight tools and the awakeclock reading of the last+// tool transition. It uses the same clock as the daemon's idle watchdog.+func (b *cursorBackgroundTools) Activity() (int32, time.Duration) {+ return b.inFlight.Load(), time.Duration(b.lastToolActivity.Load())}func (b *cursorBackgroundTools) Send(msg Message) {if msg.Type == MessageToolUse || msg.Type == MessageToolResult {- now := time.Now().UnixNano()+ now := int64(awakeclock.Now())for {previous := b.lastToolActivity.Load()if now <= previous || b.lastToolActivity.CompareAndSwap(previous, now) {diff --git a/server/pkg/awakeclock/awakeclock.go b/server/pkg/awakeclock/awakeclock.gonew file mode 100644index 0000000000..3944b955fe--- /dev/null+++ b/server/pkg/awakeclock/awakeclock.go@@ -0,0 +1,23 @@+// Package awakeclock reads a clock that advances only while the host is+// awake. Liveness budgets (the daemon's idle watchdog, GitHub #9024) must+// measure it rather than wall time: nothing can run while the host is+// suspended, so slept time says nothing about whether a process is hung.+//+// Readings are durations from an arbitrary process-wide origin. Only the+// difference between two readings is meaningful, and absolute values may be+// negative (for example inside a testing/synctest bubble).+package awakeclock++import "time"++// origin carries Go's monotonic reading. time.Since(origin) therefore uses+// the runtime's monotonic clock, which already stops during suspend on+// Linux (CLOCK_MONOTONIC) and macOS (mach_absolute_time). On Windows the+// runtime clock keeps counting through sleep, so sleptSinceOrigin+// subtracts it there; it returns 0 everywhere else.+var origin = time.Now()++// Now returns the awake time elapsed since the process-wide origin.+func Now() time.Duration {+ return time.Since(origin) - sleptSinceOrigin()+}diff --git a/server/pkg/awakeclock/awakeclock_other.go b/server/pkg/awakeclock/awakeclock_other.gonew file mode 100644index 0000000000..1250bad2b1--- /dev/null+++ b/server/pkg/awakeclock/awakeclock_other.go@@ -0,0 +1,9 @@+//go:build !windows++package awakeclock++import "time"++// sleptSinceOrigin is zero because the runtime monotonic clock already+// excludes suspend on Linux and macOS.+func sleptSinceOrigin() time.Duration { return 0 }diff --git a/server/pkg/awakeclock/awakeclock_test.go b/server/pkg/awakeclock/awakeclock_test.gonew file mode 100644index 0000000000..d8aed0b726--- /dev/null+++ b/server/pkg/awakeclock/awakeclock_test.go@@ -0,0 +1,37 @@+package awakeclock++import (+ "testing"+ "testing/synctest"+ "time"+)++func TestNowTracksAwakeTime(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ start := Now()+ time.Sleep(90 * time.Minute)+ if got := Now() - start; got != 90*time.Minute {+ t.Fatalf("elapsed = %s, want 90m", got)+ }+ })+}++func TestSleptFromReadings(t *testing.T) {+ // 5h since boot including sleep; 3h awake → 2h slept.+ if got := sleptFromReadings(uint64((5 * time.Hour).Milliseconds()), uint64(3*time.Hour/100)); got != 2*time.Hour {+ t.Fatalf("slept = %s, want 2h", got)+ }+ // Tick count lags by sub-ms resolution: clamped, never negative.+ if got := sleptFromReadings(1000, uint64(1000*time.Millisecond/100)+5000); got != 0 {+ t.Fatalf("slept = %s, want 0", got)+ }+}++func TestSleptDelta(t *testing.T) {+ if got := sleptDelta(time.Hour, 3*time.Hour); got != 2*time.Hour {+ t.Fatalf("delta = %s, want 2h", got)+ }+ if got := sleptDelta(time.Hour, time.Hour-time.Millisecond); got != 0 {+ t.Fatalf("delta = %s, want 0", got)+ }+}diff --git a/server/pkg/awakeclock/awakeclock_windows.go b/server/pkg/awakeclock/awakeclock_windows.gonew file mode 100644index 0000000000..66836fc154--- /dev/null+++ b/server/pkg/awakeclock/awakeclock_windows.go@@ -0,0 +1,61 @@+//go:build windows++package awakeclock++import (+ "sync/atomic"+ "time"+ "unsafe"++ "golang.org/x/sys/windows"+)++// Windows' runtime monotonic clock (interrupt time) keeps counting while the+// host sleeps or hibernates. Both readings below count from boot:+//+// - GetTickCount64 includes sleep (ms resolution).+// - QueryUnbiasedInterruptTime excludes it (100 ns units).+//+// Their difference is the total time the host has spent asleep since boot.+// Both are available since Windows 7.+// https://learn.microsoft.com/en-us/windows/win32/sysinfo/interrupt-time+var (+ kernel32 = windows.NewLazySystemDLL("kernel32.dll")+ procGetTickCount64 = kernel32.NewProc("GetTickCount64")+ procQueryUnbiasedInterruptTime = kernel32.NewProc("QueryUnbiasedInterruptTime")++ originSlept = hostSleptSinceBoot()+ // maxSlept keeps the correction monotone. The tick count has+ // millisecond resolution, so successive differences can jitter down by a+ // few ms. Total slept time never actually decreases.+ maxSlept atomic.Int64+)++func sleptSinceOrigin() time.Duration {+ slept := sleptDelta(originSlept, hostSleptSinceBoot())+ for {+ previous := maxSlept.Load()+ if int64(slept) <= previous {+ return time.Duration(previous)+ }+ if maxSlept.CompareAndSwap(previous, int64(slept)) {+ return slept+ }+ }+}++// hostSleptSinceBoot returns total host sleep since boot, or 0 if the APIs+// cannot be called. In that case the clock falls back to the runtime+// monotonic clock, which matches the behaviour before this package existed.+func hostSleptSinceBoot() time.Duration {+ if procGetTickCount64.Find() != nil || procQueryUnbiasedInterruptTime.Find() != nil {+ return 0+ }+ tickMs, _, _ := procGetTickCount64.Call()+ var unbiased100ns uint64+ ok, _, _ := procQueryUnbiasedInterruptTime.Call(uintptr(unsafe.Pointer(&unbiased100ns)))+ if ok == 0 {+ return 0+ }+ return sleptFromReadings(uint64(tickMs), unbiased100ns)+}diff --git a/server/pkg/awakeclock/sleep.go b/server/pkg/awakeclock/sleep.gonew file mode 100644index 0000000000..92d2229bb4--- /dev/null+++ b/server/pkg/awakeclock/sleep.go@@ -0,0 +1,22 @@+package awakeclock++import "time"++// sleptFromReadings converts a sleep-inclusive tick count (ms) and a+// sleep-exclusive interrupt time (100 ns) into total slept time. A negative+// result comes from the ms tick resolution and is clamped to zero.+func sleptFromReadings(tickMs, unbiased100ns uint64) time.Duration {+ slept := time.Duration(tickMs)*time.Millisecond - time.Duration(unbiased100ns)*100+ if slept < 0 {+ return 0+ }+ return slept+}++// sleptDelta returns sleep accrued since origin, never negative.+func sleptDelta(origin, now time.Duration) time.Duration {+ if now < origin {+ return 0+ }+ return now - origin+}