Skip to content

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

Go

MUL-7002: remove database reads from WebSocket heartbeats (#7976)

Multica Eve571e61128d0a
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 22fafd00ff..524edce0ba 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -371,7 +371,10 @@ func main() {
hub := realtime.NewHub()
go hub.Run()
daemonHub := daemonws.NewHub()
- var daemonWakeup service.TaskWakeupNotifier = daemonHub
+ var daemonWakeup interface {
+ service.TaskWakeupNotifier
+ handler.RuntimeGoneNotifier
+ } = daemonHub
// Nil unless a Redis relay is running: without one there is only one
// replica, and it both publishes the completion and holds the socket.
var wecomRelay WecomRelay
@@ -585,7 +588,7 @@ func main() {
// 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)
+ heartbeatScheduler := handler.NewBatchedHeartbeatScheduler(queries, handler.DefaultHeartbeatBatchInterval, daemonWakeup)
// Validate the LLM retry budget before the router exists: an operator who
// typed a value we cannot honor should see the boot stop, the same way a
diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.go
index 6e36c4d3ee..b395378fc5 100644
--- a/server/internal/daemonws/hub.go
+++ b/server/internal/daemonws/hub.go
@@ -26,15 +26,77 @@ type ClientIdentity struct {
// WorkspaceID is the legacy single-workspace scope used by older callers
// and daemon-token auth. New code should populate WorkspaceIDs from the
// runtime rows authorized for this connection.
- WorkspaceID string
- WorkspaceIDs []string
- RuntimeIDs []string
+ WorkspaceID string
+ WorkspaceIDs []string
+ RuntimeIDs []string
+ // RuntimeLeases is populated from the connection-time batch authorization
+ // query. Entries are retained for the lifetime of the connection to avoid
+ // concurrent map writes; they are not an authorization source. client.runtimes
+ // is the sole mutable heartbeat scope and is checked before a lease is used.
+ // Each value tracks only the DB liveness state needed to throttle writes.
+ RuntimeLeases map[string]*RuntimeLease
ClientVersion string
// Capabilities is the raw X-Client-Capabilities header captured at connect,
// so RPC handlers can honor the same capability gating as the HTTP path.
Capabilities string
}
+// RuntimeLease is the connection-scoped liveness state for one already
+// authenticated runtime. Ownership is immutable after the WebSocket upgrade;
+// only the last DB write and status advance as heartbeats are processed.
+type RuntimeLease struct {
+ mu sync.Mutex
+
+ workspaceID string
+ status string
+ lastSeenAt time.Time
+ lastSeenAtValid bool
+}
+
+// RuntimeLeaseState is an atomic snapshot used by the heartbeat handler.
+type RuntimeLeaseState struct {
+ WorkspaceID string
+ Status string
+ LastSeenAt time.Time
+ LastSeenAtValid bool
+}
+
+func NewRuntimeLease(workspaceID, status string, lastSeenAt time.Time, lastSeenAtValid bool) *RuntimeLease {
+ return &RuntimeLease{
+ workspaceID: workspaceID,
+ status: status,
+ lastSeenAt: lastSeenAt,
+ lastSeenAtValid: lastSeenAtValid,
+ }
+}
+
+func (l *RuntimeLease) Snapshot() RuntimeLeaseState {
+ if l == nil {
+ return RuntimeLeaseState{}
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return RuntimeLeaseState{
+ WorkspaceID: l.workspaceID,
+ Status: l.status,
+ LastSeenAt: l.lastSeenAt,
+ LastSeenAtValid: l.lastSeenAtValid,
+ }
+}
+
+// MarkDBWriteScheduled advances the connection's DB-flush watermark after a
+// synchronous write succeeds or a durable batch entry has been accepted.
+func (l *RuntimeLease) MarkDBWriteScheduled(at time.Time) {
+ if l == nil {
+ return
+ }
+ l.mu.Lock()
+ l.status = "online"
+ l.lastSeenAt = at
+ l.lastSeenAtValid = true
+ l.mu.Unlock()
+}
+
// AuthorizedWorkspaceIDs returns the connection's workspace scope in stable
// order, preferring the multi-workspace field and falling back to WorkspaceID
// for older tests/callers.
@@ -86,11 +148,12 @@ func (i ClientIdentity) AllowsWorkspace(workspaceID string) bool {
}
type client struct {
- hub *Hub
- conn *websocket.Conn
- send chan []byte
- identity ClientIdentity
- runtimes map[string]struct{}
+ hub *Hub
+ conn *websocket.Conn
+ send chan []byte
+ identity ClientIdentity
+ runtimeMu sync.RWMutex
+ runtimes map[string]struct{}
// ctx is cancelled when the connection tears down, so async RPC handlers
// stop instead of running against a dead socket. cancel is invoked from
@@ -129,7 +192,13 @@ func (c *client) trySend(frame []byte) bool {
}
}
-const eventDedupCapacity = 128
+const (
+ eventDedupCapacity = 128
+ // The runtime-gone cache is hub-wide rather than per connection. Size it
+ // independently to retain a complete runtime GC batch (currently capped at
+ // 500) through local delivery and Redis loopback.
+ runtimeGoneDedupCapacity = 512
+)
// markSeen records eventID as already delivered to this client. Empty event IDs
// disable dedup and are always delivered.
@@ -155,6 +224,63 @@ func (c *client) markSeen(eventID string) bool {
return true
}
+func (c *client) allowsRuntime(runtimeID string) bool {
+ c.runtimeMu.RLock()
+ defer c.runtimeMu.RUnlock()
+ _, ok := c.runtimes[runtimeID]
+ return ok
+}
+
+func (c *client) removeRuntime(runtimeID string) {
+ c.runtimeMu.Lock()
+ delete(c.runtimes, runtimeID)
+ c.runtimeMu.Unlock()
+}
+
+func (c *client) runtimeCount() int {
+ c.runtimeMu.RLock()
+ defer c.runtimeMu.RUnlock()
+ return len(c.runtimes)
+}
+
+// markRuntimeGoneSeen deduplicates a runtime invalidation at the Hub level.
+// Runtime invalidation removes the client from byRuntime, so the ordinary
+// per-client event cache is no longer reachable when the Redis loopback of a
+// locally delivered event arrives.
+func (h *Hub) markRuntimeGoneSeen(eventID string) bool {
+ if eventID == "" {
+ return true
+ }
+ h.runtimeGoneDedupMu.Lock()
+ defer h.runtimeGoneDedupMu.Unlock()
+ if _, ok := h.runtimeGoneSeenIDs[eventID]; ok {
+ return false
+ }
+ h.runtimeGoneSeenIDs[eventID] = struct{}{}
+ h.runtimeGoneSeenOrder = append(h.runtimeGoneSeenOrder, eventID)
+ if len(h.runtimeGoneSeenOrder) > runtimeGoneDedupCapacity {
+ drop := h.runtimeGoneSeenOrder[0]
+ h.runtimeGoneSeenOrder = h.runtimeGoneSeenOrder[1:]
+ delete(h.runtimeGoneSeenIDs, drop)
+ }
+ return true
+}
+
+func (h *Hub) forgetRuntimeGoneSeen(eventID string) {
+ if eventID == "" {
+ return
+ }
+ h.runtimeGoneDedupMu.Lock()
+ delete(h.runtimeGoneSeenIDs, eventID)
+ for index, seenID := range h.runtimeGoneSeenOrder {
+ if seenID == eventID {
+ h.runtimeGoneSeenOrder = append(h.runtimeGoneSeenOrder[:index], h.runtimeGoneSeenOrder[index+1:]...)
+ break
+ }
+ }
+ h.runtimeGoneDedupMu.Unlock()
+}
+
// HeartbeatHandler processes a daemon:heartbeat frame. It must verify that
// runtimeID is one of identity.RuntimeIDs (the connection's authenticated
// scope) and return the ack payload to send back. Returning an error skips
@@ -192,6 +318,10 @@ type Hub struct {
byWorkspace map[string]map[*client]bool
byUser map[string]map[*client]bool
+ runtimeGoneDedupMu sync.Mutex
+ runtimeGoneSeenIDs map[string]struct{}
+ runtimeGoneSeenOrder []string
+
hbMu sync.RWMutex
onHeartbeat HeartbeatHandler
@@ -212,10 +342,11 @@ func NewHub() *Hub {
// grows cookie fallback.
CheckOrigin: func(r *http.Request) bool { return true },
},
- clients: make(map[*client]bool),
- byRuntime: make(map[string]map[*client]bool),
- byWorkspace: make(map[string]map[*client]bool),
- byUser: make(map[string]map[*client]bool),
+ clients: make(map[*client]bool),
+ byRuntime: make(map[string]map[*client]bool),
+ byWorkspace: make(map[string]map[*client]bool),
+ byUser: make(map[string]map[*client]bool),
+ runtimeGoneSeenIDs: make(map[string]struct{}, runtimeGoneDedupCapacity),
}
}
@@ -337,8 +468,9 @@ func (h *Hub) NotifyPendingWork(runtimeID, kind string) {
}
// NotifyRuntimeGone tells daemons watching runtimeID that the server deleted
-// the runtime. The existing heartbeat lookup remains the correctness fallback;
-// this notification only closes the active-connection invalidation gap.
+// the runtime and removes it from each connection's heartbeat scope. The
+// heartbeat scheduler's batch write receipts remain the correctness fallback
+// when this best-effort notification is missed.
func (h *Hub) NotifyRuntimeGone(runtimeID string) {
h.notifyRuntimeGone(runtimeID, "")
}
@@ -405,7 +537,7 @@ func (h *Hub) notifyRuntimeGone(runtimeID, eventID string) {
if err != nil {
return
}
- delivered, deduped := h.notifyFrame(runtimeID, data, eventID)
+ delivered, deduped := h.invalidateRuntime(runtimeID, data, eventID)
if delivered {
M.RuntimeGoneDeliveredHit.Add(1)
} else if !deduped {
@@ -413,6 +545,52 @@ func (h *Hub) notifyRuntimeGone(runtimeID, eventID string) {
}
}
+func (h *Hub) invalidateRuntime(runtimeID string, data []byte, eventID string) (delivered bool, deduped bool) {
+ h.mu.Lock()
+ connections := h.byRuntime[runtimeID]
+ clients := make([]*client, 0, len(connections))
+ for c := range connections {
+ c.removeRuntime(runtimeID)
+ clients = append(clients, c)
+ }
+ delete(h.byRuntime, runtimeID)
+ h.mu.Unlock()
+ if len(clients) == 0 {
+ if !h.markRuntimeGoneSeen(eventID) {
+ return false, true
+ }
+ // Do not consume the event when it raced just ahead of connection
+ // registration. Its Redis loopback/replay can still invalidate the
+ // newly registered scope; the batch receipt remains the final fallback.
+ h.forgetRuntimeGoneSeen(eventID)
+ return false, false
+ }
+ // Mark only after removing the current clients. If this event was already
+ // seen, the clients collected above registered after its first delivery and
+ // still need invalidation; clients from the first delivery are no longer in
+ // byRuntime and cannot receive a duplicate frame.
+ h.markRuntimeGoneSeen(eventID)
+
+ slow := make([]*client, 0)
+ for _, c := range clients {
+ if !c.markSeen(eventID) {
+ deduped = true
+ continue
+ }
+ if c.trySend(data) {
+ delivered = true
+ } else {
+ slow = append(slow, c)
+ }
+ }
+ for _, c := range slow {
+ M.SlowEvictionsTotal.Add(1)
+ h.unregister(c)
+ c.conn.Close()
+ }
+ return delivered, deduped
+}
+
func (h *Hub) DeliverDaemonRuntime(scopeID string, frame []byte, eventID string) {
if h == nil {
return
@@ -483,7 +661,7 @@ func (h *Hub) DeliverDaemonRuntime(scopeID string, frame []byte, eventID string)
M.RuntimeGoneDeliveredMiss.Add(1)
return
}
- delivered, deduped := h.notifyFrame(payload.RuntimeID, frame, eventID)
+ delivered, deduped := h.invalidateRuntime(payload.RuntimeID, frame, eventID)
if delivered {
M.RuntimeGoneDeliveredHit.Add(1)
} else if !deduped {
@@ -656,6 +834,7 @@ func (h *Hub) UserConnectionCount(userID string) int {
func (h *Hub) register(c *client) {
h.mu.Lock()
h.clients[c] = true
+ c.runtimeMu.RLock()
for runtimeID := range c.runtimes {
conns := h.byRuntime[runtimeID]
if conns == nil {
@@ -664,6 +843,7 @@ func (h *Hub) register(c *client) {
}
conns[c] = true
}
+ c.runtimeMu.RUnlock()
workspaceIDs := c.identity.AuthorizedWorkspaceIDs()
for _, workspaceID := range workspaceIDs {
conns := h.byWorkspace[workspaceID]
@@ -691,7 +871,7 @@ func (h *Hub) register(c *client) {
"user_id", c.identity.UserID,
"workspace_id", c.identity.PrimaryWorkspaceID(),
"workspace_ids", workspaceIDs,
- "runtimes", len(c.runtimes),
+ "runtimes", c.runtimeCount(),
"client_version", c.identity.ClientVersion,
"total_clients", total,
)
@@ -704,6 +884,7 @@ func (h *Hub) unregister(c *client) {
return
}
delete(h.clients, c)
+ c.runtimeMu.RLock()
for runtimeID := range c.runtimes {
if conns := h.byRuntime[runtimeID]; conns != nil {
delete(conns, c)
@@ -712,6 +893,7 @@ func (h *Hub) unregister(c *client) {
}
}
}
+ c.runtimeMu.RUnlock()
workspaceIDs := c.identity.AuthorizedWorkspaceIDs()
for _, workspaceID := range workspaceIDs {
if conns := h.byWorkspace[workspaceID]; conns != nil {
@@ -743,7 +925,7 @@ func (h *Hub) unregister(c *client) {
"user_id", c.identity.UserID,
"workspace_id", c.identity.PrimaryWorkspaceID(),
"workspace_ids", workspaceIDs,
- "runtimes", len(c.runtimes),
+ "runtimes", c.runtimeCount(),
"total_clients", total,
)
}
@@ -900,7 +1082,7 @@ func (c *client) handleHeartbeatFrame(raw json.RawMessage) {
slog.Debug("daemon websocket heartbeat missing runtime_id", "daemon_id", c.identity.DaemonID)
return
}
- if _, ok := c.runtimes[payload.RuntimeID]; !ok {
+ if !c.allowsRuntime(payload.RuntimeID) {
// The connection authenticated for a fixed runtime set; reject any
// heartbeat for a runtime the client did not register for.
slog.Warn("daemon websocket heartbeat for unauthorized runtime",
diff --git a/server/internal/daemonws/runtime_gone_test.go b/server/internal/daemonws/runtime_gone_test.go
index 760b6a0be9..826e7fcbee 100644
--- a/server/internal/daemonws/runtime_gone_test.go
+++ b/server/internal/daemonws/runtime_gone_test.go
@@ -26,6 +26,12 @@ func TestNotifyRuntimeGone(t *testing.T) {
if payload.Status != protocol.HeartbeatStatusRuntimeGone || !payload.RuntimeGone {
t.Fatalf("payload = %+v, want runtime_gone acknowledgement", payload)
}
+ if client.allowsRuntime("runtime-1") {
+ t.Fatal("invalidated runtime remained in the connection heartbeat scope")
+ }
+ if got := hub.RuntimeConnectionCount("runtime-1"); got != 0 {
+ t.Fatalf("runtime connection count = %d, want 0 after invalidation", got)
+ }
if M.RuntimeGoneDeliveredHit.Load() != 1 {
t.Fatalf("runtime-gone delivered hit metric = %d, want 1", M.RuntimeGoneDeliveredHit.Load())
}
@@ -75,6 +81,9 @@ func TestRelayNotifierPublishesAndDeliversRuntimeGone(t *testing.T) {
if payload.RuntimeID != "runtime-1" || payload.Status != protocol.HeartbeatStatusRuntimeGone || !payload.RuntimeGone {
t.Fatalf("payload = %+v, want relayed runtime_gone acknowledgement", payload)
}
+ if remoteClient.allowsRuntime("runtime-1") {
+ t.Fatal("relayed invalidation left runtime in the connection heartbeat scope")
+ }
remoteHub.DeliverDaemonRuntime(relay.scopeID, relay.frame, relay.eventID)
select {
@@ -155,6 +164,34 @@ func TestRelayNotifierDedupsRuntimeGoneLoopback(t *testing.T) {
}
}
+func TestRuntimeGoneReplayInvalidatesConnectionRegisteredAfterFirstDelivery(t *testing.T) {
+ M.Reset()
+ defer M.Reset()
+
+ hub := NewHub()
+ first := attachDaemonTestClient(hub, "runtime-1")
+ frame, err := runtimeGoneFrame("runtime-1")
+ if err != nil {
+ t.Fatalf("runtimeGoneFrame: %v", err)
+ }
+
+ hub.DeliverDaemonRuntime("runtime-1", frame, "event-1")
+ readRuntimeGoneFrame(t, first.send)
+
+ // Model a connection that passed its DB authorization before deletion but
+ // did not register with the Hub until after the first local delivery.
+ late := attachDaemonTestClient(hub, "runtime-1")
+ hub.DeliverDaemonRuntime("runtime-1", frame, "event-1")
+ readRuntimeGoneFrame(t, late.send)
+
+ if late.allowsRuntime("runtime-1") {
+ t.Fatal("relay replay left late connection in the heartbeat scope")
+ }
+ if got := hub.RuntimeConnectionCount("runtime-1"); got != 0 {
+ t.Fatalf("runtime connection count = %d, want 0", got)
+ }
+}
+
func readRuntimeGoneFrame(t *testing.T, frames <-chan []byte) protocol.DaemonHeartbeatAckPayload {
t.Helper()
select {
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 568fd372db..2f1567b9ab 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1114,8 +1114,16 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {
}
authMs = time.Since(start).Milliseconds()
- ack, m, err := h.processHeartbeat(r.Context(), rt, req.SupportsBatchImport)
- updateMs = m.UpdateMs
+ updateStart := time.Now()
+ if err := h.recordHeartbeat(r.Context(), rt); err != nil {
+ updateMs = time.Since(updateStart).Milliseconds()
+ outcome = "error_update"
+ writeError(w, http.StatusInternalServerError, "heartbeat failed")
+ return
+ }
+ updateMs = time.Since(updateStart).Milliseconds()
+
+ ack, m, err := h.processHeartbeat(r.Context(), runtimeID, req.SupportsBatchImport)
probeModelMs = m.ProbeModelMs
popModelMs = m.PopModelMs
probeSkillsMs = m.ProbeSkillsMs
@@ -1154,43 +1162,43 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
-// HandleDaemonWSHeartbeat is the daemonws.HeartbeatHandler entry point: it
-// resolves the runtime, verifies the connection's workspace owns it, and
-// returns the ack payload. It is the WebSocket-side mirror of DaemonHeartbeat.
-//
-// Workspace authorization is re-checked on every heartbeat instead of trusted
-// from the upgrade-time check because runtime ownership can change (e.g. a
-// runtime is reassigned to another workspace mid-connection).
-//
-// When the runtime row is missing (pgx.ErrNoRows), the function returns a
-// successful ack with Status=HeartbeatStatusRuntimeGone and RuntimeGone=true
-// instead of an error. That keeps the hub from logging every beat at Warn,
-// and tells the daemon to drop the stale runtime and re-register. Other DB
-// errors still propagate as errors so they keep their existing Warn logging
-// and the daemon does not mistake a hiccup for a deletion.
+// HandleDaemonWSHeartbeat is the daemonws.HeartbeatHandler entry point. The
+// WebSocket upgrade already batch-authenticated the fixed runtime set and
+// captured each runtime's liveness state in a connection lease, so the hot
+// path never reads agent_runtime. HTTP heartbeat remains the stateless lookup
+// fallback for a daemon that stops receiving WebSocket acknowledgements.
func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws.ClientIdentity, runtimeID string, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, error) {
- runtimeUUID, err := util.ParseUUID(runtimeID)
- if err != nil {
- return nil, fmt.Errorf("invalid runtime_id: %w", err)
+ lease := identity.RuntimeLeases[runtimeID]
+ if lease == nil {
+ return nil, fmt.Errorf("runtime not in connection lease")
}
- rt, err := h.getAgentRuntime(ctx, obsmetrics.RuntimeLookupSourceHeartbeatWS, runtimeUUID)
- if err != nil {
+ // Defensive consistency assertion only: the workspace scope and lease came
+ // from the same connection-time query. This does not re-authorize against DB.
+ if !identity.AllowsWorkspace(lease.Snapshot().WorkspaceID) {
+ return nil, fmt.Errorf("runtime not in connection workspace")
+ }
+ if err := h.recordHeartbeatLease(ctx, runtimeID, lease); err != nil {
if isNotFound(err) {
- return &protocol.DaemonHeartbeatAckPayload{
- RuntimeID: runtimeID,
- Status: protocol.HeartbeatStatusRuntimeGone,
- RuntimeGone: true,
- }, nil
+ if h.DaemonRuntimeGone != nil {
+ h.NotifyRuntimeGone(runtimeID)
+ return nil, nil
+ }
+ return runtimeGoneHeartbeatAck(runtimeID), nil
}
- return nil, fmt.Errorf("get agent runtime: %w", err)
+ return nil, err
}
- if !identity.AllowsWorkspace(uuidToString(rt.WorkspaceID)) {
- return nil, fmt.Errorf("runtime not in connection workspace")
- }
- ack, _, err := h.processHeartbeat(ctx, rt, supportsBatchImport)
+ ack, _, err := h.processHeartbeat(ctx, runtimeID, supportsBatchImport)
return ack, err
}
+func runtimeGoneHeartbeatAck(runtimeID string) *protocol.DaemonHeartbeatAckPayload {
+ return &protocol.DaemonHeartbeatAckPayload{
+ RuntimeID: runtimeID,
+ Status: protocol.HeartbeatStatusRuntimeGone,
+ RuntimeGone: true,
+ }
+}
+
// 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
@@ -1205,24 +1213,57 @@ func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws
// 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 {
+ return h.recordHeartbeatState(ctx, rt.ID, uuidToString(rt.ID), heartbeatLivenessState{
+ Status: rt.Status,
+ LastSeenAt: rt.LastSeenAt.Time,
+ LastSeenAtValid: rt.LastSeenAt.Valid,
+ }, nil)
+}
+
+func (h *Handler) recordHeartbeatLease(ctx context.Context, runtimeID string, lease *daemonws.RuntimeLease) error {
+ runtimeUUID, err := util.ParseUUID(runtimeID)
+ if err != nil {
+ return fmt.Errorf("invalid runtime_id: %w", err)
+ }
+ state := lease.Snapshot()
+ return h.recordHeartbeatState(ctx, runtimeUUID, runtimeID, heartbeatLivenessState{
+ Status: state.Status,
+ LastSeenAt: state.LastSeenAt,
+ LastSeenAtValid: state.LastSeenAtValid,
+ }, lease.MarkDBWriteScheduled)
+}
+
+type heartbeatLivenessState struct {
+ Status string
+ LastSeenAt time.Time
+ LastSeenAtValid bool
+}
+
+func (h *Handler) recordHeartbeatState(
+ ctx context.Context,
+ runtimeUUID pgtype.UUID,
+ runtimeID string,
+ state heartbeatLivenessState,
+ markDBWriteScheduled func(time.Time),
+) 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
+ state.Status != "online" ||
+ !state.LastSeenAtValid ||
+ now.Sub(state.LastSeenAt) >= runtimeHeartbeatDBFlushInterval
if h.LivenessStore.Available() {
- if err := h.LivenessStore.Touch(ctx, uuidToString(rt.ID), runtimeLivenessTTL); err != nil {
+ if err := h.LivenessStore.Touch(ctx, runtimeID, 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)
+ "runtime_id", runtimeID, "error", err)
needDBWrite = true
}
}
@@ -1231,33 +1272,40 @@ func (h *Handler) recordHeartbeat(ctx context.Context, rt db.AgentRuntime) error
return nil
}
- // 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)
+ // Status transitions remain synchronous so the acknowledgement cannot race
+ // dependent work that expects an online row. The steady-state online bump
+ // is ID-only and may be coalesced by the production scheduler.
+ if state.Status != "online" || !state.LastSeenAtValid {
+ if _, err := h.Queries.MarkAgentRuntimeOnline(ctx, runtimeUUID); err != nil {
+ return err
+ }
+ if markDBWriteScheduled != nil {
+ markDBWriteScheduled(now)
+ }
+ return nil
+ }
+ if err := h.HeartbeatScheduler.Schedule(ctx, runtimeUUID); err != nil {
+ return err
+ }
+ if markDBWriteScheduled != nil {
+ markDBWriteScheduled(now)
+ }
+ return nil
}
// heartbeatMetrics carries per-stage timings out of processHeartbeat so the
// HTTP slow-log can stay structured. The WS path discards them.
type heartbeatMetrics struct {
- UpdateMs, ProbeModelMs, PopModelMs, ProbeSkillsMs, PopSkillsMs, ProbeImportMs, PopImportMs int64
- ProbeModelTimedOut, ProbeSkillsTimedOut, ProbeImportTimedOut bool
+ ProbeModelMs, PopModelMs, ProbeSkillsMs, PopSkillsMs, ProbeImportMs, PopImportMs int64
+ ProbeModelTimedOut, ProbeSkillsTimedOut, ProbeImportTimedOut bool
}
-// processHeartbeat does the work shared by HTTP POST /api/daemon/heartbeat and
-// 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, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, heartbeatMetrics, error) {
+// processHeartbeat pulls pending actions for both HTTP and WebSocket
+// heartbeats using only the runtime ID. Each transport records liveness first:
+// HTTP uses its stateless runtime row, while WebSocket uses the connection
+// lease. Auth and request decoding also remain transport-specific.
+func (h *Handler) processHeartbeat(ctx context.Context, runtimeID string, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, heartbeatMetrics, error) {
var m heartbeatMetrics
- runtimeID := uuidToString(rt.ID)
-
- updateStart := time.Now()
- 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/daemon_test.go b/server/internal/handler/daemon_test.go
index a3d67743b2..cb48caa7d0 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -890,21 +890,24 @@ func TestDaemonHeartbeat_WithDaemonToken_CrossWorkspace(t *testing.T) {
w = testutil.Call(t, testHandler.DaemonHeartbeat, req).Want(http.StatusNotFound)
}
-// TestHandleDaemonWSHeartbeat_RuntimeGoneReturnsAckNotError pins the fix for
-// issue #2391: when GetAgentRuntime returns pgx.ErrNoRows (runtime row was
-// deleted server-side), the WS handler must return a successful ack with
-// RuntimeGone=true rather than an error. Returning an error makes the WS hub
-// log every beat at Warn — the flood the issue is about.
+// TestHandleDaemonWSHeartbeat_RuntimeGoneReturnsAckNotError pins the receipt
+// fallback for a deletion that missed active invalidation. The connection
+// lease schedules an ID-only write, whose missing row becomes RuntimeGone
+// instead of a handler error.
func TestHandleDaemonWSHeartbeat_RuntimeGoneReturnsAckNotError(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
- // A well-formed UUID that does NOT exist in agent_runtime. The handler
- // must turn the resulting pgx.ErrNoRows into a RuntimeGone ack.
+ // A well-formed UUID that does NOT exist in agent_runtime.
missingRuntime := uuid.New().String()
ack, err := testHandler.HandleDaemonWSHeartbeat(context.Background(),
- daemonws.ClientIdentity{WorkspaceID: testWorkspaceID},
+ daemonws.ClientIdentity{
+ WorkspaceID: testWorkspaceID,
+ RuntimeLeases: map[string]*daemonws.RuntimeLease{
+ missingRuntime: daemonws.NewRuntimeLease(testWorkspaceID, "online", time.Now().Add(-2*runtimeHeartbeatDBFlushInterval), true),
+ },
+ },
missingRuntime, false)
if err != nil {
t.Fatalf("HandleDaemonWSHeartbeat: unexpected error %v", err)
@@ -943,7 +946,12 @@ func TestHandleDaemonWSHeartbeat_AllowsAnyAuthorizedWorkspace(t *testing.T) {
})
ack, err := testHandler.HandleDaemonWSHeartbeat(ctx,
- daemonws.ClientIdentity{WorkspaceIDs: []string{testWorkspaceID, workspaceID}},
+ daemonws.ClientIdentity{
+ WorkspaceIDs: []string{testWorkspaceID, workspaceID},
+ RuntimeLeases: map[string]*daemonws.RuntimeLease{
+ runtimeID: daemonws.NewRuntimeLease(workspaceID, "online", time.Now(), true),
+ },
+ },
runtimeID, false)
if err != nil {
t.Fatalf("HandleDaemonWSHeartbeat: unexpected error %v", err)
diff --git a/server/internal/handler/daemon_ws.go b/server/internal/handler/daemon_ws.go
index 89d78f5f31..1ad1c1b45e 100644
--- a/server/internal/handler/daemon_ws.go
+++ b/server/internal/handler/daemon_ws.go
@@ -1,6 +1,7 @@
package handler
import (
+ "log/slog"
"net/http"
"strings"
@@ -21,40 +22,83 @@ func (h *Handler) DaemonWebSocket(w http.ResponseWriter, r *http.Request) {
return
}
+ identity, ok := h.buildDaemonWebSocketIdentity(w, r, runtimeIDs, userID)
+ if !ok {
+ return
+ }
+ h.DaemonHub.HandleWebSocket(w, r, identity)
+}
+
+// buildDaemonWebSocketIdentity authenticates the connection's entire runtime
+// set with one narrow query and seeds the connection-scoped heartbeat leases.
+// Runtime ownership is immutable, so the heartbeat hot path can safely use
+// this fixed scope without re-reading agent_runtime every 15 seconds.
+func (h *Handler) buildDaemonWebSocketIdentity(w http.ResponseWriter, r *http.Request, runtimeIDs []string, userID string) (daemonws.ClientIdentity, bool) {
+ identity := daemonws.ClientIdentity{
+ DaemonID: middleware.DaemonIDFromContext(r.Context()),
+ UserID: userID,
+ RuntimeIDs: runtimeIDs,
+ RuntimeLeases: make(map[string]*daemonws.RuntimeLease, len(runtimeIDs)),
+ ClientVersion: r.Header.Get("X-Client-Version"),
+ Capabilities: r.Header.Get("X-Client-Capabilities"),
+ }
+ if len(runtimeIDs) == 0 {
+ return identity, true
+ }
+
+ runtimeUUIDs, ok := parseUUIDSliceOrBadRequest(w, runtimeIDs, "runtime_ids")
+ if !ok {
+ return daemonws.ClientIdentity{}, false
+ }
+ rows, err := h.Queries.GetAgentRuntimeHeartbeatLeases(r.Context(), runtimeUUIDs)
+ if err != nil {
+ slog.Warn("load daemon websocket runtime leases failed", "runtimes", len(runtimeIDs), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to load runtimes")
+ return daemonws.ClientIdentity{}, false
+ }
+ byID := make(map[string]int, len(rows))
+ for index, row := range rows {
+ byID[uuidToString(row.ID)] = index
+ }
+
workspaceIDs := make([]string, 0, len(runtimeIDs))
seenWorkspaceIDs := make(map[string]struct{}, len(runtimeIDs))
- for _, runtimeID := range runtimeIDs {
- rt, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID)
- if !ok {
- return
+ for runtimeIndex, runtimeID := range runtimeIDs {
+ index, found := byID[uuidToString(runtimeUUIDs[runtimeIndex])]
+ if !found {
+ writeError(w, http.StatusNotFound, "runtime not found")
+ return daemonws.ClientIdentity{}, false
}
- if daemonID := middleware.DaemonIDFromContext(r.Context()); daemonID != "" && rt.DaemonID.Valid && rt.DaemonID.String != daemonID {
+ rt := rows[index]
+ if identity.DaemonID != "" && rt.DaemonID.Valid && rt.DaemonID.String != identity.DaemonID {
writeError(w, http.StatusNotFound, "runtime not found")
- return
+ return daemonws.ClientIdentity{}, false
}
workspaceID := uuidToString(rt.WorkspaceID)
+ if !h.requireDaemonWorkspaceAccess(w, r, workspaceID) {
+ return daemonws.ClientIdentity{}, false
+ }
if workspaceID != "" {
if _, ok := seenWorkspaceIDs[workspaceID]; !ok {
seenWorkspaceIDs[workspaceID] = struct{}{}
workspaceIDs = append(workspaceIDs, workspaceID)
}
}
+ identity.RuntimeLeases[runtimeID] = daemonws.NewRuntimeLease(
+ workspaceID,
+ rt.Status,
+ rt.LastSeenAt.Time,
+ rt.LastSeenAt.Valid,
+ )
}
primaryWorkspaceID := ""
if len(workspaceIDs) > 0 {
primaryWorkspaceID = workspaceIDs[0]
}
-
- h.DaemonHub.HandleWebSocket(w, r, daemonws.ClientIdentity{
- DaemonID: middleware.DaemonIDFromContext(r.Context()),
- UserID: userID,
- WorkspaceID: primaryWorkspaceID,
- WorkspaceIDs: workspaceIDs,
- RuntimeIDs: runtimeIDs,
- ClientVersion: r.Header.Get("X-Client-Version"),
- Capabilities: r.Header.Get("X-Client-Capabilities"),
- })
+ identity.WorkspaceID = primaryWorkspaceID
+ identity.WorkspaceIDs = workspaceIDs
+ return identity, true
}
func parseRuntimeIDs(r *http.Request) []string {
diff --git a/server/internal/handler/daemon_ws_test.go b/server/internal/handler/daemon_ws_test.go
new file mode 100644
index 0000000000..80132494a4
--- /dev/null
+++ b/server/internal/handler/daemon_ws_test.go
@@ -0,0 +1,123 @@
+package handler
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestBuildDaemonWebSocketIdentitySeedsBatchRuntimeLeases(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ const daemonID = "lease-daemon"
+ runtimeIDs := []string{
+ dbfx.Runtime(t, "WS lease runtime 1", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "daemon_id": daemonID,
+ "provider": "ws-lease-1",
+ "device_info": "WS lease runtime 1",
+ }),
+ dbfx.Runtime(t, "WS lease runtime 2", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "daemon_id": daemonID,
+ "provider": "ws-lease-2",
+ "device_info": "WS lease runtime 2",
+ }),
+ }
+ req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/ws", nil, testWorkspaceID, daemonID)
+ req.Header.Set("X-Client-Version", "0.9.0")
+ w := httptest.NewRecorder()
+
+ identity, ok := testHandler.buildDaemonWebSocketIdentity(w, req, runtimeIDs, "")
+ if !ok {
+ t.Fatalf("buildDaemonWebSocketIdentity rejected valid runtimes: %d %s", w.Code, w.Body.String())
+ }
+ if identity.DaemonID != daemonID || identity.WorkspaceID != testWorkspaceID {
+ t.Fatalf("identity scope = daemon %q workspace %q", identity.DaemonID, identity.WorkspaceID)
+ }
+ if identity.ClientVersion != "0.9.0" {
+ t.Fatalf("client version = %q, want 0.9.0", identity.ClientVersion)
+ }
+ if len(identity.RuntimeLeases) != len(runtimeIDs) {
+ t.Fatalf("runtime leases = %d, want %d", len(identity.RuntimeLeases), len(runtimeIDs))
+ }
+ for _, runtimeID := range runtimeIDs {
+ lease := identity.RuntimeLeases[runtimeID]
+ if lease == nil {
+ t.Fatalf("missing lease for runtime %s", runtimeID)
+ }
+ state := lease.Snapshot()
+ if state.WorkspaceID != testWorkspaceID || state.Status != "online" || !state.LastSeenAtValid {
+ t.Fatalf("lease %s = %+v", runtimeID, state)
+ }
+ if time.Since(state.LastSeenAt) > time.Minute {
+ t.Fatalf("lease %s last_seen_at unexpectedly stale: %s", runtimeID, state.LastSeenAt)
+ }
+ }
+}
+
+func TestBuildDaemonWebSocketIdentityFailsClosedForMissingRuntime(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/ws", nil, testWorkspaceID, "lease-daemon")
+ w := httptest.NewRecorder()
+
+ if _, ok := testHandler.buildDaemonWebSocketIdentity(w, req, []string{uuid.NewString()}, ""); ok {
+ t.Fatal("missing runtime unexpectedly authorized")
+ }
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestBuildDaemonWebSocketIdentityRejectsWrongDaemon(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := dbfx.Runtime(t, "WS lease daemon scope", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "daemon_id": "owner-daemon",
+ "device_info": "WS lease daemon scope",
+ })
+ req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/ws", nil, testWorkspaceID, "other-daemon")
+ w := httptest.NewRecorder()
+
+ if _, ok := testHandler.buildDaemonWebSocketIdentity(w, req, []string{runtimeID}, ""); ok {
+ t.Fatal("runtime owned by another daemon unexpectedly authorized")
+ }
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestBuildDaemonWebSocketIdentityRejectsCrossWorkspaceRuntime(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ workspaceID := dbfx.Insert(t, "workspace", testutil.Cols{
+ "name": "WS Lease Other Workspace",
+ "slug": "ws-lease-" + uuid.NewString(),
+ "description": "Cross-workspace lease test",
+ "issue_prefix": "HWL",
+ })
+ runtimeID := dbfx.Runtime(t, "WS lease cross workspace", testutil.Cols{
+ "workspace_id": workspaceID,
+ "daemon_id": "lease-daemon",
+ "device_info": "WS lease cross workspace",
+ })
+ req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/ws", nil, testWorkspaceID, "lease-daemon")
+ w := httptest.NewRecorder()
+
+ if _, ok := testHandler.buildDaemonWebSocketIdentity(w, req, []string{runtimeID}, ""); ok {
+ t.Fatal("cross-workspace runtime unexpectedly authorized")
+ }
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404: %s", w.Code, w.Body.String())
+ }
+}
diff --git a/server/internal/handler/heartbeat_scheduler.go b/server/internal/handler/heartbeat_scheduler.go
index a2d1cab643..3e46a46baa 100644
--- a/server/internal/handler/heartbeat_scheduler.go
+++ b/server/internal/handler/heartbeat_scheduler.go
@@ -2,11 +2,14 @@ package handler
import (
"context"
+ "errors"
"log/slog"
"sync"
"time"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -15,32 +18,26 @@ import (
//
// Two implementations exist:
//
-// - PassthroughHeartbeatScheduler runs the legacy synchronous TouchAgentRuntimeLastSeen
+// - PassthroughHeartbeatScheduler runs the 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.
+// observe the bump immediately.
//
// - 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.
+// beating every 15s costs ~1 DB transaction per tick instead of N. IDs
+// omitted by UPDATE ... RETURNING are reconciled after each flush: rows
+// raced offline are restored, while deleted rows invalidate their connection.
+// 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
+ // window check has decided a DB write is warranted. Runtime ownership and
+ // status live in the connection lease, so only the ID enters this layer.
+ Schedule(ctx context.Context, runtimeID pgtype.UUID) 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).
+// PassthroughHeartbeatScheduler is the synchronous scheduler used as the
+// default in handler.New so tests observe DB writes immediately.
type PassthroughHeartbeatScheduler struct {
queries *db.Queries
}
@@ -49,19 +46,17 @@ func NewPassthroughHeartbeatScheduler(queries *db.Queries) *PassthroughHeartbeat
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.
+func (p *PassthroughHeartbeatScheduler) Schedule(ctx context.Context, runtimeID pgtype.UUID) error {
+ rows, err := p.queries.TouchAgentRuntimeLastSeen(ctx, runtimeID)
+ if err != nil {
+ return err
+ }
+ if rows > 0 {
+ return nil
}
- _, err := p.queries.MarkAgentRuntimeOnline(ctx, rt.ID)
+ // The row either raced offline or was deleted. MarkAgentRuntimeOnline
+ // restores the former and preserves pgx.ErrNoRows for the latter.
+ _, err = p.queries.MarkAgentRuntimeOnline(ctx, runtimeID)
return err
}
@@ -77,12 +72,12 @@ func (p *PassthroughHeartbeatScheduler) Schedule(ctx context.Context, rt db.Agen
//
// 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.
+// Failed flushes are re-queued because the connection lease has already
+// advanced its local flush watermark; the map remains fleet-bounded during a
+// persistent outage and retries once per tick.
type BatchedHeartbeatScheduler struct {
queries *db.Queries
- fallback *PassthroughHeartbeatScheduler
+ runtimeGone RuntimeGoneNotifier
tickInterval time.Duration
mu sync.Mutex
@@ -96,17 +91,24 @@ type BatchedHeartbeatScheduler 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.
+// holds with a comfortable buffer (60 + 15 + 30 = 105 < 150). One failed
+// flush retry adds another tick (135 < 150); additional failures keep the ID
+// fleet-bounded in pending until DB writes recover. Lengthening either interval
+// requires bumping RuntimeClaimFreshnessSeconds in lockstep.
const DefaultHeartbeatBatchInterval = 30 * time.Second
-func NewBatchedHeartbeatScheduler(queries *db.Queries, tickInterval time.Duration) *BatchedHeartbeatScheduler {
+// Only a row old enough for the sweeper to demote can be restored from a batch
+// receipt. A freshly-offline row was explicitly deregistered and must remain
+// offline even if an older heartbeat was already pending.
+const heartbeatReceiptRecoveryThreshold = time.Duration(service.RuntimeClaimFreshnessSeconds) * time.Second
+
+func NewBatchedHeartbeatScheduler(queries *db.Queries, tickInterval time.Duration, runtimeGone RuntimeGoneNotifier) *BatchedHeartbeatScheduler {
if tickInterval <= 0 {
tickInterval = DefaultHeartbeatBatchInterval
}
return &BatchedHeartbeatScheduler{
queries: queries,
- fallback: NewPassthroughHeartbeatScheduler(queries),
+ runtimeGone: runtimeGone,
tickInterval: tickInterval,
pending: make(map[pgtype.UUID]struct{}),
stopCh: make(chan struct{}),
@@ -114,15 +116,9 @@ func NewBatchedHeartbeatScheduler(queries *db.Queries, tickInterval time.Duratio
}
}
-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)
- }
+func (b *BatchedHeartbeatScheduler) Schedule(_ context.Context, runtimeID pgtype.UUID) error {
b.mu.Lock()
- b.pending[rt.ID] = struct{}{}
+ b.pending[runtimeID] = struct{}{}
b.mu.Unlock()
return nil
}
@@ -198,19 +194,95 @@ func (b *BatchedHeartbeatScheduler) flushOnce(ctx context.Context) {
b.pending = make(map[pgtype.UUID]struct{})
b.mu.Unlock()
- rows, err := b.queries.TouchAgentRuntimesLastSeenBatch(ctx, ids)
+ touched, err := b.queries.TouchAgentRuntimesLastSeenBatch(ctx, ids)
if err != nil {
- // Don't requeue on persistent errors — see type comment.
+ // The connection lease advances its flush watermark when Schedule
+ // accepts the ID, so retain failed IDs here instead of waiting another
+ // full lease interval before retrying.
+ b.requeue(ids)
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)
+ if len(touched) == len(ids) {
+ return
+ }
+
+ touchedSet := make(map[pgtype.UUID]struct{}, len(touched))
+ for _, id := range touched {
+ touchedSet[id] = struct{}{}
+ }
+ omitted := make([]pgtype.UUID, 0, len(ids)-len(touched))
+ for _, id := range ids {
+ if _, ok := touchedSet[id]; !ok {
+ omitted = append(omitted, id)
+ }
+ }
+
+ states, err := b.queries.GetAgentRuntimeHeartbeatLeases(ctx, omitted)
+ if err != nil {
+ b.requeue(omitted)
+ slog.Warn("heartbeat batch reconciliation query failed",
+ "omitted", len(omitted), "error", err)
+ return
+ }
+ existing := make(map[pgtype.UUID]struct{}, len(states))
+ recovered := 0
+ preservedOffline := 0
+ missing := 0
+ now := time.Now()
+ for _, state := range states {
+ existing[state.ID] = struct{}{}
+ if state.Status != "offline" || !state.LastSeenAt.Valid || now.Sub(state.LastSeenAt.Time) < heartbeatReceiptRecoveryThreshold {
+ // The omission was not a stale-sweeper race. In particular, preserve
+ // recent explicit deregistration and its offline_reason metadata.
+ preservedOffline++
+ continue
+ }
+ if _, err := b.queries.MarkAgentRuntimeOnline(ctx, state.ID); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ missing++
+ b.notifyRuntimeGone(state.ID)
+ continue
+ }
+ b.requeue([]pgtype.UUID{state.ID})
+ slog.Warn("heartbeat batch offline recovery failed",
+ "runtime_id", uuidToString(state.ID), "error", err)
+ continue
+ }
+ recovered++
+ }
+
+ for _, id := range omitted {
+ if _, ok := existing[id]; ok {
+ continue
+ }
+ missing++
+ b.notifyRuntimeGone(id)
+ }
+ slog.Info("heartbeat batch flush reconciled omitted runtimes",
+ "scheduled", len(ids),
+ "touched", len(touched),
+ "recovered", recovered,
+ "preserved_offline", preservedOffline,
+ "missing", missing,
+ )
+}
+
+func (b *BatchedHeartbeatScheduler) requeue(ids []pgtype.UUID) {
+ // A runtime can disconnect while its ID waits here, so a recovered DB may
+ // receive one final delayed last_seen_at refresh. That delay is bounded by
+ // one retry tick after recovery; keeping the ID is required because the
+ // connection lease already advanced its local flush watermark.
+ b.mu.Lock()
+ for _, id := range ids {
+ b.pending[id] = struct{}{}
+ }
+ b.mu.Unlock()
+}
+
+func (b *BatchedHeartbeatScheduler) notifyRuntimeGone(id pgtype.UUID) {
+ if b.runtimeGone != nil {
+ b.runtimeGone.NotifyRuntimeGone(uuidToString(id))
}
}
diff --git a/server/internal/handler/heartbeat_scheduler_test.go b/server/internal/handler/heartbeat_scheduler_test.go
index d5af197079..8019dd3444 100644
--- a/server/internal/handler/heartbeat_scheduler_test.go
+++ b/server/internal/handler/heartbeat_scheduler_test.go
@@ -7,9 +7,11 @@ import (
"time"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-// TestBatchedHeartbeatScheduler_CoalescesAndFlushes confirms the core P1 win:
+// TestBatchedHeartbeatScheduler_CoalescesAndFlushes confirms the batching 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) {
@@ -24,7 +26,7 @@ func TestBatchedHeartbeatScheduler_CoalescesAndFlushes(t *testing.T) {
setRuntimeLastSeenAt(t, runtimeID, stale)
rt := loadRuntime(t, runtimeID)
- sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0)
+ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0, nil)
// Hammer Schedule with the same id from many goroutines.
const callers = 50
@@ -33,7 +35,7 @@ func TestBatchedHeartbeatScheduler_CoalescesAndFlushes(t *testing.T) {
for i := 0; i < callers; i++ {
go func() {
defer wg.Done()
- if err := sched.Schedule(context.Background(), rt); err != nil {
+ if err := sched.Schedule(context.Background(), rt.ID); err != nil {
t.Errorf("Schedule: %v", err)
}
}()
@@ -65,32 +67,47 @@ func TestBatchedHeartbeatScheduler_CoalescesAndFlushes(t *testing.T) {
}
}
-// 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) {
+// TestBatchedHeartbeatScheduler_ExplicitDeregisterReceiptStaysOffline confirms
+// that a heartbeat queued before a user-visible deregistration cannot undo the
+// offline state or leave an online row with stale offline_reason metadata.
+func TestBatchedHeartbeatScheduler_ExplicitDeregisterReceiptStaysOffline(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, nil)
+ if err := sched.Schedule(context.Background(), rt.ID); err != nil {
+ t.Fatalf("Schedule: %v", err)
+ }
+ reason := []byte(`{"code":"provider_removed"}`)
+ if err := testHandler.Queries.SetAgentRuntimeOfflineWithReason(context.Background(), db.SetAgentRuntimeOfflineWithReasonParams{
+ ID: rt.ID,
+ OfflineReason: reason,
+ }); err != nil {
+ t.Fatalf("SetAgentRuntimeOfflineWithReason: %v", err)
}
- sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0)
- if err := sched.Schedule(context.Background(), rt); err != nil {
- t.Fatalf("Schedule: %v", err)
+ if got := sched.PendingCount(); got != 1 {
+ t.Fatalf("pre-deregister heartbeat should remain queued, pending=%d", got)
}
+ sched.FlushNow(context.Background())
- if got := sched.PendingCount(); got != 0 {
- t.Fatalf("offline row should not have been queued, pending=%d", got)
+ var status string
+ var reasonPreserved bool
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT status, metadata->'offline_reason' = $2::jsonb
+ FROM agent_runtime
+ WHERE id = $1
+ `, runtimeID, reason).Scan(&status, &reasonPreserved); err != nil {
+ t.Fatalf("read runtime after flush: %v", err)
}
- status, _, _ := readRuntimeRow(t, runtimeID)
- if status != "online" {
- t.Fatalf("expected status=online after sync flip, got %q", status)
+ if status != "offline" || !reasonPreserved {
+ t.Fatalf("explicit deregistration changed after receipt: status=%q reason_preserved=%t", status, reasonPreserved)
+ }
+ if got := sched.PendingCount(); got != 0 {
+ t.Fatalf("preserved offline runtime remained pending: %d", got)
}
}
@@ -108,13 +125,13 @@ func TestBatchedHeartbeatScheduler_StopDrains(t *testing.T) {
// Long tick so the natural ticker can't fire during the test — only
// the Stop drain can flush.
- sched := NewBatchedHeartbeatScheduler(testHandler.Queries, time.Hour)
+ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, time.Hour, nil)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sched.Run(ctx)
- if err := sched.Schedule(context.Background(), rt); err != nil {
+ if err := sched.Schedule(context.Background(), rt.ID); err != nil {
t.Fatalf("Schedule: %v", err)
}
if got := sched.PendingCount(); got != 1 {
@@ -147,7 +164,7 @@ func TestBatchedHeartbeatScheduler_StopFlushesLateSchedule(t *testing.T) {
setRuntimeLastSeenAt(t, runtimeID, stale)
rt := loadRuntime(t, runtimeID)
- sched := NewBatchedHeartbeatScheduler(testHandler.Queries, time.Hour)
+ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, time.Hour, nil)
runCtx, runCancel := context.WithCancel(context.Background())
go sched.Run(runCtx)
@@ -162,7 +179,7 @@ func TestBatchedHeartbeatScheduler_StopFlushesLateSchedule(t *testing.T) {
// 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 {
+ if err := sched.Schedule(context.Background(), rt.ID); err != nil {
t.Fatalf("Schedule: %v", err)
}
if got := sched.PendingCount(); got != 1 {
@@ -186,7 +203,7 @@ func TestBatchedHeartbeatScheduler_FlushIgnoresEmpty(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
- sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0)
+ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0, nil)
// Just calling FlushNow with nothing queued should not panic or error.
sched.FlushNow(context.Background())
if got := sched.PendingCount(); got != 0 {
@@ -194,43 +211,67 @@ func TestBatchedHeartbeatScheduler_FlushIgnoresEmpty(t *testing.T) {
}
}
-// 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.
+// TestBatchedHeartbeatScheduler_RaceToOfflineSelfHeals confirms that if the
+// sweeper flips a row offline between Schedule and FlushNow, receipt
+// reconciliation restores it without a new heartbeat lookup.
func TestBatchedHeartbeatScheduler_RaceToOfflineSelfHeals(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
+ setRuntimeLastSeenAt(t, runtimeID, time.Now().Add(-2*heartbeatReceiptRecoveryThreshold))
rt := loadRuntime(t, runtimeID)
- sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0)
- if err := sched.Schedule(context.Background(), rt); err != nil {
+ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0, nil)
+ if err := sched.Schedule(context.Background(), rt.ID); err != nil {
t.Fatalf("Schedule: %v", err)
}
- // Sweeper races us to offline before the flush.
- setRuntimeStatus(t, runtimeID, "offline")
+ // The real sweeper query races us to offline before the flush. Its stale
+ // predicate is the fact receipt reconciliation is allowed to rely on.
+ rows, err := testHandler.Queries.MarkRuntimesOfflineByIDs(context.Background(), db.MarkRuntimesOfflineByIDsParams{
+ Ids: []pgtype.UUID{rt.ID},
+ StaleSeconds: service.RuntimeClaimFreshnessSeconds,
+ })
+ if err != nil {
+ t.Fatalf("MarkRuntimesOfflineByIDs: %v", err)
+ }
+ if len(rows) != 1 {
+ t.Fatalf("sweeper rows = %d, want 1", len(rows))
+ }
sched.FlushNow(context.Background())
- // Bulk UPDATE's status='online' predicate means the row stays offline.
+ // The bulk UPDATE omits the offline row, and receipt reconciliation flips
+ // it back online without waiting for another heartbeat.
status, _, _ := readRuntimeRow(t, runtimeID)
- if status != "offline" {
- t.Fatalf("expected status=offline after raced flush, got %q", status)
+ if status != "online" {
+ t.Fatalf("expected receipt reconciliation to recover online, 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)
+func TestBatchedHeartbeatScheduler_DeletedReceiptInvalidatesRuntime(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
+ rt := loadRuntime(t, runtimeID)
+ notifier := &recordingRuntimeGoneNotifier{}
+ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0, notifier)
+ if err := sched.Schedule(context.Background(), rt.ID); err != nil {
+ t.Fatalf("Schedule: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("delete runtime before flush: %v", err)
}
- status2, _, _ := readRuntimeRow(t, runtimeID)
- if status2 != "online" {
- t.Fatalf("expected sync recovery to flip back to online, got %q", status2)
+
+ sched.FlushNow(context.Background())
+
+ if len(notifier.runtimeIDs) != 1 || notifier.runtimeIDs[0] != runtimeID {
+ t.Fatalf("runtime-gone notifications = %v, want [%s]", notifier.runtimeIDs, runtimeID)
+ }
+ if got := sched.PendingCount(); got != 0 {
+ t.Fatalf("deleted runtime remained pending after reconciliation: %d", got)
}
}
@@ -249,7 +290,7 @@ func TestPassthroughHeartbeatScheduler_TouchAndRaceRecovery(t *testing.T) {
sched := NewPassthroughHeartbeatScheduler(testHandler.Queries)
- if err := sched.Schedule(context.Background(), rt); err != nil {
+ if err := sched.Schedule(context.Background(), rt.ID); err != nil {
t.Fatalf("Schedule: %v", err)
}
_, lastSeen, _ := readRuntimeRow(t, runtimeID)
@@ -260,7 +301,7 @@ func TestPassthroughHeartbeatScheduler_TouchAndRaceRecovery(t *testing.T) {
// 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 {
+ if err := sched.Schedule(context.Background(), rt2.ID); err != nil {
t.Fatalf("Schedule under race: %v", err)
}
status, _, _ := readRuntimeRow(t, runtimeID)
diff --git a/server/internal/handler/heartbeat_test.go b/server/internal/handler/heartbeat_test.go
index f9d4575592..18413a7cc9 100644
--- a/server/internal/handler/heartbeat_test.go
+++ b/server/internal/handler/heartbeat_test.go
@@ -7,7 +7,9 @@ import (
"testing"
"time"
+ "github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/daemonws"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -62,6 +64,16 @@ func (f *fakeLivenessStore) touchCount() int {
return len(f.touched)
}
+type recordingHeartbeatScheduler struct {
+ ids []pgtype.UUID
+ err error
+}
+
+func (s *recordingHeartbeatScheduler) Schedule(_ context.Context, id pgtype.UUID) error {
+ s.ids = append(s.ids, id)
+ return s.err
+}
+
// 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()
@@ -114,6 +126,78 @@ func pgUUID(s string) (pgtype.UUID, error) {
return u, nil
}
+func TestRecordHeartbeatLeaseThrottlesDBScheduling(t *testing.T) {
+ runtimeID := uuid.NewString()
+ fake := &fakeLivenessStore{available: true, aliveOK: true}
+ scheduler := &recordingHeartbeatScheduler{}
+ h := &Handler{LivenessStore: fake, HeartbeatScheduler: scheduler}
+ lease := daemonws.NewRuntimeLease("workspace-1", "online", time.Now().Add(-2*runtimeHeartbeatDBFlushInterval), true)
+
+ if err := h.recordHeartbeatLease(context.Background(), runtimeID, lease); err != nil {
+ t.Fatalf("first recordHeartbeatLease: %v", err)
+ }
+ if err := h.recordHeartbeatLease(context.Background(), runtimeID, lease); err != nil {
+ t.Fatalf("second recordHeartbeatLease: %v", err)
+ }
+
+ if len(scheduler.ids) != 1 {
+ t.Fatalf("scheduled DB writes = %d, want 1 within one flush window", len(scheduler.ids))
+ }
+ if fake.touchCount() != 2 {
+ t.Fatalf("Redis touches = %d, want 2", fake.touchCount())
+ }
+ state := lease.Snapshot()
+ if !state.LastSeenAtValid || time.Since(state.LastSeenAt) > time.Second {
+ t.Fatalf("lease DB watermark was not advanced: %+v", state)
+ }
+}
+
+func TestRecordHeartbeatLeaseScheduleFailureKeepsStaleWatermark(t *testing.T) {
+ runtimeID := uuid.NewString()
+ fake := &fakeLivenessStore{available: true, aliveOK: true}
+ injected := errors.New("injected schedule failure")
+ scheduler := &recordingHeartbeatScheduler{err: injected}
+ h := &Handler{LivenessStore: fake, HeartbeatScheduler: scheduler}
+ stale := time.Now().Add(-2 * runtimeHeartbeatDBFlushInterval)
+ lease := daemonws.NewRuntimeLease("workspace-1", "online", stale, true)
+
+ if err := h.recordHeartbeatLease(context.Background(), runtimeID, lease); !errors.Is(err, injected) {
+ t.Fatalf("recordHeartbeatLease error = %v, want injected failure", err)
+ }
+ if got := lease.Snapshot().LastSeenAt; !got.Equal(stale) {
+ t.Fatalf("failed schedule advanced lease watermark: got %s want %s", got, stale)
+ }
+}
+
+func TestRecordHeartbeatLeaseOfflineTransitionIsSynchronous(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
+ setRuntimeStatus(t, runtimeID, "offline")
+ fake := &fakeLivenessStore{available: true, aliveOK: true}
+ scheduler := NewBatchedHeartbeatScheduler(testHandler.Queries, time.Hour, nil)
+ h := *testHandler
+ h.LivenessStore = fake
+ h.HeartbeatScheduler = scheduler
+ lease := daemonws.NewRuntimeLease(testWorkspaceID, "offline", time.Now(), true)
+
+ if err := h.recordHeartbeatLease(context.Background(), runtimeID, lease); err != nil {
+ t.Fatalf("recordHeartbeatLease: %v", err)
+ }
+
+ status, _, _ := readRuntimeRow(t, runtimeID)
+ if status != "online" {
+ t.Fatalf("status = %q, want online before heartbeat returns", status)
+ }
+ if got := scheduler.PendingCount(); got != 0 {
+ t.Fatalf("offline transition was deferred to batch queue: pending=%d", got)
+ }
+ if state := lease.Snapshot(); state.Status != "online" || !state.LastSeenAtValid {
+ t.Fatalf("lease state was not advanced after synchronous recovery: %+v", state)
+ }
+}
+
// 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.
diff --git a/server/internal/handler/runtime_lookup_metrics_test.go b/server/internal/handler/runtime_lookup_metrics_test.go
index 40b6d744a2..3bb3a73ad9 100644
--- a/server/internal/handler/runtime_lookup_metrics_test.go
+++ b/server/internal/handler/runtime_lookup_metrics_test.go
@@ -5,6 +5,7 @@ import (
"net/http"
"net/http/httptest"
"testing"
+ "time"
"github.com/google/uuid"
dto "github.com/prometheus/client_model/go"
@@ -14,17 +15,10 @@ import (
"github.com/multica-ai/multica/server/internal/testutil"
)
-// TestAgentRuntimeLookupSourcesAreDistinct drives the three entry points the
-// investigation in MUL-6884 could not tell apart — the WebSocket heartbeat, the
-// HTTP heartbeat fallback, and a browser poll — and asserts each lands on its
-// own source.
-//
-// This is the whole point of the metric. All three issue the same statement, so
-// pg_stat_statements sums them into one row; if they also shared a Prometheus
-// label the counter would answer no question the database could not already
-// answer, and the follow-up decision (raise the heartbeat interval, or back off
-// the 500ms polls) would still be a guess.
-func TestAgentRuntimeLookupSourcesAreDistinct(t *testing.T) {
+// TestAgentRuntimeLookupWSHotPathIsZeroRead drives 1,000 heartbeats through one
+// connection lease and proves they do not increment the GetAgentRuntime metric.
+// HTTP fallback and browser polling remain attributed as before.
+func TestAgentRuntimeLookupWSHotPathIsZeroRead(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
@@ -35,17 +29,27 @@ func TestAgentRuntimeLookupSourcesAreDistinct(t *testing.T) {
"workspace_id": testWorkspaceID,
"device_info": "lookup source runtime",
})
+ fake := &fakeLivenessStore{available: true, aliveOK: true}
+ h := *testHandler
+ h.LivenessStore = fake
+ identity := daemonws.ClientIdentity{
+ WorkspaceID: testWorkspaceID,
+ RuntimeLeases: map[string]*daemonws.RuntimeLease{
+ runtimeID: daemonws.NewRuntimeLease(testWorkspaceID, "online", time.Now(), true),
+ },
+ }
before := lookupSnapshot(t, m)
- if _, err := testHandler.HandleDaemonWSHeartbeat(ctx,
- daemonws.ClientIdentity{WorkspaceID: testWorkspaceID}, runtimeID, false); err != nil {
- t.Fatalf("HandleDaemonWSHeartbeat: %v", err)
+ for i := 0; i < 1000; i++ {
+ if _, err := h.HandleDaemonWSHeartbeat(ctx, identity, runtimeID, false); err != nil {
+ t.Fatalf("HandleDaemonWSHeartbeat %d: %v", i, err)
+ }
}
httpBeat := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat",
map[string]any{"runtime_id": runtimeID}, testWorkspaceID, "lookup-source-daemon")
- testutil.Call(t, testHandler.DaemonHeartbeat, httpBeat).Want(http.StatusOK)
+ testutil.Call(t, h.DaemonHeartbeat, httpBeat).Want(http.StatusOK)
// A model poll for a runtime that no longer exists: the read-access gate
// runs the lookup before any auth check, so this exercises the poll's
@@ -58,7 +62,6 @@ func TestAgentRuntimeLookupSourcesAreDistinct(t *testing.T) {
for _, want := range []struct {
source, result string
}{
- {obsmetrics.RuntimeLookupSourceHeartbeatWS, obsmetrics.RuntimeLookupResultOK},
{obsmetrics.RuntimeLookupSourceHeartbeatHTTP, obsmetrics.RuntimeLookupResultOK},
{obsmetrics.RuntimeLookupSourceRuntimeModelPoll, obsmetrics.RuntimeLookupResultNotFound},
} {
@@ -70,6 +73,7 @@ func TestAgentRuntimeLookupSourcesAreDistinct(t *testing.T) {
// The poll must not have been billed to the heartbeat, nor the heartbeats
// to each other.
for _, key := range []string{
+ obsmetrics.RuntimeLookupSourceHeartbeatWS + "/" + obsmetrics.RuntimeLookupResultOK,
obsmetrics.RuntimeLookupSourceHeartbeatWS + "/" + obsmetrics.RuntimeLookupResultNotFound,
obsmetrics.RuntimeLookupSourceHeartbeatHTTP + "/" + obsmetrics.RuntimeLookupResultNotFound,
obsmetrics.RuntimeLookupSourceRuntimeModelPoll + "/" + obsmetrics.RuntimeLookupResultOK,
@@ -79,6 +83,9 @@ func TestAgentRuntimeLookupSourcesAreDistinct(t *testing.T) {
t.Errorf("%s delta = %v, want 0", key, got)
}
}
+ if got := fake.touchCount(); got != 1001 {
+ t.Errorf("liveness touches = %d, want 1001 (1,000 WS + 1 HTTP)", got)
+ }
}
// ---- helpers --------------------------------------------------------------
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index 744e7398aa..00ed4762c4 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -229,8 +229,9 @@ func metricLabels(metric string) []string {
// on RuntimeLookupSourceOther, which should sit at ~0 — a non-zero rate there
// means a new call site was added without classifying it.
const (
- // RuntimeLookupSourceHeartbeatWS is the daemon WebSocket heartbeat, one
- // read per runtime per HeartbeatInterval.
+ // RuntimeLookupSourceHeartbeatWS is retained as the rollout guard for the
+ // daemon WebSocket heartbeat. The connection-lease path must keep this
+ // series at zero; any increment is a regression to per-heartbeat reads.
RuntimeLookupSourceHeartbeatWS = "heartbeat_ws"
// RuntimeLookupSourceHeartbeatHTTP is the POST /api/daemon/heartbeat
// fallback used when the WebSocket ack does not arrive.
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 1203d0edf1..574dcacbdb 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -481,6 +481,50 @@ func (q *Queries) GetAgentRuntimeForWorkspace(ctx context.Context, arg GetAgentR
return i, err
}
+const getAgentRuntimeHeartbeatLeases = `-- name: GetAgentRuntimeHeartbeatLeases :many
+SELECT id, workspace_id, daemon_id, status, last_seen_at
+FROM agent_runtime
+WHERE id = ANY($1::uuid[])
+`
+
+type GetAgentRuntimeHeartbeatLeasesRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+ Status string `json:"status"`
+ LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
+}
+
+// Narrow connection-time and heartbeat-reconciliation projection. The daemon
+// WebSocket authenticates its whole runtime set in one round trip and then
+// keeps these immutable ownership fields plus liveness state in its connection
+// lease, avoiding a GetAgentRuntime call on every heartbeat.
+func (q *Queries) GetAgentRuntimeHeartbeatLeases(ctx context.Context, ids []pgtype.UUID) ([]GetAgentRuntimeHeartbeatLeasesRow, error) {
+ rows, err := q.db.Query(ctx, getAgentRuntimeHeartbeatLeases, ids)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []GetAgentRuntimeHeartbeatLeasesRow{}
+ for rows.Next() {
+ var i GetAgentRuntimeHeartbeatLeasesRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DaemonID,
+ &i.Status,
+ &i.LastSeenAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const getAgentRuntimes = `-- name: GetAgentRuntimes :many
SELECT 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, visibility, profile_id, custom_name FROM agent_runtime
WHERE id = ANY($1::uuid[])
@@ -1221,10 +1265,11 @@ func (q *Queries) TouchAgentRuntimeLastSeen(ctx context.Context, id pgtype.UUID)
return result.RowsAffected(), nil
}
-const touchAgentRuntimesLastSeenBatch = `-- name: TouchAgentRuntimesLastSeenBatch :execrows
+const touchAgentRuntimesLastSeenBatch = `-- name: TouchAgentRuntimesLastSeenBatch :many
UPDATE agent_runtime
SET last_seen_at = now()
WHERE id = ANY($1::uuid[]) AND status = 'online'
+RETURNING id
`
// Bulk variant of TouchAgentRuntimeLastSeen used by the BatchedHeartbeatScheduler:
@@ -1233,15 +1278,27 @@ WHERE id = ANY($1::uuid[]) AND status = 'online'
//
// 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)
+// NOT touch updated_at so the rows stay HOT-eligible. RETURNING is load-bearing:
+// the scheduler reconciles omitted IDs in one narrow batch query, restoring
+// sweeper-raced offline rows and invalidating connections for deleted rows.
+func (q *Queries) TouchAgentRuntimesLastSeenBatch(ctx context.Context, ids []pgtype.UUID) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, touchAgentRuntimesLastSeenBatch, ids)
if err != nil {
- return 0, err
+ return nil, err
}
- return result.RowsAffected(), nil
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
}
const unbindTasksFromRuntime = `-- name: UnbindTasksFromRuntime :execrows
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index 10fdf68093..e404d8a5b2 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -30,6 +30,15 @@ WHERE id = $1;
SELECT * FROM agent_runtime
WHERE id = ANY(@ids::uuid[]);
+-- name: GetAgentRuntimeHeartbeatLeases :many
+-- Narrow connection-time and heartbeat-reconciliation projection. The daemon
+-- WebSocket authenticates its whole runtime set in one round trip and then
+-- keeps these immutable ownership fields plus liveness state in its connection
+-- lease, avoiding a GetAgentRuntime call on every heartbeat.
+SELECT id, workspace_id, daemon_id, status, last_seen_at
+FROM agent_runtime
+WHERE id = ANY(@ids::uuid[]);
+
-- name: LockAgentRuntime :one
-- Acquires a row-level exclusive lock on the runtime row. Used at the
-- top of the cascade-delete transaction so that:
@@ -183,19 +192,20 @@ UPDATE agent_runtime
SET last_seen_at = now()
WHERE id = $1 AND status = 'online';
--- name: TouchAgentRuntimesLastSeenBatch :execrows
+-- name: TouchAgentRuntimesLastSeenBatch :many
-- 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.
+-- NOT touch updated_at so the rows stay HOT-eligible. RETURNING is load-bearing:
+-- the scheduler reconciles omitted IDs in one narrow batch query, restoring
+-- sweeper-raced offline rows and invalidating connections for deleted rows.
UPDATE agent_runtime
SET last_seen_at = now()
-WHERE id = ANY(@ids::uuid[]) AND status = 'online';
+WHERE id = ANY(@ids::uuid[]) AND status = 'online'
+RETURNING id;
-- name: MarkAgentRuntimeOnline :one
-- Used on the offline→online transition (and on first heartbeat after