Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
perf(heartbeat): batch runtime last_seen_at writes (#2213)
LinYushencc527c34be82
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 403fe54f66..1d9c6b45e9 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -277,10 +277,17 @@ func main() {}}+ // Construct the BatchedHeartbeatScheduler before the router so it can+ // be injected into the Handler. The Run goroutine starts below+ // alongside the sweeper, and Stop is called explicitly during graceful+ // shutdown so any pending bumps are flushed before we exit.+ heartbeatScheduler := handler.NewBatchedHeartbeatScheduler(queries, handler.DefaultHeartbeatBatchInterval)+r := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{- HTTPMetrics: httpMetrics,- DaemonHub: daemonHub,- DaemonWakeup: daemonWakeup,+ HTTPMetrics: httpMetrics,+ DaemonHub: daemonHub,+ DaemonWakeup: daemonWakeup,+ HeartbeatScheduler: heartbeatScheduler,})srv := &http.Server{@@ -306,6 +313,7 @@ func main() {// Start background sweeper to mark stale runtimes as offline.go runRuntimeSweeper(sweepCtx, queries, liveness, taskSvc, bus)+ go heartbeatScheduler.Run(sweepCtx)go runAutopilotScheduler(autopilotCtx, queries, autopilotSvc)go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())go runDBStatsLogger(sweepCtx, pool)@@ -332,9 +340,12 @@ func main() {<-quitslog.Info("shutting down server")- sweepCancel()autopilotCancel()+ // Order matters: drain in-flight HTTP first so any heartbeat handlers+ // finish calling Schedule() before we stop the scheduler. Otherwise a+ // late heartbeat could enqueue a pending ID after Run has already+ // drained and exited, and Stop() would not flush it.apiShutdownCtx, apiShutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)if err := srv.Shutdown(apiShutdownCtx); err != nil {apiShutdownCancel()@@ -343,6 +354,11 @@ func main() {}apiShutdownCancel()+ // HTTP is fully drained — safe to stop the sweeper and flush the+ // final batch of queued heartbeat bumps.+ sweepCancel()+ heartbeatScheduler.Stop()+if metricsServer != nil {metricsShutdownCtx, metricsShutdownCancel := context.WithTimeout(context.Background(), 3*time.Second)if err := metricsServer.Shutdown(metricsShutdownCtx); err != nil {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 818e8ab92b..f2fbf4a7df 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -72,6 +72,11 @@ type RouterOptions struct {HTTPMetrics *obsmetrics.HTTPMetricsDaemonHub *daemonws.HubDaemonWakeup service.TaskWakeupNotifier+ // HeartbeatScheduler, when non-nil, replaces the default synchronous+ // passthrough scheduler on the constructed Handler. main.go injects a+ // BatchedHeartbeatScheduler here so the caller can also drive Run/Stop;+ // tests leave this nil and get the legacy synchronous behavior.+ HeartbeatScheduler handler.HeartbeatScheduler}func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticsClient analytics.Client, rdb *redis.Client, opts RouterOptions) chi.Router {@@ -112,6 +117,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.LocalSkillImportStore = handler.NewRedisLocalSkillImportStore(rdb)h.LivenessStore = handler.NewRedisLivenessStore(rdb)}+ if opts.HeartbeatScheduler != nil {+ h.HeartbeatScheduler = opts.HeartbeatScheduler+ }// Auth caches: PAT cache is shared between the regular Auth middleware,// the DaemonAuth fallback (mul_) path, and the revoke handler// (invalidate). DaemonTokenCache backs the DaemonAuth mdt_ path. Bothdiff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.goindex dcb34e04f4..4dd00f5b45 100644--- a/server/cmd/server/runtime_sweeper.go+++ b/server/cmd/server/runtime_sweeper.go@@ -19,13 +19,14 @@ const (sweepInterval = 30 * time.Second// staleThresholdSeconds marks runtimes offline if no heartbeat for this// long. Must be strictly greater than runtimeHeartbeatDBFlushInterval- // (60s in handler/daemon.go) plus one daemon heartbeat cycle (~15s) so- // the DB stale window never trips on an alive-but-DB-lagging runtime- // when the sweeper's Redis check errors and we fall back to the DB.- // 90s leaves a 15s buffer above the 75s worst-case DB age and still- // keeps detection latency for a genuinely-dead runtime under- // staleThreshold + sweepInterval = 120s.- staleThresholdSeconds = 90.0+ // (60s in handler/daemon.go) plus one daemon heartbeat cycle (~15s)+ // plus the BatchedHeartbeatScheduler tick interval (~30s) so the DB+ // stale window never trips on an alive-but-DB-lagging runtime when the+ // sweeper's Redis check errors and we fall back to the DB.+ // 150s leaves a 45s buffer above the 105s worst-case DB age, and keeps+ // detection latency for a genuinely-dead runtime under staleThreshold ++ // sweepInterval = 180s (~3 minutes).+ staleThresholdSeconds = 150.0// offlineRuntimeTTLSeconds deletes offline runtimes with no active agents// after this duration. 7 days gives users plenty of time to restart daemons.offlineRuntimeTTLSeconds = 7 * 24 * 3600.0diff --git a/server/cmd/server/runtime_sweeper_race_test.go b/server/cmd/server/runtime_sweeper_race_test.goindex f2de6f5256..f6c2079ec8 100644--- a/server/cmd/server/runtime_sweeper_race_test.go+++ b/server/cmd/server/runtime_sweeper_race_test.go@@ -25,7 +25,10 @@ func TestMarkRuntimesOfflineByIDs_RespectsConcurrentHeartbeat(t *testing.T) {queries := db.New(testPool)// Insert an "online" runtime whose last_seen_at is well past the stale- // threshold — the SELECT step would pick this up as a candidate.+ // threshold — the SELECT step would pick this up as a candidate. Use+ // 2× the threshold so this stays correct if staleThresholdSeconds is+ // retuned in the future.+ staleSeed := time.Duration(staleThresholdSeconds*2) * time.Secondvar runtimeID stringif err := testPool.QueryRow(ctx, `INSERT INTO agent_runtime (@@ -33,9 +36,9 @@ func TestMarkRuntimesOfflineByIDs_RespectsConcurrentHeartbeat(t *testing.T) {status, device_info, metadata, last_seen_at)VALUES ($1, NULL, $2, 'cloud', 'claude',- 'online', '', '{}'::jsonb, now() - interval '5 minutes')+ 'online', '', '{}'::jsonb, now() - make_interval(secs => $3))RETURNING id- `, testWorkspaceID, "race-test-runtime").Scan(&runtimeID); err != nil {+ `, testWorkspaceID, "race-test-runtime", staleSeed.Seconds()).Scan(&runtimeID); err != nil {t.Fatalf("seed runtime: %v", err)}t.Cleanup(func() {@@ -91,6 +94,7 @@ func TestMarkRuntimesOfflineByIDs_OfflinesGenuinelyStale(t *testing.T) {ctx := context.Background()queries := db.New(testPool)+ staleSeed := time.Duration(staleThresholdSeconds*2) * time.Secondvar runtimeID stringif err := testPool.QueryRow(ctx, `INSERT INTO agent_runtime (@@ -98,9 +102,9 @@ func TestMarkRuntimesOfflineByIDs_OfflinesGenuinelyStale(t *testing.T) {status, device_info, metadata, last_seen_at)VALUES ($1, NULL, $2, 'cloud', 'claude',- 'online', '', '{}'::jsonb, now() - interval '5 minutes')+ 'online', '', '{}'::jsonb, now() - make_interval(secs => $3))RETURNING id- `, testWorkspaceID, "race-test-stale-runtime").Scan(&runtimeID); err != nil {+ `, testWorkspaceID, "race-test-stale-runtime", staleSeed.Seconds()).Scan(&runtimeID); err != nil {t.Fatalf("seed runtime: %v", err)}t.Cleanup(func() {diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 948a242a02..9a9acfaf00 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -531,29 +531,41 @@ type DaemonHeartbeatRequest struct {// to claim, so we never start a claim we might have to abort.const heartbeatHasPendingTimeout = 1 * time.Second-// runtimeLivenessTTL is how long a Redis liveness record stays valid. Set-// equal to the runtime sweeper's stale threshold so a runtime that stops-// heartbeating expires out of Redis at the same instant the DB stale window-// would mark it offline. Anything shorter would create a window where Redis-// says "dead" but the DB still says "online", confusing the sweeper filter.+// runtimeLivenessTTL is how long a Redis liveness record stays valid before+// expiring. The daemon refreshes it every heartbeat (~15s), so this just+// needs to be a few heartbeats long — the value (90s) tolerates ~6 missed+// beats before Redis declares the runtime dead.+//+// It is intentionally shorter than the sweeper's stale threshold (150s in+// cmd/server/runtime_sweeper.go). That ordering is safe and desirable:+// Redis can declare a runtime dead before the DB stale window opens, and+// the sweeper will simply ignore it until the DB column also crosses the+// threshold. The unsafe direction would be the opposite (Redis claiming+// "alive" past the DB stale window, masking a truly dead runtime when the+// sweeper consults Redis as the source of truth) — that cannot happen here.const runtimeLivenessTTL = 90 * time.Second// runtimeHeartbeatDBFlushInterval is the maximum staleness we tolerate on// agent_runtime.last_seen_at while Redis is the active liveness source. When-// last_seen_at gets older than this, the heartbeat path forces a DB write so-// (a) the UI's "last seen" display stays bounded and (b) the sweeper's+// last_seen_at gets older than this, the heartbeat path schedules a DB write+// so (a) the UI's "last seen" display stays bounded and (b) the sweeper's// DB-only fallback path (used when an IsAliveBatch call to Redis errors) does// not false-positive on alive-but-Redis-only runtimes.//// Load-bearing invariant: this must be strictly less than the sweeper's-// stale threshold (90s in cmd/server/runtime_sweeper.go). DB age for an-// alive runtime is bounded by flush + heartbeat_interval (~75s with 60s-// flush + 15s daemon cadence), so a sweeper that falls back to the DB stale-// window cannot mistakenly mark it offline.+// stale threshold (150s in cmd/server/runtime_sweeper.go) MINUS one daemon+// heartbeat cycle (~15s) MINUS the BatchedHeartbeatScheduler tick interval+// (~30s). Worst-case DB age for an alive runtime is therefore bounded by+// flush + heartbeat + batchTick = 60 + 15 + 30 = 105s, leaving a 45s buffer+// below the 150s stale window. If you tune any of these constants, recompute+// the chain and keep at least a one-tick buffer.//-// At the default 15s daemon heartbeat cadence, a 60s flush means each-// runtime writes the DB roughly once every four beats — a 4x reduction-// versus rewriting on every beat.+// We intentionally keep the per-runtime flush throttle at 60s (rather than+// pushing it higher) so a crashed runtime is detected within ~150s instead+// of ~10 minutes. The bulk of the DB-pressure win comes from batched+// coalescing in HeartbeatScheduler — at 70 online runtimes that collapses+// ~17 single-row UPDATE/s into ~0.03 bulk UPDATE/s (one per batch tick),+// independent of how the per-runtime throttle is tuned.const runtimeHeartbeatDBFlushInterval = 60 * time.Secondfunc (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {@@ -684,6 +696,10 @@ func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws// When LivenessStore is unavailable (no Redis configured) or any Touch call// errors, recordHeartbeat falls back to writing the DB on every beat — that// is the original behavior and keeps the sweeper's DB-only path correct.+//+// The actual DB write is delegated to h.HeartbeatScheduler so production can+// coalesce many runtimes' bumps into one bulk UPDATE per tick. See+// heartbeat_scheduler.go for the two implementations.func (h *Handler) recordHeartbeat(ctx context.Context, rt db.AgentRuntime) error {now := time.Now()@@ -711,29 +727,10 @@ func (h *Handler) recordHeartbeat(ctx context.Context, rt db.AgentRuntime) errorreturn nil}- // Online rows take the cheap path: a single non-indexed column write- // that stays HOT-eligible. Only the offline→online transition (or a- // row that has never been seen) needs to flip status and updated_at.- //- // rt.Status was read from a prior SELECT and can race with the- // sweeper: between that SELECT and this UPDATE the sweeper might have- // flipped the row to offline. TouchAgentRuntimeLastSeen carries a- // status='online' predicate and reports affected rows, so we can- // detect the race (rows == 0) and recover via MarkAgentRuntimeOnline,- // matching the legacy UpdateAgentRuntimeHeartbeat behavior of always- // re-asserting online on every heartbeat.- if rt.Status == "online" && rt.LastSeenAt.Valid {- rows, err := h.Queries.TouchAgentRuntimeLastSeen(ctx, rt.ID)- if err != nil {- return err- }- if rows > 0 {- return nil- }- // Fall through: sweeper raced us to offline; flip back online.- }- _, err := h.Queries.MarkAgentRuntimeOnline(ctx, rt.ID)- return err+ // Either bumps last_seen_at on an already-online row (Touch + race+ // fallback) or flips status from offline to online. The scheduler+ // chooses sync vs batched per case; see HeartbeatScheduler doc.+ return h.HeartbeatScheduler.Schedule(ctx, rt)}// heartbeatMetrics carries per-stage timings out of processHeartbeat so thediff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 831647f761..c1fcc22f7e 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -64,6 +64,7 @@ type Handler struct {LocalSkillListStore LocalSkillListStoreLocalSkillImportStore LocalSkillImportStoreLivenessStore LivenessStore+ HeartbeatScheduler HeartbeatSchedulerStorage storage.StorageCFSigner *auth.CloudFrontSignerAnalytics analytics.Client@@ -103,6 +104,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventLocalSkillListStore: NewInMemoryLocalSkillListStore(),LocalSkillImportStore: NewInMemoryLocalSkillImportStore(),LivenessStore: NewNoopLivenessStore(),+ HeartbeatScheduler: NewPassthroughHeartbeatScheduler(queries),Storage: store,CFSigner: cfSigner,Analytics: analyticsClient,diff --git a/server/internal/handler/heartbeat_scheduler.go b/server/internal/handler/heartbeat_scheduler.gonew file mode 100644index 0000000000..a2d1cab643--- /dev/null+++ b/server/internal/handler/heartbeat_scheduler.go@@ -0,0 +1,216 @@+package handler++import (+ "context"+ "log/slog"+ "sync"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// HeartbeatScheduler decides how a "this runtime is alive, bump its+// last_seen_at" request actually reaches the database.+//+// Two implementations exist:+//+// - PassthroughHeartbeatScheduler runs the legacy synchronous TouchAgentRuntimeLastSeen+// followed by a MarkAgentRuntimeOnline fallback when the touch matches zero rows+// (sweeper-race recovery). It is the default Handler wiring so unit tests+// observe the bump immediately and the existing race-recovery test stays valid.+//+// - BatchedHeartbeatScheduler queues runtime IDs in memory and flushes them as a+// single bulk UPDATE every tick. Production wires this so a fleet of N runtimes+// beating every 15s costs ~1 DB transaction per tick instead of N. Sync paths+// (status flip, never-seen rows) still go through MarkAgentRuntimeOnline+// immediately; only the hot "online row, just bumping last_seen_at" path is+// batched. See cmd/server/main.go for the goroutine wiring and shutdown drain.+type HeartbeatScheduler interface {+ // Schedule is called from the heartbeat hot path after the per-row flush+ // window check has decided a DB write is warranted. Implementations must+ // preserve the sweeper-race semantics: if rt.Status was "online" at SELECT+ // time but the row is now offline, the scheduler must eventually flip it+ // back online (sync path immediately; batched path defers to the runtime's+ // next beat, which will see status="offline" and take the sync branch in+ // recordHeartbeat).+ Schedule(ctx context.Context, rt db.AgentRuntime) error+}++// PassthroughHeartbeatScheduler is the synchronous, legacy-behavior scheduler.+// Used as the default in handler.New so tests observe DB writes immediately,+// and as the inline fallback inside BatchedHeartbeatScheduler for cases that+// must commit before returning (offline→online flip, never-seen runtime).+type PassthroughHeartbeatScheduler struct {+ queries *db.Queries+}++func NewPassthroughHeartbeatScheduler(queries *db.Queries) *PassthroughHeartbeatScheduler {+ return &PassthroughHeartbeatScheduler{queries: queries}+}++func (p *PassthroughHeartbeatScheduler) Schedule(ctx context.Context, rt db.AgentRuntime) error {+ if rt.Status == "online" && rt.LastSeenAt.Valid {+ rows, err := p.queries.TouchAgentRuntimeLastSeen(ctx, rt.ID)+ if err != nil {+ return err+ }+ if rows > 0 {+ return nil+ }+ // Sweeper raced us to offline between the SELECT and this UPDATE.+ // Fall through to MarkAgentRuntimeOnline to flip the row back.+ }+ _, err := p.queries.MarkAgentRuntimeOnline(ctx, rt.ID)+ return err+}++// BatchedHeartbeatScheduler coalesces same-id Schedule calls within a tick+// window into a single bulk UPDATE.+//+// Concurrency model:+// - Schedule grabs a short mutex, inserts into a map (deduped), releases.+// - A single goroutine (Run) drains the map every tickInterval into a bulk+// UPDATE.+// - Stop signals the run loop, which performs one final drain so pending+// IDs are not lost on graceful shutdown.+//+// Bounded growth: pending is keyed by runtime ID, so its size is bounded by+// the active runtime fleet (one entry per heartbeating runtime per tick).+// Persistent DB errors are logged but do NOT re-queue the failed IDs — the+// next beat from each runtime will reschedule naturally, and re-queuing on+// a hard outage would just balloon the map.+type BatchedHeartbeatScheduler struct {+ queries *db.Queries+ fallback *PassthroughHeartbeatScheduler+ tickInterval time.Duration++ mu sync.Mutex+ pending map[pgtype.UUID]struct{}++ stopOnce sync.Once+ stopCh chan struct{}+ doneCh chan struct{}+}++// DefaultHeartbeatBatchInterval is the production tick cadence for the+// BatchedHeartbeatScheduler. Chosen so the load-bearing chain+// `flushInterval + heartbeatInterval + tickInterval < staleThresholdSeconds`+// holds with a comfortable buffer (60 + 15 + 30 = 105 < 150). Lengthening+// this requires bumping staleThresholdSeconds in lockstep.+const DefaultHeartbeatBatchInterval = 30 * time.Second++func NewBatchedHeartbeatScheduler(queries *db.Queries, tickInterval time.Duration) *BatchedHeartbeatScheduler {+ if tickInterval <= 0 {+ tickInterval = DefaultHeartbeatBatchInterval+ }+ return &BatchedHeartbeatScheduler{+ queries: queries,+ fallback: NewPassthroughHeartbeatScheduler(queries),+ tickInterval: tickInterval,+ pending: make(map[pgtype.UUID]struct{}),+ stopCh: make(chan struct{}),+ doneCh: make(chan struct{}),+ }+}++func (b *BatchedHeartbeatScheduler) Schedule(ctx context.Context, rt db.AgentRuntime) error {+ // Status flip (offline→online) and never-seen rows must commit before+ // returning so callers / dependent reads observe the new state. Only+ // the hot "already online, bumping last_seen_at" case is batched.+ if rt.Status != "online" || !rt.LastSeenAt.Valid {+ return b.fallback.Schedule(ctx, rt)+ }+ b.mu.Lock()+ b.pending[rt.ID] = struct{}{}+ b.mu.Unlock()+ return nil+}++// Run drives periodic bulk flushes. Returns after Stop is called and the+// final drain has completed. Intended to be invoked once in its own+// goroutine from main.go.+func (b *BatchedHeartbeatScheduler) Run(ctx context.Context) {+ defer close(b.doneCh)+ t := time.NewTicker(b.tickInterval)+ defer t.Stop()+ for {+ select {+ case <-b.stopCh:+ // Drain whatever is still queued. Use a fresh, short-bounded+ // context so a cancelled parent ctx doesn't drop the final flush.+ drainCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ b.flushOnce(drainCtx)+ cancel()+ return+ case <-ctx.Done():+ drainCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ b.flushOnce(drainCtx)+ cancel()+ return+ case <-t.C:+ b.flushOnce(ctx)+ }+ }+}++// Stop signals the Run goroutine to drain and exit. Blocks until the final+// flush completes so callers can sequence shutdown deterministically.+//+// As a defense-in-depth, Stop also performs one more flush after Run has+// exited. This catches the rare case where Run already returned via its+// ctx.Done() branch (e.g. parent ctx was cancelled before Stop was called)+// and a late Schedule call has since added entries to the pending map.+func (b *BatchedHeartbeatScheduler) Stop() {+ b.stopOnce.Do(func() {+ close(b.stopCh)+ })+ <-b.doneCh+ finalCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ b.flushOnce(finalCtx)+ cancel()+}++// FlushNow is exposed for tests that want to assert post-flush DB state+// without sleeping for tickInterval. Production code should rely on Run.+func (b *BatchedHeartbeatScheduler) FlushNow(ctx context.Context) {+ b.flushOnce(ctx)+}++// PendingCount reports the number of unique runtime IDs currently queued.+// Exposed for tests and potential metrics.+func (b *BatchedHeartbeatScheduler) PendingCount() int {+ b.mu.Lock()+ defer b.mu.Unlock()+ return len(b.pending)+}++func (b *BatchedHeartbeatScheduler) flushOnce(ctx context.Context) {+ b.mu.Lock()+ if len(b.pending) == 0 {+ b.mu.Unlock()+ return+ }+ ids := make([]pgtype.UUID, 0, len(b.pending))+ for id := range b.pending {+ ids = append(ids, id)+ }+ b.pending = make(map[pgtype.UUID]struct{})+ b.mu.Unlock()++ rows, err := b.queries.TouchAgentRuntimesLastSeenBatch(ctx, ids)+ if err != nil {+ // Don't requeue on persistent errors — see type comment.+ slog.Warn("heartbeat batch flush failed",+ "scheduled", len(ids), "error", err)+ return+ }+ if int(rows) < len(ids) {+ // Some runtimes raced into a non-online state between Schedule and+ // flush. Their next heartbeat sees status != "online" and falls+ // through to the sync MarkAgentRuntimeOnline path in recordHeartbeat,+ // so the divergence self-heals within one beat (~15s).+ slog.Info("heartbeat batch flush: some runtimes raced to offline",+ "scheduled", len(ids), "affected", rows)+ }+}diff --git a/server/internal/handler/heartbeat_scheduler_test.go b/server/internal/handler/heartbeat_scheduler_test.gonew file mode 100644index 0000000000..d5af197079--- /dev/null+++ b/server/internal/handler/heartbeat_scheduler_test.go@@ -0,0 +1,274 @@+package handler++import (+ "context"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+)++// TestBatchedHeartbeatScheduler_CoalescesAndFlushes confirms the core P1 win:+// many Schedule calls for the same id within a tick window collapse to a+// single bulk UPDATE, and the DB observes the bump after FlushNow.+func TestBatchedHeartbeatScheduler_CoalescesAndFlushes(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)++ // Push the row's last_seen_at into the past so the post-flush value is+ // distinguishable from the pre-flush one.+ stale := time.Now().Add(-2 * time.Hour)+ setRuntimeLastSeenAt(t, runtimeID, stale)+ rt := loadRuntime(t, runtimeID)++ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0)++ // Hammer Schedule with the same id from many goroutines.+ const callers = 50+ var wg sync.WaitGroup+ wg.Add(callers)+ for i := 0; i < callers; i++ {+ go func() {+ defer wg.Done()+ if err := sched.Schedule(context.Background(), rt); err != nil {+ t.Errorf("Schedule: %v", err)+ }+ }()+ }+ wg.Wait()++ if got := sched.PendingCount(); got != 1 {+ t.Fatalf("expected coalesced pending=1, got %d", got)+ }++ // Pre-flush the DB row should still show the stale value.+ _, lastSeenBefore, _ := readRuntimeRow(t, runtimeID)+ if !lastSeenBefore.Equal(stale) {+ // stale time is rounded by the DB, allow same instant+ if lastSeenBefore.After(stale.Add(time.Second)) {+ t.Fatalf("DB unexpectedly bumped before flush: %s", lastSeenBefore)+ }+ }++ sched.FlushNow(context.Background())++ if got := sched.PendingCount(); got != 0 {+ t.Fatalf("expected pending=0 after flush, got %d", got)+ }++ _, lastSeenAfter, _ := readRuntimeRow(t, runtimeID)+ if !lastSeenAfter.After(stale.Add(time.Hour)) {+ t.Fatalf("flush did not bump last_seen_at: stale=%s after=%s", stale, lastSeenAfter)+ }+}++// TestBatchedHeartbeatScheduler_OfflineFallsBackSync confirms that the sync+// path is preserved: an offline-status row goes through MarkAgentRuntimeOnline+// immediately, not through the queue.+func TestBatchedHeartbeatScheduler_OfflineFallsBackSync(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ setRuntimeStatus(t, runtimeID, "offline")+ setRuntimeLastSeenAt(t, runtimeID, time.Now())+ rt := loadRuntime(t, runtimeID)+ if rt.Status != "offline" {+ t.Fatalf("setup: status=%q want offline", rt.Status)+ }++ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0)+ if err := sched.Schedule(context.Background(), rt); err != nil {+ t.Fatalf("Schedule: %v", err)+ }++ if got := sched.PendingCount(); got != 0 {+ t.Fatalf("offline row should not have been queued, pending=%d", got)+ }+ status, _, _ := readRuntimeRow(t, runtimeID)+ if status != "online" {+ t.Fatalf("expected status=online after sync flip, got %q", status)+ }+}++// TestBatchedHeartbeatScheduler_StopDrains confirms the shutdown contract:+// IDs queued before Stop must be flushed to the DB by the time Stop returns,+// otherwise a graceful restart would lose heartbeat state.+func TestBatchedHeartbeatScheduler_StopDrains(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ stale := time.Now().Add(-2 * time.Hour)+ setRuntimeLastSeenAt(t, runtimeID, stale)+ rt := loadRuntime(t, runtimeID)++ // Long tick so the natural ticker can't fire during the test — only+ // the Stop drain can flush.+ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, time.Hour)++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ go sched.Run(ctx)++ if err := sched.Schedule(context.Background(), rt); err != nil {+ t.Fatalf("Schedule: %v", err)+ }+ if got := sched.PendingCount(); got != 1 {+ t.Fatalf("expected pending=1 before Stop, got %d", got)+ }++ sched.Stop()++ if got := sched.PendingCount(); got != 0 {+ t.Fatalf("expected pending=0 after Stop drain, got %d", got)+ }+ _, lastSeen, _ := readRuntimeRow(t, runtimeID)+ if !lastSeen.After(stale.Add(time.Hour)) {+ t.Fatalf("Stop did not drain pending bump: stale=%s after=%s", stale, lastSeen)+ }+}++// TestBatchedHeartbeatScheduler_StopFlushesLateSchedule verifies the+// defense-in-depth flush in Stop(): if Run already returned via ctx.Done()+// and a heartbeat is then Schedule'd before Stop is called, that bump must+// still hit the DB after Stop returns. This guards the production shutdown+// race where in-flight HTTP heartbeats can call Schedule while sweepCtx is+// already cancelled.+func TestBatchedHeartbeatScheduler_StopFlushesLateSchedule(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ stale := time.Now().Add(-2 * time.Hour)+ setRuntimeLastSeenAt(t, runtimeID, stale)+ rt := loadRuntime(t, runtimeID)++ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, time.Hour)++ runCtx, runCancel := context.WithCancel(context.Background())+ go sched.Run(runCtx)++ // Force Run to exit via ctx.Done() before any Schedule call. Wait for+ // it to fully drain (which closes doneCh by reading it directly is+ // awkward; instead, briefly poll on a separate Stop-less path). The+ // simplest deterministic signal: cancel, then sleep just enough for+ // the goroutine to hit the ctx.Done() branch and close doneCh.+ runCancel()+ time.Sleep(50 * time.Millisecond)++ // Now Schedule a late heartbeat. Run is gone; only Stop's defensive+ // flush can persist this.+ if err := sched.Schedule(context.Background(), rt); err != nil {+ t.Fatalf("Schedule: %v", err)+ }+ if got := sched.PendingCount(); got != 1 {+ t.Fatalf("expected pending=1 before Stop, got %d", got)+ }++ sched.Stop()++ if got := sched.PendingCount(); got != 0 {+ t.Fatalf("expected pending=0 after Stop's defensive flush, got %d", got)+ }+ _, lastSeen, _ := readRuntimeRow(t, runtimeID)+ if !lastSeen.After(stale.Add(time.Hour)) {+ t.Fatalf("Stop did not flush late Schedule: stale=%s after=%s", stale, lastSeen)+ }+}++// TestBatchedHeartbeatScheduler_FlushIgnoresEmpty exercises the empty-pending+// fast path: a tick with nothing queued must not issue a DB call.+func TestBatchedHeartbeatScheduler_FlushIgnoresEmpty(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0)+ // Just calling FlushNow with nothing queued should not panic or error.+ sched.FlushNow(context.Background())+ if got := sched.PendingCount(); got != 0 {+ t.Fatalf("pending should remain 0, got %d", got)+ }+}++// TestBatchedHeartbeatScheduler_RaceToOfflineSelfHeals confirms the+// next-beat-recovery contract: if the sweeper flips a row to offline between+// Schedule and FlushNow, the bulk UPDATE leaves it offline (no rows+// affected), and the runtime's *next* beat takes the sync path through+// recordHeartbeat → MarkAgentRuntimeOnline to recover.+func TestBatchedHeartbeatScheduler_RaceToOfflineSelfHeals(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ rt := loadRuntime(t, runtimeID)++ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0)+ if err := sched.Schedule(context.Background(), rt); err != nil {+ t.Fatalf("Schedule: %v", err)+ }++ // Sweeper races us to offline before the flush.+ setRuntimeStatus(t, runtimeID, "offline")++ sched.FlushNow(context.Background())++ // Bulk UPDATE's status='online' predicate means the row stays offline.+ status, _, _ := readRuntimeRow(t, runtimeID)+ if status != "offline" {+ t.Fatalf("expected status=offline after raced flush, got %q", status)+ }++ // Reload and re-Schedule: rt.Status is now offline, so the scheduler+ // takes the sync MarkAgentRuntimeOnline path and the row recovers.+ rt2 := loadRuntime(t, runtimeID)+ if err := sched.Schedule(context.Background(), rt2); err != nil {+ t.Fatalf("recovery Schedule: %v", err)+ }+ status2, _, _ := readRuntimeRow(t, runtimeID)+ if status2 != "online" {+ t.Fatalf("expected sync recovery to flip back to online, got %q", status2)+ }+}++// TestPassthroughHeartbeatScheduler_TouchAndRaceRecovery confirms the legacy+// behavior is preserved end-to-end: an online row gets bumped via Touch, and+// a row whose status was raced to offline between SELECT and Schedule is+// recovered via MarkAgentRuntimeOnline.+func TestPassthroughHeartbeatScheduler_TouchAndRaceRecovery(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ stale := time.Now().Add(-time.Hour)+ setRuntimeLastSeenAt(t, runtimeID, stale)+ rt := loadRuntime(t, runtimeID)++ sched := NewPassthroughHeartbeatScheduler(testHandler.Queries)++ if err := sched.Schedule(context.Background(), rt); err != nil {+ t.Fatalf("Schedule: %v", err)+ }+ _, lastSeen, _ := readRuntimeRow(t, runtimeID)+ if !lastSeen.After(stale.Add(time.Minute)) {+ t.Fatalf("passthrough did not bump last_seen_at: stale=%s after=%s", stale, lastSeen)+ }++ // Race: snapshot still says online but DB is now offline.+ rt2 := loadRuntime(t, runtimeID)+ setRuntimeStatus(t, runtimeID, "offline")+ if err := sched.Schedule(context.Background(), rt2); err != nil {+ t.Fatalf("Schedule under race: %v", err)+ }+ status, _, _ := readRuntimeRow(t, runtimeID)+ if status != "online" {+ t.Fatalf("expected race recovery via MarkAgentRuntimeOnline, got %q", status)+ }+}++// silenceUnusedPgUUID ensures the package compiles even if no other test+// happens to reference pgtype after future edits trim imports.+var _ = pgtype.UUID{}diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 9eef2013b0..86b03592d8 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -559,6 +559,29 @@ func (q *Queries) TouchAgentRuntimeLastSeen(ctx context.Context, id pgtype.UUID)return result.RowsAffected(), nil}+const touchAgentRuntimesLastSeenBatch = `-- name: TouchAgentRuntimesLastSeenBatch :execrows+UPDATE agent_runtime+SET last_seen_at = now()+WHERE id = ANY($1::uuid[]) AND status = 'online'+`++// Bulk variant of TouchAgentRuntimeLastSeen used by the BatchedHeartbeatScheduler:+// coalesces N per-runtime "bump last_seen_at" requests into a single UPDATE so a+// fleet beating every 15s costs ~1 DB transaction per batch tick instead of N.+//+// Same load-bearing predicate as the single-id form: status='online' avoids+// silently un-deleting a sweeper-flipped offline row, and we deliberately do+// NOT touch updated_at so the rows stay HOT-eligible. Affected-rows < len(ids)+// means some IDs raced to offline between Schedule and flush; their next beat+// will fall through the recordHeartbeat sync path and call MarkAgentRuntimeOnline.+func (q *Queries) TouchAgentRuntimesLastSeenBatch(ctx context.Context, ids []pgtype.UUID) (int64, error) {+ result, err := q.db.Exec(ctx, touchAgentRuntimesLastSeenBatch, ids)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const upsertAgentRuntime = `-- name: UpsertAgentRuntime :oneINSERT INTO agent_runtime (workspace_id,diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex d2d32dbe7f..4a21af1d29 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -56,6 +56,20 @@ UPDATE agent_runtimeSET last_seen_at = now()WHERE id = $1 AND status = 'online';+-- name: TouchAgentRuntimesLastSeenBatch :execrows+-- Bulk variant of TouchAgentRuntimeLastSeen used by the BatchedHeartbeatScheduler:+-- coalesces N per-runtime "bump last_seen_at" requests into a single UPDATE so a+-- fleet beating every 15s costs ~1 DB transaction per batch tick instead of N.+--+-- Same load-bearing predicate as the single-id form: status='online' avoids+-- silently un-deleting a sweeper-flipped offline row, and we deliberately do+-- NOT touch updated_at so the rows stay HOT-eligible. Affected-rows < len(ids)+-- means some IDs raced to offline between Schedule and flush; their next beat+-- will fall through the recordHeartbeat sync path and call MarkAgentRuntimeOnline.+UPDATE agent_runtime+SET last_seen_at = now()+WHERE id = ANY(@ids::uuid[]) AND status = 'online';+-- name: MarkAgentRuntimeOnline :one-- Used on the offline→online transition (and on first heartbeat after-- registration). Writes status, last_seen_at, and updated_at because the