Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(server): redis-backed runtime liveness with DB fallback (#2121)

Bohan Jiang09f04847d376
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index aa990e13a9..795449f984 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -14,6 +14,7 @@ import (
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -294,8 +295,17 @@ func main() {
autopilotSvc := service.NewAutopilotService(queries, pool, bus, taskSvc)
registerAutopilotListeners(bus, autopilotSvc)
+ // Construct a LivenessStore that mirrors the one wired into the HTTP
+ // handler. Both the heartbeat write path (handler) and the sweeper read
+ // path (here) must agree on the same Redis-or-Noop choice; if they
+ // disagree, online runtimes get falsely marked offline.
+ var liveness handler.LivenessStore = handler.NewNoopLivenessStore()
+ if storeRedis != nil {
+ liveness = handler.NewRedisLivenessStore(storeRedis)
+ }
+
// Start background sweeper to mark stale runtimes as offline.
- go runRuntimeSweeper(sweepCtx, queries, taskSvc, bus)
+ go runRuntimeSweeper(sweepCtx, queries, liveness, taskSvc, bus)
go runAutopilotScheduler(autopilotCtx, queries, autopilotSvc)
go runDBStatsLogger(sweepCtx, pool)
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 28e7e506bc..818e8ab92b 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -110,6 +110,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
h.ModelListStore = handler.NewRedisModelListStore(rdb)
h.LocalSkillListStore = handler.NewRedisLocalSkillListStore(rdb)
h.LocalSkillImportStore = handler.NewRedisLocalSkillImportStore(rdb)
+ h.LivenessStore = handler.NewRedisLivenessStore(rdb)
}
// Auth caches: PAT cache is shared between the regular Auth middleware,
// the DaemonAuth fallback (mul_) path, and the revoke handler
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index cd38494cae..dcb34e04f4 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -7,6 +7,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -16,9 +17,15 @@ import (
const (
// sweepInterval is how often we check for stale runtimes and tasks.
sweepInterval = 30 * time.Second
- // staleThresholdSeconds marks runtimes offline if no heartbeat for this long.
- // The daemon heartbeat interval is 15s, so 45s = 3 missed heartbeats.
- staleThresholdSeconds = 45.0
+ // 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
// 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.0
@@ -35,7 +42,14 @@ const (
// last_seen_at exceeds the stale threshold, and fails orphaned tasks.
// This handles cases where the daemon crashes, is killed without calling
// the deregister endpoint, or leaves tasks in a non-terminal state.
-func runRuntimeSweeper(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus) {
+//
+// liveness is consulted before flipping any candidate to offline: when the
+// LivenessStore is available and reports the runtime as alive, we skip the
+// row even though its DB last_seen_at is old (Redis is the authority on the
+// hot heartbeat path; the DB is allowed to lag up to runtimeHeartbeatDBFlushInterval).
+// When liveness is unavailable or errors, we fall back to trusting the DB
+// stale window — that is the original behavior.
+func runRuntimeSweeper(ctx context.Context, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus) {
ticker := time.NewTicker(sweepInterval)
defer ticker.Stop()
@@ -44,7 +58,7 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, taskSvc *servic
case <-ctx.Done():
return
case <-ticker.C:
- sweepStaleRuntimes(ctx, queries, taskSvc, bus)
+ sweepStaleRuntimes(ctx, queries, liveness, taskSvc, bus)
sweepStaleTasks(ctx, queries, taskSvc, bus)
gcRuntimes(ctx, queries, bus)
}
@@ -53,13 +67,32 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, taskSvc *servic
// sweepStaleRuntimes marks runtimes offline if they haven't heartbeated,
// then fails any tasks belonging to those offline runtimes.
-func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus) {
- staleRows, err := queries.MarkStaleRuntimesOffline(ctx, staleThresholdSeconds)
+func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus) {
+ candidates, err := queries.SelectStaleOnlineRuntimes(ctx, staleThresholdSeconds)
+ if err != nil {
+ slog.Warn("runtime sweeper: failed to list stale online runtimes", "error", err)
+ return
+ }
+ if len(candidates) == 0 {
+ return
+ }
+
+ toOffline := filterStaleRuntimesByLiveness(ctx, candidates, liveness)
+ if len(toOffline) == 0 {
+ return
+ }
+
+ staleRows, err := queries.MarkRuntimesOfflineByIDs(ctx, db.MarkRuntimesOfflineByIDsParams{
+ Ids: toOffline,
+ StaleSeconds: staleThresholdSeconds,
+ })
if err != nil {
slog.Warn("runtime sweeper: failed to mark stale runtimes offline", "error", err)
return
}
if len(staleRows) == 0 {
+ // All filtered candidates raced into a non-online state between the
+ // SELECT and the UPDATE. Nothing to broadcast.
return
}
@@ -70,6 +103,15 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, taskSvc *servi
workspaces[wsID] = true
}
+ // Drop liveness records for confirmed-offline runtimes so a future
+ // MGET sweep doesn't see a stray key keep them "alive". TTLs would
+ // reap these eventually, but explicit cleanup is cheap and clearer.
+ if liveness.Available() {
+ for _, row := range staleRows {
+ liveness.Forget(ctx, util.UUIDToString(row.ID))
+ }
+ }
+
slog.Info("runtime sweeper: marked stale runtimes offline", "count", len(staleRows), "workspaces", len(workspaces))
// Fail orphaned tasks (dispatched/running) whose runtimes just went offline.
@@ -94,6 +136,40 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, taskSvc *servi
}
}
+// filterStaleRuntimesByLiveness narrows a SELECT-of-stale-candidates down to
+// the set that should actually be flipped offline. When liveness is available
+// and reports a candidate as alive, we skip it (DB is just lagging). When the
+// store is unavailable or errors, we trust the DB stale window — i.e. every
+// candidate flips, matching the legacy MarkStaleRuntimesOffline behavior.
+func filterStaleRuntimesByLiveness(ctx context.Context, candidates []db.SelectStaleOnlineRuntimesRow, liveness handler.LivenessStore) []pgtype.UUID {
+ ids := make([]pgtype.UUID, 0, len(candidates))
+ if !liveness.Available() {
+ for _, c := range candidates {
+ ids = append(ids, c.ID)
+ }
+ return ids
+ }
+ idStrs := make([]string, len(candidates))
+ for i, c := range candidates {
+ idStrs[i] = util.UUIDToString(c.ID)
+ }
+ alive, ok := liveness.IsAliveBatch(ctx, idStrs)
+ if !ok {
+ // Store hiccup: degrade to DB-only behavior for this tick.
+ for _, c := range candidates {
+ ids = append(ids, c.ID)
+ }
+ return ids
+ }
+ for i, c := range candidates {
+ if alive[idStrs[i]] {
+ continue
+ }
+ ids = append(ids, c.ID)
+ }
+ return ids
+}
+
// gcRuntimes deletes offline runtimes that have exceeded the TTL and have
// no active (non-archived) agents. Before deleting, it cleans up any
// archived agents so the FK constraint (ON DELETE RESTRICT) doesn't block.
diff --git a/server/cmd/server/runtime_sweeper_filter_test.go b/server/cmd/server/runtime_sweeper_filter_test.go
new file mode 100644
index 0000000000..027564c05f
--- /dev/null
+++ b/server/cmd/server/runtime_sweeper_filter_test.go
@@ -0,0 +1,132 @@
+package main
+
+import (
+ "context"
+ "reflect"
+ "sort"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// fakeLiveness drives every Available / IsAliveBatch branch in
+// filterStaleRuntimesByLiveness without standing up Redis. The sweeper-side
+// behavior is the most subtle part of the design, so it gets a dedicated
+// suite here even though the handler package has analogous coverage.
+type fakeLiveness struct {
+ available bool
+ aliveResult map[string]bool
+ aliveOK bool
+}
+
+func (f *fakeLiveness) Available() bool { return f.available }
+func (f *fakeLiveness) Touch(_ context.Context, _ string, _ time.Duration) error {
+ return nil
+}
+func (f *fakeLiveness) IsAliveBatch(_ context.Context, ids []string) (map[string]bool, bool) {
+ if !f.aliveOK {
+ return nil, false
+ }
+ out := make(map[string]bool, len(ids))
+ for _, id := range ids {
+ out[id] = f.aliveResult[id]
+ }
+ return out, true
+}
+func (f *fakeLiveness) Forget(_ context.Context, _ string) {}
+
+func makeUUIDForFilter(t *testing.T, s string) pgtype.UUID {
+ t.Helper()
+ u, err := util.ParseUUID(s)
+ if err != nil {
+ t.Fatalf("ParseUUID(%q): %v", s, err)
+ }
+ return u
+}
+
+func candidateRow(t *testing.T, id string) db.SelectStaleOnlineRuntimesRow {
+ return db.SelectStaleOnlineRuntimesRow{ID: makeUUIDForFilter(t, id)}
+}
+
+func sortedIDStrings(ids []pgtype.UUID) []string {
+ out := make([]string, len(ids))
+ for i, id := range ids {
+ out[i] = util.UUIDToString(id)
+ }
+ sort.Strings(out)
+ return out
+}
+
+// TestFilterStaleRuntimesByLiveness_NoopStorePassesThrough confirms that with
+// no Redis the filter returns every candidate — the sweeper trusts the DB
+// stale window and behaves like the legacy MarkStaleRuntimesOffline path.
+func TestFilterStaleRuntimesByLiveness_NoopStorePassesThrough(t *testing.T) {
+ a := "11111111-1111-1111-1111-111111111111"
+ b := "22222222-2222-2222-2222-222222222222"
+ candidates := []db.SelectStaleOnlineRuntimesRow{
+ candidateRow(t, a),
+ candidateRow(t, b),
+ }
+
+ got := filterStaleRuntimesByLiveness(context.Background(), candidates, handler.NewNoopLivenessStore())
+
+ want := []string{a, b}
+ if !reflect.DeepEqual(sortedIDStrings(got), want) {
+ t.Fatalf("noop store should pass every candidate through: got=%v want=%v",
+ sortedIDStrings(got), want)
+ }
+}
+
+// TestFilterStaleRuntimesByLiveness_AliveCandidatesSkipped confirms the core
+// optimization: candidates whose Redis liveness is fresh are NOT marked
+// offline, even though their DB last_seen_at is stale.
+func TestFilterStaleRuntimesByLiveness_AliveCandidatesSkipped(t *testing.T) {
+ aliveID := "11111111-1111-1111-1111-111111111111"
+ deadID := "22222222-2222-2222-2222-222222222222"
+ candidates := []db.SelectStaleOnlineRuntimesRow{
+ candidateRow(t, aliveID),
+ candidateRow(t, deadID),
+ }
+
+ got := filterStaleRuntimesByLiveness(context.Background(), candidates, &fakeLiveness{
+ available: true,
+ aliveOK: true,
+ aliveResult: map[string]bool{
+ aliveID: true,
+ // deadID intentionally absent — defaults to false.
+ },
+ })
+
+ want := []string{deadID}
+ if !reflect.DeepEqual(sortedIDStrings(got), want) {
+ t.Fatalf("alive candidates should be skipped: got=%v want=%v",
+ sortedIDStrings(got), want)
+ }
+}
+
+// TestFilterStaleRuntimesByLiveness_StoreErrorFallsBackToDB confirms the
+// graceful-degradation contract: when IsAliveBatch returns ok=false, the
+// sweeper trusts the DB stale window — same as if Redis were not configured.
+func TestFilterStaleRuntimesByLiveness_StoreErrorFallsBackToDB(t *testing.T) {
+ a := "11111111-1111-1111-1111-111111111111"
+ b := "22222222-2222-2222-2222-222222222222"
+ candidates := []db.SelectStaleOnlineRuntimesRow{
+ candidateRow(t, a),
+ candidateRow(t, b),
+ }
+
+ got := filterStaleRuntimesByLiveness(context.Background(), candidates, &fakeLiveness{
+ available: true,
+ aliveOK: false, // simulates Redis MGET error
+ })
+
+ want := []string{a, b}
+ if !reflect.DeepEqual(sortedIDStrings(got), want) {
+ t.Fatalf("store error should fall back to passing every candidate: got=%v want=%v",
+ sortedIDStrings(got), want)
+ }
+}
diff --git a/server/cmd/server/runtime_sweeper_race_test.go b/server/cmd/server/runtime_sweeper_race_test.go
new file mode 100644
index 0000000000..f2de6f5256
--- /dev/null
+++ b/server/cmd/server/runtime_sweeper_race_test.go
@@ -0,0 +1,130 @@
+package main
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestMarkRuntimesOfflineByIDs_RespectsConcurrentHeartbeat is the regression
+// test for the SELECT/filter/UPDATE race that GPT-Boy flagged in PR #2121:
+// once the sweeper splits the candidate gather and the actual write into two
+// statements, a heartbeat that lands between them must veto the offline
+// flip. The original single-statement MarkStaleRuntimesOffline preserved
+// this implicitly because the predicate and the write lived in one UPDATE;
+// MarkRuntimesOfflineByIDs preserves it explicitly via the stale predicate
+// re-check.
+func TestMarkRuntimesOfflineByIDs_RespectsConcurrentHeartbeat(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ ctx := context.Background()
+ 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.
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider,
+ status, device_info, metadata, last_seen_at
+ )
+ VALUES ($1, NULL, $2, 'cloud', 'claude',
+ 'online', '', '{}'::jsonb, now() - interval '5 minutes')
+ RETURNING id
+ `, testWorkspaceID, "race-test-runtime").Scan(&runtimeID); err != nil {
+ t.Fatalf("seed runtime: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ })
+
+ // Simulate the race window: a heartbeat lands between SELECT and UPDATE.
+ // The sweeper has already gathered this runtime as a candidate and is
+ // about to flip it offline; the heartbeat path bumps last_seen_at to now.
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_runtime SET last_seen_at = now() WHERE id = $1`,
+ runtimeID,
+ ); err != nil {
+ t.Fatalf("simulate concurrent heartbeat: %v", err)
+ }
+
+ // The final UPDATE must NOT mark this runtime offline — its last_seen_at
+ // is now fresh, so the stale predicate inside MarkRuntimesOfflineByIDs
+ // vetoes the write.
+ rows, err := queries.MarkRuntimesOfflineByIDs(ctx, db.MarkRuntimesOfflineByIDsParams{
+ Ids: []pgtype.UUID{parseUUID(runtimeID)},
+ StaleSeconds: staleThresholdSeconds,
+ })
+ if err != nil {
+ t.Fatalf("MarkRuntimesOfflineByIDs: %v", err)
+ }
+ if len(rows) != 0 {
+ t.Fatalf("expected 0 rows offlined (stale predicate should veto), got %d", len(rows))
+ }
+
+ var status string
+ var lastSeen time.Time
+ if err := testPool.QueryRow(ctx,
+ `SELECT status, last_seen_at FROM agent_runtime WHERE id = $1`, runtimeID,
+ ).Scan(&status, &lastSeen); err != nil {
+ t.Fatalf("read back runtime: %v", err)
+ }
+ if status != "online" {
+ t.Fatalf("runtime was incorrectly marked offline despite fresh heartbeat: status=%q", status)
+ }
+ if time.Since(lastSeen) > 30*time.Second {
+ t.Fatalf("last_seen_at not preserved: %s ago", time.Since(lastSeen))
+ }
+}
+
+// TestMarkRuntimesOfflineByIDs_OfflinesGenuinelyStale confirms the happy
+// path still works: a runtime whose last_seen_at really is past the stale
+// threshold gets marked offline by the same query.
+func TestMarkRuntimesOfflineByIDs_OfflinesGenuinelyStale(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ ctx := context.Background()
+ queries := db.New(testPool)
+
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider,
+ status, device_info, metadata, last_seen_at
+ )
+ VALUES ($1, NULL, $2, 'cloud', 'claude',
+ 'online', '', '{}'::jsonb, now() - interval '5 minutes')
+ RETURNING id
+ `, testWorkspaceID, "race-test-stale-runtime").Scan(&runtimeID); err != nil {
+ t.Fatalf("seed runtime: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ })
+
+ rows, err := queries.MarkRuntimesOfflineByIDs(ctx, db.MarkRuntimesOfflineByIDsParams{
+ Ids: []pgtype.UUID{parseUUID(runtimeID)},
+ StaleSeconds: staleThresholdSeconds,
+ })
+ if err != nil {
+ t.Fatalf("MarkRuntimesOfflineByIDs: %v", err)
+ }
+ if len(rows) != 1 {
+ t.Fatalf("expected 1 row offlined, got %d", len(rows))
+ }
+
+ var status string
+ if err := testPool.QueryRow(ctx,
+ `SELECT status FROM agent_runtime WHERE id = $1`, runtimeID,
+ ).Scan(&status); err != nil {
+ t.Fatalf("read back runtime: %v", err)
+ }
+ if status != "offline" {
+ t.Fatalf("genuinely-stale runtime not marked offline: status=%q", status)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 20a4196371..3c09841c00 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -523,6 +523,31 @@ 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.
+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
+// 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.
+//
+// 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.
+const runtimeHeartbeatDBFlushInterval = 60 * time.Second
+
func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {
start := time.Now()
authPath := middleware.DaemonAuthPathFromContext(r.Context())
@@ -642,6 +667,67 @@ func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws
return ack, err
}
+// recordHeartbeat marks the runtime as alive. When LivenessStore is available
+// (Redis configured and reachable) it writes a TTL'd liveness key and skips
+// the DB row write on most beats — the DB is only updated on the
+// offline→online transition or once per runtimeHeartbeatDBFlushInterval to
+// keep last_seen_at fresh enough for the UI and the DB-fallback sweeper.
+//
+// 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.
+func (h *Handler) recordHeartbeat(ctx context.Context, rt db.AgentRuntime) error {
+ now := time.Now()
+
+ // Decide whether the DB row needs a write *before* touching Redis, so a
+ // Touch failure can simply force needDBWrite=true without re-evaluating
+ // the structural reasons.
+ needDBWrite := !h.LivenessStore.Available() ||
+ rt.Status != "online" ||
+ !rt.LastSeenAt.Valid ||
+ now.Sub(rt.LastSeenAt.Time) >= runtimeHeartbeatDBFlushInterval
+
+ if h.LivenessStore.Available() {
+ if err := h.LivenessStore.Touch(ctx, uuidToString(rt.ID), runtimeLivenessTTL); err != nil {
+ // Redis hiccup: degrade transparently to the DB-only path for
+ // this beat. The sweeper falls back to its DB threshold the
+ // same way when IsAliveBatch fails, so end-to-end correctness
+ // is preserved.
+ slog.Warn("liveness touch failed; falling back to DB heartbeat",
+ "runtime_id", uuidToString(rt.ID), "error", err)
+ needDBWrite = true
+ }
+ }
+
+ if !needDBWrite {
+ return 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
+}
+
// heartbeatMetrics carries per-stage timings out of processHeartbeat so the
// HTTP slow-log can stay structured. The WS path discards them.
type heartbeatMetrics struct {
@@ -650,19 +736,19 @@ type heartbeatMetrics struct {
}
// processHeartbeat does the work shared by HTTP POST /api/daemon/heartbeat and
-// the WebSocket daemon:heartbeat path: bumps last_seen_at and pulls any
-// pending actions queued for the runtime. Auth and request decoding live in
-// the caller because they differ between transports.
+// the WebSocket daemon:heartbeat path: records liveness and pulls any pending
+// actions queued for the runtime. Auth and request decoding live in the
+// caller because they differ between transports.
func (h *Handler) processHeartbeat(ctx context.Context, rt db.AgentRuntime) (*protocol.DaemonHeartbeatAckPayload, heartbeatMetrics, error) {
var m heartbeatMetrics
runtimeID := uuidToString(rt.ID)
updateStart := time.Now()
- _, updateErr := h.Queries.UpdateAgentRuntimeHeartbeat(ctx, rt.ID)
- m.UpdateMs = time.Since(updateStart).Milliseconds()
- if updateErr != nil {
- return nil, m, updateErr
+ if err := h.recordHeartbeat(ctx, rt); err != nil {
+ m.UpdateMs = time.Since(updateStart).Milliseconds()
+ return nil, m, err
}
+ m.UpdateMs = time.Since(updateStart).Milliseconds()
slog.Debug("daemon heartbeat", "runtime_id", runtimeID)
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 5d7cf6efe6..831647f761 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -63,6 +63,7 @@ type Handler struct {
ModelListStore ModelListStore
LocalSkillListStore LocalSkillListStore
LocalSkillImportStore LocalSkillImportStore
+ LivenessStore LivenessStore
Storage storage.Storage
CFSigner *auth.CloudFrontSigner
Analytics analytics.Client
@@ -101,6 +102,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
ModelListStore: NewInMemoryModelListStore(),
LocalSkillListStore: NewInMemoryLocalSkillListStore(),
LocalSkillImportStore: NewInMemoryLocalSkillImportStore(),
+ LivenessStore: NewNoopLivenessStore(),
Storage: store,
CFSigner: cfSigner,
Analytics: analyticsClient,
diff --git a/server/internal/handler/heartbeat_test.go b/server/internal/handler/heartbeat_test.go
new file mode 100644
index 0000000000..f9d4575592
--- /dev/null
+++ b/server/internal/handler/heartbeat_test.go
@@ -0,0 +1,318 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// fakeLivenessStore lets tests drive every Available / Touch / IsAliveBatch
+// branch of recordHeartbeat without spinning up Redis. It records call counts
+// so we can assert the gate behavior without any DB-time dependence.
+type fakeLivenessStore struct {
+ mu sync.Mutex
+ available bool
+ touchErr error
+ touched []string
+ aliveResult map[string]bool
+ aliveOK bool
+ forgotten []string
+}
+
+func (f *fakeLivenessStore) Available() bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.available
+}
+
+func (f *fakeLivenessStore) Touch(_ context.Context, runtimeID string, _ time.Duration) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.touched = append(f.touched, runtimeID)
+ return f.touchErr
+}
+
+func (f *fakeLivenessStore) IsAliveBatch(_ context.Context, ids []string) (map[string]bool, bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if !f.aliveOK {
+ return nil, false
+ }
+ out := make(map[string]bool, len(ids))
+ for _, id := range ids {
+ out[id] = f.aliveResult[id]
+ }
+ return out, true
+}
+
+func (f *fakeLivenessStore) Forget(_ context.Context, runtimeID string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.forgotten = append(f.forgotten, runtimeID)
+}
+
+func (f *fakeLivenessStore) touchCount() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return len(f.touched)
+}
+
+// readRuntimeRow returns the fresh agent_runtime row for assertions.
+func readRuntimeRow(t *testing.T, runtimeID string) (status string, lastSeen time.Time, updatedAt time.Time) {
+ t.Helper()
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT status, last_seen_at, updated_at FROM agent_runtime WHERE id = $1`, runtimeID,
+ ).Scan(&status, &lastSeen, &updatedAt); err != nil {
+ t.Fatalf("read runtime row: %v", err)
+ }
+ return
+}
+
+func setRuntimeLastSeenAt(t *testing.T, runtimeID string, when time.Time) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE agent_runtime SET last_seen_at = $1 WHERE id = $2`, when, runtimeID,
+ ); err != nil {
+ t.Fatalf("force last_seen_at: %v", err)
+ }
+}
+
+func setRuntimeStatus(t *testing.T, runtimeID, status string) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE agent_runtime SET status = $1 WHERE id = $2`, status, runtimeID,
+ ); err != nil {
+ t.Fatalf("force status: %v", err)
+ }
+}
+
+// loadRuntime is a thin wrapper around the sqlc query to keep the test bodies
+// short.
+func loadRuntime(t *testing.T, runtimeID string) db.AgentRuntime {
+ t.Helper()
+ uuid, err := pgUUID(runtimeID)
+ if err != nil {
+ t.Fatalf("parse runtime id: %v", err)
+ }
+ rt, err := testHandler.Queries.GetAgentRuntime(context.Background(), uuid)
+ if err != nil {
+ t.Fatalf("GetAgentRuntime: %v", err)
+ }
+ return rt
+}
+
+func pgUUID(s string) (pgtype.UUID, error) {
+ var u pgtype.UUID
+ if err := u.Scan(s); err != nil {
+ return u, err
+ }
+ return u, nil
+}
+
+// TestRecordHeartbeat_NoopStoreAlwaysWritesDB confirms that without a Redis
+// LivenessStore the heartbeat path keeps the legacy behavior: every call
+// bumps last_seen_at on the DB row.
+func TestRecordHeartbeat_NoopStoreAlwaysWritesDB(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
+
+ orig := testHandler.LivenessStore
+ testHandler.LivenessStore = NewNoopLivenessStore()
+ t.Cleanup(func() { testHandler.LivenessStore = orig })
+
+ // Pin last_seen_at to "just now" to ensure the DB-flush condition is not
+ // what's driving the write.
+ setRuntimeLastSeenAt(t, runtimeID, time.Now())
+ rt := loadRuntime(t, runtimeID)
+ before := rt.LastSeenAt.Time
+
+ time.Sleep(50 * time.Millisecond)
+
+ if err := testHandler.recordHeartbeat(context.Background(), rt); err != nil {
+ t.Fatalf("recordHeartbeat: %v", err)
+ }
+
+ _, lastSeen, _ := readRuntimeRow(t, runtimeID)
+ if !lastSeen.After(before) {
+ t.Fatalf("noop-store heartbeat did not bump last_seen_at: before=%s after=%s", before, lastSeen)
+ }
+}
+
+// TestRecordHeartbeat_RedisAvailableSkipsDBWithinFlushWindow confirms the hot
+// path: when Redis is the source of truth and the row is fresh, the heartbeat
+// touches Redis but does NOT rewrite the DB row.
+func TestRecordHeartbeat_RedisAvailableSkipsDBWithinFlushWindow(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
+
+ fake := &fakeLivenessStore{available: true, aliveOK: true}
+ orig := testHandler.LivenessStore
+ testHandler.LivenessStore = fake
+ t.Cleanup(func() { testHandler.LivenessStore = orig })
+
+ // Pin last_seen_at to "just now" so we are inside the flush window.
+ setRuntimeLastSeenAt(t, runtimeID, time.Now())
+ rt := loadRuntime(t, runtimeID)
+ before := rt.LastSeenAt.Time
+
+ if err := testHandler.recordHeartbeat(context.Background(), rt); err != nil {
+ t.Fatalf("recordHeartbeat: %v", err)
+ }
+
+ if fake.touchCount() != 1 {
+ t.Fatalf("expected exactly one Touch, got %d", fake.touchCount())
+ }
+ _, lastSeen, _ := readRuntimeRow(t, runtimeID)
+ if !lastSeen.Equal(before) {
+ t.Fatalf("DB last_seen_at should not have been rewritten within flush window: before=%s after=%s", before, lastSeen)
+ }
+}
+
+// TestRecordHeartbeat_DBFlushOnStaleRow confirms the DB summary flush:
+// even with Redis healthy, a row whose last_seen_at exceeds the flush
+// interval gets a write so the UI's display value stays bounded.
+func TestRecordHeartbeat_DBFlushOnStaleRow(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
+
+ fake := &fakeLivenessStore{available: true, aliveOK: true}
+ orig := testHandler.LivenessStore
+ testHandler.LivenessStore = fake
+ t.Cleanup(func() { testHandler.LivenessStore = orig })
+
+ // Push last_seen_at past the flush threshold.
+ stale := time.Now().Add(-2 * runtimeHeartbeatDBFlushInterval)
+ setRuntimeLastSeenAt(t, runtimeID, stale)
+ rt := loadRuntime(t, runtimeID)
+
+ if err := testHandler.recordHeartbeat(context.Background(), rt); err != nil {
+ t.Fatalf("recordHeartbeat: %v", err)
+ }
+
+ _, lastSeen, _ := readRuntimeRow(t, runtimeID)
+ if !lastSeen.After(stale.Add(time.Minute)) {
+ t.Fatalf("DB last_seen_at should have been flushed: stale=%s after=%s", stale, lastSeen)
+ }
+}
+
+// TestRecordHeartbeat_OfflineToOnlineForcesDBWrite confirms that an offline
+// row's first heartbeat always rewrites the DB to flip status, even with
+// Redis healthy.
+func TestRecordHeartbeat_OfflineToOnlineForcesDBWrite(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
+
+ fake := &fakeLivenessStore{available: true, aliveOK: true}
+ orig := testHandler.LivenessStore
+ testHandler.LivenessStore = fake
+ t.Cleanup(func() { testHandler.LivenessStore = orig })
+
+ setRuntimeStatus(t, runtimeID, "offline")
+ // Keep last_seen_at fresh so the DB-flush condition is not what's
+ // driving the write — only the offline→online transition is.
+ setRuntimeLastSeenAt(t, runtimeID, time.Now())
+ rt := loadRuntime(t, runtimeID)
+ if rt.Status != "offline" {
+ t.Fatalf("setup: status = %q, want offline", rt.Status)
+ }
+
+ if err := testHandler.recordHeartbeat(context.Background(), rt); err != nil {
+ t.Fatalf("recordHeartbeat: %v", err)
+ }
+
+ status, _, _ := readRuntimeRow(t, runtimeID)
+ if status != "online" {
+ t.Fatalf("expected status=online after offline→online heartbeat, got %q", status)
+ }
+}
+
+// TestRecordHeartbeat_TouchErrorFallsBackToDB confirms graceful degradation:
+// if Redis Touch errors, the heartbeat still writes the DB so the sweeper's
+// DB-only fallback path observes a fresh last_seen_at.
+func TestRecordHeartbeat_TouchErrorFallsBackToDB(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
+
+ fake := &fakeLivenessStore{
+ available: true,
+ touchErr: errors.New("simulated redis outage"),
+ }
+ orig := testHandler.LivenessStore
+ testHandler.LivenessStore = fake
+ t.Cleanup(func() { testHandler.LivenessStore = orig })
+
+ setRuntimeLastSeenAt(t, runtimeID, time.Now())
+ rt := loadRuntime(t, runtimeID)
+ before := rt.LastSeenAt.Time
+
+ time.Sleep(50 * time.Millisecond)
+
+ if err := testHandler.recordHeartbeat(context.Background(), rt); err != nil {
+ t.Fatalf("recordHeartbeat: %v", err)
+ }
+
+ _, lastSeen, _ := readRuntimeRow(t, runtimeID)
+ if !lastSeen.After(before) {
+ t.Fatalf("Touch failure should have fallen back to a DB write: before=%s after=%s", before, lastSeen)
+ }
+}
+
+// TestRecordHeartbeat_SweeperRaceRecoversOnline pins the regression for the
+// status-snapshot race: rt.Status was read from a prior SELECT, but the
+// sweeper can flip the row to offline between that SELECT and the heartbeat's
+// write. Without the affected-rows fallback in recordHeartbeat, the heartbeat
+// would only bump last_seen_at and leave the row stuck offline. The legacy
+// UpdateAgentRuntimeHeartbeat always re-asserted status='online', so this
+// regression test guards the new SELECT/Touch/MarkOnline path against the
+// same scenario.
+func TestRecordHeartbeat_SweeperRaceRecoversOnline(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
+
+ // Force the noop store so recordHeartbeat takes the DB-write path
+ // without any Redis interference. The race is independent of the
+ // liveness store — it lives entirely between the rt.Status snapshot
+ // and the DB UPDATE.
+ orig := testHandler.LivenessStore
+ testHandler.LivenessStore = NewNoopLivenessStore()
+ t.Cleanup(func() { testHandler.LivenessStore = orig })
+
+ // Snapshot the runtime while it is still online.
+ rt := loadRuntime(t, runtimeID)
+ if rt.Status != "online" {
+ t.Fatalf("setup: runtime should be online, got %q", rt.Status)
+ }
+
+ // Simulate the sweeper flipping the row to offline between the
+ // snapshot and the heartbeat's UPDATE.
+ setRuntimeStatus(t, runtimeID, "offline")
+
+ if err := testHandler.recordHeartbeat(context.Background(), rt); err != nil {
+ t.Fatalf("recordHeartbeat: %v", err)
+ }
+
+ status, lastSeen, _ := readRuntimeRow(t, runtimeID)
+ if status != "online" {
+ t.Fatalf("expected sweeper-raced runtime to recover online, got %q", status)
+ }
+ if time.Since(lastSeen) > 30*time.Second {
+ t.Fatalf("last_seen_at not refreshed: %s ago", time.Since(lastSeen))
+ }
+}
diff --git a/server/internal/handler/runtime_liveness_store.go b/server/internal/handler/runtime_liveness_store.go
new file mode 100644
index 0000000000..c14a39f829
--- /dev/null
+++ b/server/internal/handler/runtime_liveness_store.go
@@ -0,0 +1,130 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+// LivenessStore tracks short-lived "this runtime heartbeated recently" records.
+// It exists so the heartbeat hot path can write a TTL'd Redis key instead of
+// rewriting agent_runtime.last_seen_at on every beat. The DB row is still the
+// authority for state transitions and the fallback when the store is unavailable.
+//
+// The interface is deliberately small and side-effect-free on errors: callers
+// that get an error from Touch or ok=false from IsAlive must fall back to the
+// DB-only behavior (rewrite last_seen_at every beat; trust the SQL stale window
+// in the sweeper). That keeps the system correct end-to-end whenever Redis is
+// missing or unhealthy without any per-call configuration.
+type LivenessStore interface {
+ // Available reports whether the store is wired to a real backend. False
+ // means callers should treat the DB as the only source of truth — the
+ // other methods on a non-available store are no-ops.
+ Available() bool
+
+ // Touch records a fresh heartbeat for runtimeID with the given TTL.
+ // Returns an error on backend failure; callers should fall back to a
+ // DB heartbeat write on error.
+ Touch(ctx context.Context, runtimeID string, ttl time.Duration) error
+
+ // IsAliveBatch reports liveness for many runtime IDs at once. The
+ // returned map covers every input ID (false for any not alive). ok=false
+ // signals the backend errored or is unavailable; callers must fall back
+ // to the DB stale window.
+ IsAliveBatch(ctx context.Context, runtimeIDs []string) (alive map[string]bool, ok bool)
+
+ // Forget drops the liveness record for runtimeID. Used on deregister
+ // and after the sweeper confirms a runtime offline. Best-effort: errors
+ // are logged but not returned, since the TTL will reap the key anyway.
+ Forget(ctx context.Context, runtimeID string)
+}
+
+// noopLivenessStore is the default — used whenever no Redis client is wired in.
+// All methods are no-ops; Available() returns false so callers know to use
+// the DB path.
+type noopLivenessStore struct{}
+
+// NewNoopLivenessStore returns a LivenessStore that always reports unavailable.
+// Callers should default to this and swap in a real store at wire time.
+func NewNoopLivenessStore() LivenessStore { return noopLivenessStore{} }
+
+func (noopLivenessStore) Available() bool { return false }
+
+func (noopLivenessStore) Touch(_ context.Context, _ string, _ time.Duration) error {
+ return nil
+}
+
+func (noopLivenessStore) IsAliveBatch(_ context.Context, _ []string) (map[string]bool, bool) {
+ return nil, false
+}
+
+func (noopLivenessStore) Forget(_ context.Context, _ string) {}
+
+// runtimeLivenessKeyPrefix is the Redis key prefix for runtime liveness
+// records. Mirrors the namespacing used by the other runtime stores
+// (mul:update:*, mul:model_list:*, mul:local_skill_list:*).
+const runtimeLivenessKeyPrefix = "mul:runtime:hb:"
+
+func runtimeLivenessKey(runtimeID string) string {
+ return runtimeLivenessKeyPrefix + runtimeID
+}
+
+// RedisLivenessStore writes one TTL'd key per runtime heartbeat. The presence
+// of an unexpired key is the signal "this runtime is alive right now"; the
+// sweeper consults this before marking a stale-in-DB runtime offline.
+type RedisLivenessStore struct {
+ rdb *redis.Client
+}
+
+func NewRedisLivenessStore(rdb *redis.Client) *RedisLivenessStore {
+ return &RedisLivenessStore{rdb: rdb}
+}
+
+func (s *RedisLivenessStore) Available() bool { return s != nil && s.rdb != nil }
+
+func (s *RedisLivenessStore) Touch(ctx context.Context, runtimeID string, ttl time.Duration) error {
+ if !s.Available() {
+ return errors.New("redis liveness store: unavailable")
+ }
+ if runtimeID == "" {
+ return errors.New("redis liveness store: empty runtime id")
+ }
+ if err := s.rdb.Set(ctx, runtimeLivenessKey(runtimeID), "1", ttl).Err(); err != nil {
+ return fmt.Errorf("liveness touch: %w", err)
+ }
+ return nil
+}
+
+func (s *RedisLivenessStore) IsAliveBatch(ctx context.Context, runtimeIDs []string) (map[string]bool, bool) {
+ if !s.Available() || len(runtimeIDs) == 0 {
+ return map[string]bool{}, s.Available()
+ }
+ keys := make([]string, len(runtimeIDs))
+ for i, id := range runtimeIDs {
+ keys[i] = runtimeLivenessKey(id)
+ }
+ values, err := s.rdb.MGet(ctx, keys...).Result()
+ if err != nil {
+ slog.Warn("liveness mget failed; falling back to DB",
+ "error", err, "count", len(keys))
+ return nil, false
+ }
+ out := make(map[string]bool, len(runtimeIDs))
+ for i, id := range runtimeIDs {
+ out[id] = values[i] != nil
+ }
+ return out, true
+}
+
+func (s *RedisLivenessStore) Forget(ctx context.Context, runtimeID string) {
+ if !s.Available() || runtimeID == "" {
+ return
+ }
+ if err := s.rdb.Del(ctx, runtimeLivenessKey(runtimeID)).Err(); err != nil {
+ slog.Warn("liveness forget failed", "error", err, "runtime_id", runtimeID)
+ }
+}
diff --git a/server/internal/handler/runtime_liveness_store_test.go b/server/internal/handler/runtime_liveness_store_test.go
new file mode 100644
index 0000000000..d36fd27329
--- /dev/null
+++ b/server/internal/handler/runtime_liveness_store_test.go
@@ -0,0 +1,107 @@
+package handler
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+func TestNoopLivenessStore_AlwaysUnavailable(t *testing.T) {
+ s := NewNoopLivenessStore()
+ if s.Available() {
+ t.Fatal("noop store reported Available()=true")
+ }
+ if err := s.Touch(context.Background(), "rt-1", time.Second); err != nil {
+ t.Fatalf("noop Touch returned error: %v", err)
+ }
+ alive, ok := s.IsAliveBatch(context.Background(), []string{"rt-1"})
+ if ok {
+ t.Fatalf("noop IsAliveBatch returned ok=true with alive=%v", alive)
+ }
+ // Forget on the noop must not panic.
+ s.Forget(context.Background(), "rt-1")
+}
+
+func TestRedisLivenessStore_TouchAndIsAlive(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ ctx := context.Background()
+ s := NewRedisLivenessStore(rdb)
+
+ if !s.Available() {
+ t.Fatal("redis store reported Available()=false with a live client")
+ }
+
+ if err := s.Touch(ctx, "rt-1", 10*time.Second); err != nil {
+ t.Fatalf("Touch: %v", err)
+ }
+
+ alive, ok := s.IsAliveBatch(ctx, []string{"rt-1", "rt-missing"})
+ if !ok {
+ t.Fatal("IsAliveBatch returned ok=false against a healthy Redis")
+ }
+ if !alive["rt-1"] {
+ t.Fatal("rt-1 was just touched but IsAliveBatch reported dead")
+ }
+ if alive["rt-missing"] {
+ t.Fatal("rt-missing was never touched but IsAliveBatch reported alive")
+ }
+}
+
+func TestRedisLivenessStore_TTLExpiry(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ ctx := context.Background()
+ s := NewRedisLivenessStore(rdb)
+
+ // Use a real (small) TTL — go-redis SET supports milliseconds via the
+ // time.Duration parameter, but most production Redis builds round
+ // sub-second TTLs to one second. Use 1 second + sleep slightly longer.
+ if err := s.Touch(ctx, "rt-expire", 1*time.Second); err != nil {
+ t.Fatalf("Touch: %v", err)
+ }
+ alive, ok := s.IsAliveBatch(ctx, []string{"rt-expire"})
+ if !ok || !alive["rt-expire"] {
+ t.Fatalf("expected fresh touch to be alive, got ok=%v alive=%+v", ok, alive)
+ }
+
+ time.Sleep(1500 * time.Millisecond)
+
+ alive, ok = s.IsAliveBatch(ctx, []string{"rt-expire"})
+ if !ok {
+ t.Fatal("IsAliveBatch returned ok=false against a healthy Redis")
+ }
+ if alive["rt-expire"] {
+ t.Fatal("expected key to expire after TTL but IsAliveBatch reported alive")
+ }
+}
+
+func TestRedisLivenessStore_Forget(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ ctx := context.Background()
+ s := NewRedisLivenessStore(rdb)
+
+ if err := s.Touch(ctx, "rt-forget", 10*time.Second); err != nil {
+ t.Fatalf("Touch: %v", err)
+ }
+ s.Forget(ctx, "rt-forget")
+
+ alive, ok := s.IsAliveBatch(ctx, []string{"rt-forget"})
+ if !ok {
+ t.Fatal("IsAliveBatch returned ok=false against a healthy Redis")
+ }
+ if alive["rt-forget"] {
+ t.Fatal("Forget did not drop the liveness record")
+ }
+}
+
+func TestRedisLivenessStore_BatchEmptyInput(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ s := NewRedisLivenessStore(rdb)
+
+ alive, ok := s.IsAliveBatch(context.Background(), nil)
+ if !ok {
+ t.Fatal("expected ok=true on empty input against a healthy Redis")
+ }
+ if len(alive) != 0 {
+ t.Fatalf("expected empty result map, got %+v", alive)
+ }
+}
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 60e72aa3c4..6d1f5749ae 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -344,28 +344,77 @@ func (q *Queries) ListAgentRuntimesByOwner(ctx context.Context, arg ListAgentRun
return items, nil
}
-const markStaleRuntimesOffline = `-- name: MarkStaleRuntimesOffline :many
+const markAgentRuntimeOnline = `-- name: MarkAgentRuntimeOnline :one
+UPDATE agent_runtime
+SET status = 'online', last_seen_at = now(), updated_at = now()
+WHERE id = $1
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id
+`
+
+// Used on the offline→online transition (and on first heartbeat after
+// registration). Writes status, last_seen_at, and updated_at because the
+// status flip is a real state change and we want updated_at to reflect it.
+func (q *Queries) MarkAgentRuntimeOnline(ctx context.Context, id pgtype.UUID) (AgentRuntime, error) {
+ row := q.db.QueryRow(ctx, markAgentRuntimeOnline, id)
+ var i AgentRuntime
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DaemonID,
+ &i.Name,
+ &i.RuntimeMode,
+ &i.Provider,
+ &i.Status,
+ &i.DeviceInfo,
+ &i.Metadata,
+ &i.LastSeenAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.OwnerID,
+ &i.LegacyDaemonID,
+ )
+ return i, err
+}
+
+const markRuntimesOfflineByIDs = `-- name: MarkRuntimesOfflineByIDs :many
UPDATE agent_runtime
SET status = 'offline', updated_at = now()
WHERE status = 'online'
- AND last_seen_at < now() - make_interval(secs => $1::double precision)
+ AND id = ANY($1::uuid[])
+ AND last_seen_at < now() - make_interval(secs => $2::double precision)
RETURNING id, workspace_id
`
-type MarkStaleRuntimesOfflineRow struct {
+type MarkRuntimesOfflineByIDsParams struct {
+ Ids []pgtype.UUID `json:"ids"`
+ StaleSeconds float64 `json:"stale_seconds"`
+}
+
+type MarkRuntimesOfflineByIDsRow struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
}
-func (q *Queries) MarkStaleRuntimesOffline(ctx context.Context, staleSeconds float64) ([]MarkStaleRuntimesOfflineRow, error) {
- rows, err := q.db.Query(ctx, markStaleRuntimesOffline, staleSeconds)
+// Flips a known set of runtime IDs from online to offline. Paired with
+// SelectStaleOnlineRuntimes in the sweeper so the candidate selection and
+// the actual write are decoupled (the LivenessStore filter sits between).
+//
+// Re-checks the stale predicate inside the UPDATE so a concurrent heartbeat
+// between the SELECT (candidate gather), the LivenessStore filter, and this
+// UPDATE cannot demote a runtime that just refreshed last_seen_at. The
+// legacy MarkStaleRuntimesOffline UPDATE had this property implicitly
+// because the predicate and the write lived in one statement; here we
+// carry it forward explicitly so the SELECT/filter/UPDATE pipeline retains
+// the same race-freedom.
+func (q *Queries) MarkRuntimesOfflineByIDs(ctx context.Context, arg MarkRuntimesOfflineByIDsParams) ([]MarkRuntimesOfflineByIDsRow, error) {
+ rows, err := q.db.Query(ctx, markRuntimesOfflineByIDs, arg.Ids, arg.StaleSeconds)
if err != nil {
return nil, err
}
defer rows.Close()
- items := []MarkStaleRuntimesOfflineRow{}
+ items := []MarkRuntimesOfflineByIDsRow{}
for rows.Next() {
- var i MarkStaleRuntimesOfflineRow
+ var i MarkRuntimesOfflineByIDsRow
if err := rows.Scan(&i.ID, &i.WorkspaceID); err != nil {
return nil, err
}
@@ -439,6 +488,41 @@ func (q *Queries) RecordRuntimeLegacyDaemonID(ctx context.Context, arg RecordRun
return err
}
+const selectStaleOnlineRuntimes = `-- name: SelectStaleOnlineRuntimes :many
+SELECT id, workspace_id FROM agent_runtime
+WHERE status = 'online'
+ AND last_seen_at < now() - make_interval(secs => $1::double precision)
+`
+
+type SelectStaleOnlineRuntimesRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Lists online runtimes whose last_seen_at exceeds the stale window. The
+// sweeper uses this as a candidate set, then optionally filters via the
+// LivenessStore before flipping rows to offline (a fresh Redis liveness
+// record means the DB row is just lagging, not actually dead).
+func (q *Queries) SelectStaleOnlineRuntimes(ctx context.Context, staleSeconds float64) ([]SelectStaleOnlineRuntimesRow, error) {
+ rows, err := q.db.Query(ctx, selectStaleOnlineRuntimes, staleSeconds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []SelectStaleOnlineRuntimesRow{}
+ for rows.Next() {
+ var i SelectStaleOnlineRuntimesRow
+ if err := rows.Scan(&i.ID, &i.WorkspaceID); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const setAgentRuntimeOffline = `-- name: SetAgentRuntimeOffline :exec
UPDATE agent_runtime
SET status = 'offline', updated_at = now()
@@ -450,33 +534,30 @@ func (q *Queries) SetAgentRuntimeOffline(ctx context.Context, id pgtype.UUID) er
return err
}
-const updateAgentRuntimeHeartbeat = `-- name: UpdateAgentRuntimeHeartbeat :one
+const touchAgentRuntimeLastSeen = `-- name: TouchAgentRuntimeLastSeen :execrows
UPDATE agent_runtime
-SET status = 'online', last_seen_at = now(), updated_at = now()
-WHERE id = $1
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id
+SET last_seen_at = now()
+WHERE id = $1 AND status = 'online'
`
-func (q *Queries) UpdateAgentRuntimeHeartbeat(ctx context.Context, id pgtype.UUID) (AgentRuntime, error) {
- row := q.db.QueryRow(ctx, updateAgentRuntimeHeartbeat, id)
- var i AgentRuntime
- err := row.Scan(
- &i.ID,
- &i.WorkspaceID,
- &i.DaemonID,
- &i.Name,
- &i.RuntimeMode,
- &i.Provider,
- &i.Status,
- &i.DeviceInfo,
- &i.Metadata,
- &i.LastSeenAt,
- &i.CreatedAt,
- &i.UpdatedAt,
- &i.OwnerID,
- &i.LegacyDaemonID,
- )
- return i, err
+// Bumps last_seen_at on an already-online runtime. Deliberately does NOT
+// touch status or updated_at: status is unchanged on the hot heartbeat path,
+// and avoiding updated_at keeps the row HOT-eligible (no index columns
+// change) and avoids invalidating any downstream consumer that watches
+// updated_at.
+//
+// The status='online' predicate is load-bearing: callers read rt.Status from
+// a prior SELECT and may race with the sweeper, which can flip the row to
+// offline between that SELECT and this UPDATE. Without the predicate this
+// query would silently leave a freshly-heartbeated runtime stuck in offline.
+// Returning affected rows lets callers detect that race and fall back to
+// MarkAgentRuntimeOnline to flip the row back online.
+func (q *Queries) TouchAgentRuntimeLastSeen(ctx context.Context, id pgtype.UUID) (int64, error) {
+ result, err := q.db.Exec(ctx, touchAgentRuntimeLastSeen, id)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
}
const upsertAgentRuntime = `-- name: UpsertAgentRuntime :one
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index 40ab65dc93..d2d32dbe7f 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -39,7 +39,27 @@ DO UPDATE SET
updated_at = now()
RETURNING *, (xmax = 0) AS inserted;
--- name: UpdateAgentRuntimeHeartbeat :one
+-- name: TouchAgentRuntimeLastSeen :execrows
+-- Bumps last_seen_at on an already-online runtime. Deliberately does NOT
+-- touch status or updated_at: status is unchanged on the hot heartbeat path,
+-- and avoiding updated_at keeps the row HOT-eligible (no index columns
+-- change) and avoids invalidating any downstream consumer that watches
+-- updated_at.
+--
+-- The status='online' predicate is load-bearing: callers read rt.Status from
+-- a prior SELECT and may race with the sweeper, which can flip the row to
+-- offline between that SELECT and this UPDATE. Without the predicate this
+-- query would silently leave a freshly-heartbeated runtime stuck in offline.
+-- Returning affected rows lets callers detect that race and fall back to
+-- MarkAgentRuntimeOnline to flip the row back online.
+UPDATE agent_runtime
+SET last_seen_at = now()
+WHERE id = $1 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
+-- status flip is a real state change and we want updated_at to reflect it.
UPDATE agent_runtime
SET status = 'online', last_seen_at = now(), updated_at = now()
WHERE id = $1
@@ -50,10 +70,31 @@ UPDATE agent_runtime
SET status = 'offline', updated_at = now()
WHERE id = $1;
--- name: MarkStaleRuntimesOffline :many
+-- name: SelectStaleOnlineRuntimes :many
+-- Lists online runtimes whose last_seen_at exceeds the stale window. The
+-- sweeper uses this as a candidate set, then optionally filters via the
+-- LivenessStore before flipping rows to offline (a fresh Redis liveness
+-- record means the DB row is just lagging, not actually dead).
+SELECT id, workspace_id FROM agent_runtime
+WHERE status = 'online'
+ AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision);
+
+-- name: MarkRuntimesOfflineByIDs :many
+-- Flips a known set of runtime IDs from online to offline. Paired with
+-- SelectStaleOnlineRuntimes in the sweeper so the candidate selection and
+-- the actual write are decoupled (the LivenessStore filter sits between).
+--
+-- Re-checks the stale predicate inside the UPDATE so a concurrent heartbeat
+-- between the SELECT (candidate gather), the LivenessStore filter, and this
+-- UPDATE cannot demote a runtime that just refreshed last_seen_at. The
+-- legacy MarkStaleRuntimesOffline UPDATE had this property implicitly
+-- because the predicate and the write lived in one statement; here we
+-- carry it forward explicitly so the SELECT/filter/UPDATE pipeline retains
+-- the same race-freedom.
UPDATE agent_runtime
SET status = 'offline', updated_at = now()
WHERE status = 'online'
+ AND id = ANY(@ids::uuid[])
AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)
RETURNING id, workspace_id;