Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7002: push runtime deletion invalidation to active daemons (#7969)
Multica Eve731af7ccd6c0
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 57999739be..e0abcd3d79 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -491,6 +491,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busif notifier, ok := opts.DaemonWakeup.(handler.DaemonPendingWorkNotifier); ok {h.DaemonPendingWork = notifier}+ if notifier, ok := opts.DaemonWakeup.(handler.RuntimeGoneNotifier); ok {+ h.DaemonRuntimeGone = notifier+ }}if rdb != nil {h.UpdateStore = handler.NewRedisUpdateStore(rdb)diff --git a/server/cmd/server/runtime_gc_test.go b/server/cmd/server/runtime_gc_test.goindex 94acf1446e..2300e02378 100644--- a/server/cmd/server/runtime_gc_test.go+++ b/server/cmd/server/runtime_gc_test.go@@ -362,14 +362,19 @@ func TestRuntimeGCBatch_PublishesSystemActorAndDeduplicatesWorkspaceRefresh(t *t}ctx := context.Background()workspaceID := createRuntimeGCFixtureWorkspace(t, ctx, "events")- _ = createRuntimeGCFixtureRuntimeForWorkspace(t, ctx, workspaceID, "events-a")- _ = createRuntimeGCFixtureRuntimeForWorkspace(t, ctx, workspaceID, "events-b")+ runtimeA := createRuntimeGCFixtureRuntimeForWorkspace(t, ctx, workspaceID, "events-a")+ runtimeB := createRuntimeGCFixtureRuntimeForWorkspace(t, ctx, workspaceID, "events-b")publisher := &recordingRuntimeGCPublisher{}gcRuntimesWithBudget(ctx, testPool, db.New(testPool), nil, publisher, 5*time.Second)var teardownCalls, refreshCalls int+ gone := make(map[string]int)for _, call := range publisher.calls {+ if call.kind == "runtime_gone" {+ gone[call.runtimeID]+++ continue+ }if call.workspaceID != workspaceID {continue}@@ -391,6 +396,9 @@ func TestRuntimeGCBatch_PublishesSystemActorAndDeduplicatesWorkspaceRefresh(t *tif teardownCalls != 2 || refreshCalls != 1 {t.Fatalf("workspace GC events: teardown=%d refresh=%d, want 2 and 1", teardownCalls, refreshCalls)}+ if gone[runtimeA] != 1 || gone[runtimeB] != 1 {+ t.Fatalf("runtime-gone notifications = %v, want one each for %s and %s", gone, runtimeA, runtimeB)+ }}func TestRuntimeGC_RollsBackDetachedHistoryWhenDeleteFails(t *testing.T) {@@ -530,6 +538,7 @@ type runtimeGCPublishCall struct {action stringpublishRuntimeRefresh boolcancelledTasks int+ runtimeID string}type recordingRuntimeGCPublisher struct {@@ -558,6 +567,13 @@ func (p *recordingRuntimeGCPublisher) PublishRuntimeRefresh(workspaceID, actorTy})}+func (p *recordingRuntimeGCPublisher) NotifyRuntimeGone(runtimeID string) {+ p.calls = append(p.calls, runtimeGCPublishCall{+ kind: "runtime_gone",+ runtimeID: runtimeID,+ })+}+func (s *blockingRuntimeGCTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {s.begins.Add(1)<-ctx.Done()diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.goindex 550b88688f..7b84c508a2 100644--- a/server/cmd/server/runtime_sweeper.go+++ b/server/cmd/server/runtime_sweeper.go@@ -110,6 +110,7 @@ type runtimeGCTxStarter interface {type runtimeGCEventPublisher interface {PublishRuntimeTeardown(context.Context, service.RuntimeTeardownResult, string, string, string, string, bool)PublishRuntimeRefresh(string, string, string, string)+ NotifyRuntimeGone(string)}type runtimeSweepStageStats struct {@@ -453,6 +454,7 @@ func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, quemetrics.RecordRuntimeGCDeleted()gcWorkspaces[result.workspaceID] = trueif publisher != nil {+ publisher.NotifyRuntimeGone(util.UUIDToString(runtimeID))publisher.PublishRuntimeTeardown(gcCtx, result.teardown, result.workspaceID, "system", "", "runtime_gc", false)}}diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.goindex 3e717b7224..6e36c4d3ee 100644--- a/server/internal/daemonws/hub.go+++ b/server/internal/daemonws/hub.go@@ -336,6 +336,13 @@ func (h *Hub) NotifyPendingWork(runtimeID, kind string) {h.notifyPendingWork(runtimeID, kind, "")}+// 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.+func (h *Hub) NotifyRuntimeGone(runtimeID string) {+ h.notifyRuntimeGone(runtimeID, "")+}+func (h *Hub) notifyTaskAvailable(runtimeID, taskID, eventID string) {if h == nil || runtimeID == "" {return@@ -390,17 +397,38 @@ func (h *Hub) notifyPendingWork(runtimeID, kind, eventID string) {}}+func (h *Hub) notifyRuntimeGone(runtimeID, eventID string) {+ if h == nil || runtimeID == "" {+ return+ }+ data, err := runtimeGoneFrame(runtimeID)+ if err != nil {+ return+ }+ delivered, deduped := h.notifyFrame(runtimeID, data, eventID)+ if delivered {+ M.RuntimeGoneDeliveredHit.Add(1)+ } else if !deduped {+ M.RuntimeGoneDeliveredMiss.Add(1)+ }+}+func (h *Hub) DeliverDaemonRuntime(scopeID string, frame []byte, eventID string) {if h == nil {return}- M.WakeupReceivedTotal.Add(1)var msg protocol.Messageif err := json.Unmarshal(frame, &msg); err != nil {+ M.WakeupReceivedTotal.Add(1)slog.Debug("daemon websocket relay: invalid frame", "error", err, "scope_id", scopeID, "event_id", eventID)M.WakeupDeliveredMiss.Add(1)return}+ if msg.Type == protocol.EventDaemonHeartbeatAck {+ M.RuntimeGoneReceivedTotal.Add(1)+ } else {+ M.WakeupReceivedTotal.Add(1)+ }switch msg.Type {case protocol.EventDaemonTaskAvailable:var payload protocol.TaskAvailablePayload@@ -448,6 +476,19 @@ func (h *Hub) DeliverDaemonRuntime(scopeID string, frame []byte, eventID string)} else if !deduped {M.WakeupDeliveredMiss.Add(1)}+ case protocol.EventDaemonHeartbeatAck:+ var payload protocol.DaemonHeartbeatAckPayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil || payload.RuntimeID == "" || payload.Status != protocol.HeartbeatStatusRuntimeGone || !payload.RuntimeGone {+ slog.Debug("daemon websocket relay: invalid runtime_gone payload", "error", err, "scope_id", scopeID, "event_id", eventID)+ M.RuntimeGoneDeliveredMiss.Add(1)+ return+ }+ delivered, deduped := h.notifyFrame(payload.RuntimeID, frame, eventID)+ if delivered {+ M.RuntimeGoneDeliveredHit.Add(1)+ } else if !deduped {+ M.RuntimeGoneDeliveredMiss.Add(1)+ }default:M.WakeupDeliveredMiss.Add(1)return@@ -575,6 +616,17 @@ func pendingWorkFrame(runtimeID, kind string) ([]byte, error) {})}+func runtimeGoneFrame(runtimeID string) ([]byte, error) {+ return json.Marshal(protocol.Message{+ Type: protocol.EventDaemonHeartbeatAck,+ Payload: mustMarshalRaw(protocol.DaemonHeartbeatAckPayload{+ RuntimeID: runtimeID,+ Status: protocol.HeartbeatStatusRuntimeGone,+ RuntimeGone: true,+ }),+ })+}+func mustMarshalRaw(v any) json.RawMessage {data, err := json.Marshal(v)if err != nil {diff --git a/server/internal/daemonws/metrics.go b/server/internal/daemonws/metrics.goindex 63bd2ce770..fd238d32a7 100644--- a/server/internal/daemonws/metrics.go+++ b/server/internal/daemonws/metrics.go@@ -13,21 +13,32 @@ type Metrics struct {WakeupReceivedTotal atomic.Int64WakeupDeliveredHit atomic.Int64WakeupDeliveredMiss atomic.Int64++ RuntimeGoneDeliveredHit atomic.Int64+ RuntimeGoneDeliveredMiss atomic.Int64+ RuntimeGonePublishedTotal atomic.Int64+ RuntimeGonePublishErrors atomic.Int64+ RuntimeGoneReceivedTotal atomic.Int64}var M = &Metrics{}func (m *Metrics) Snapshot() map[string]any {return map[string]any{- "connects_total": m.ConnectsTotal.Load(),- "disconnects_total": m.DisconnectsTotal.Load(),- "active_connections": m.ActiveConnections.Load(),- "slow_evictions_total": m.SlowEvictionsTotal.Load(),- "wakeup_published_total": m.WakeupPublishedTotal.Load(),- "wakeup_publish_errors": m.WakeupPublishErrors.Load(),- "wakeup_received_total": m.WakeupReceivedTotal.Load(),- "wakeup_delivered_hit_total": m.WakeupDeliveredHit.Load(),- "wakeup_delivered_miss_total": m.WakeupDeliveredMiss.Load(),+ "connects_total": m.ConnectsTotal.Load(),+ "disconnects_total": m.DisconnectsTotal.Load(),+ "active_connections": m.ActiveConnections.Load(),+ "slow_evictions_total": m.SlowEvictionsTotal.Load(),+ "wakeup_published_total": m.WakeupPublishedTotal.Load(),+ "wakeup_publish_errors": m.WakeupPublishErrors.Load(),+ "wakeup_received_total": m.WakeupReceivedTotal.Load(),+ "wakeup_delivered_hit_total": m.WakeupDeliveredHit.Load(),+ "wakeup_delivered_miss_total": m.WakeupDeliveredMiss.Load(),+ "runtime_gone_delivered_hit_total": m.RuntimeGoneDeliveredHit.Load(),+ "runtime_gone_delivered_miss_total": m.RuntimeGoneDeliveredMiss.Load(),+ "runtime_gone_published_total": m.RuntimeGonePublishedTotal.Load(),+ "runtime_gone_publish_errors": m.RuntimeGonePublishErrors.Load(),+ "runtime_gone_received_total": m.RuntimeGoneReceivedTotal.Load(),}}@@ -41,4 +52,9 @@ func (m *Metrics) Reset() {m.WakeupReceivedTotal.Store(0)m.WakeupDeliveredHit.Store(0)m.WakeupDeliveredMiss.Store(0)+ m.RuntimeGoneDeliveredHit.Store(0)+ m.RuntimeGoneDeliveredMiss.Store(0)+ m.RuntimeGonePublishedTotal.Store(0)+ m.RuntimeGonePublishErrors.Store(0)+ m.RuntimeGoneReceivedTotal.Store(0)}diff --git a/server/internal/daemonws/notifier.go b/server/internal/daemonws/notifier.goindex bb98e4f297..b8055195f4 100644--- a/server/internal/daemonws/notifier.go+++ b/server/internal/daemonws/notifier.go@@ -128,3 +128,29 @@ func (n *RelayNotifier) NotifyPendingWork(runtimeID, kind string) {}M.WakeupPublishedTotal.Add(1)}++// NotifyRuntimeGone invalidates a deleted runtime on the local daemon+// connection and on any connection held by another API node.+func (n *RelayNotifier) NotifyRuntimeGone(runtimeID string) {+ if runtimeID == "" {+ return+ }+ eventID := ulid.Make().String()+ if n.local != nil {+ n.local.notifyRuntimeGone(runtimeID, eventID)+ }+ if n.relay == nil {+ return+ }+ frame, err := runtimeGoneFrame(runtimeID)+ if err != nil {+ M.RuntimeGonePublishErrors.Add(1)+ return+ }+ if err := n.relay.PublishWithID(realtime.ScopeDaemonRuntime, runtimeID, "", frame, eventID); err != nil {+ M.RuntimeGonePublishErrors.Add(1)+ slog.Warn("daemon websocket runtime-gone publish failed", "error", err, "runtime_id", runtimeID)+ return+ }+ M.RuntimeGonePublishedTotal.Add(1)+}diff --git a/server/internal/daemonws/runtime_gone_test.go b/server/internal/daemonws/runtime_gone_test.gonew file mode 100644index 0000000000..760b6a0be9--- /dev/null+++ b/server/internal/daemonws/runtime_gone_test.go@@ -0,0 +1,189 @@+package daemonws++import (+ "encoding/json"+ "errors"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestNotifyRuntimeGone(t *testing.T) {+ M.Reset()+ defer M.Reset()++ hub := NewHub()+ client := attachDaemonTestClient(hub, "runtime-1")++ hub.NotifyRuntimeGone("runtime-1")++ payload := readRuntimeGoneFrame(t, client.send)+ if payload.RuntimeID != "runtime-1" {+ t.Fatalf("runtime id = %q, want runtime-1", payload.RuntimeID)+ }+ if payload.Status != protocol.HeartbeatStatusRuntimeGone || !payload.RuntimeGone {+ t.Fatalf("payload = %+v, want runtime_gone acknowledgement", payload)+ }+ if M.RuntimeGoneDeliveredHit.Load() != 1 {+ t.Fatalf("runtime-gone delivered hit metric = %d, want 1", M.RuntimeGoneDeliveredHit.Load())+ }+ if M.WakeupDeliveredHit.Load() != 0 || M.WakeupDeliveredMiss.Load() != 0 {+ t.Fatalf("runtime-gone polluted wakeup delivery metrics: hit=%d miss=%d", M.WakeupDeliveredHit.Load(), M.WakeupDeliveredMiss.Load())+ }+}++func TestNotifyRuntimeGoneMissingConnectionDoesNotPolluteWakeupMetrics(t *testing.T) {+ M.Reset()+ defer M.Reset()++ NewHub().NotifyRuntimeGone("offline-runtime")++ if M.RuntimeGoneDeliveredHit.Load() != 0 || M.RuntimeGoneDeliveredMiss.Load() != 1 {+ t.Fatalf("runtime-gone delivery metrics: hit=%d miss=%d, want 0/1", M.RuntimeGoneDeliveredHit.Load(), M.RuntimeGoneDeliveredMiss.Load())+ }+ if M.WakeupDeliveredHit.Load() != 0 || M.WakeupDeliveredMiss.Load() != 0 {+ t.Fatalf("runtime-gone polluted wakeup delivery metrics: hit=%d miss=%d", M.WakeupDeliveredHit.Load(), M.WakeupDeliveredMiss.Load())+ }+}++func TestRelayNotifierPublishesAndDeliversRuntimeGone(t *testing.T) {+ M.Reset()+ defer M.Reset()++ relay := &recordingRelayPublisher{}+ NewRelayNotifier(nil, relay).NotifyRuntimeGone("runtime-1")++ if relay.scopeType != realtime.ScopeDaemonRuntime || relay.scopeID != "runtime-1" {+ t.Fatalf("relay scope = %q/%q, want daemon-runtime/runtime-1", relay.scopeType, relay.scopeID)+ }+ if relay.eventID == "" {+ t.Fatal("expected event id")+ }+ if M.RuntimeGonePublishedTotal.Load() != 1 || M.RuntimeGonePublishErrors.Load() != 0 {+ t.Fatalf("runtime-gone publish metrics: published=%d errors=%d, want 1/0", M.RuntimeGonePublishedTotal.Load(), M.RuntimeGonePublishErrors.Load())+ }+ if M.WakeupPublishedTotal.Load() != 0 || M.WakeupPublishErrors.Load() != 0 {+ t.Fatalf("runtime-gone polluted wakeup publish metrics: published=%d errors=%d", M.WakeupPublishedTotal.Load(), M.WakeupPublishErrors.Load())+ }++ remoteHub := NewHub()+ remoteClient := attachDaemonTestClient(remoteHub, "runtime-1")+ remoteHub.DeliverDaemonRuntime(relay.scopeID, relay.frame, relay.eventID)+ payload := readRuntimeGoneFrame(t, remoteClient.send)+ if payload.RuntimeID != "runtime-1" || payload.Status != protocol.HeartbeatStatusRuntimeGone || !payload.RuntimeGone {+ t.Fatalf("payload = %+v, want relayed runtime_gone acknowledgement", payload)+ }++ remoteHub.DeliverDaemonRuntime(relay.scopeID, relay.frame, relay.eventID)+ select {+ case duplicate := <-remoteClient.send:+ t.Fatalf("expected duplicate relay event to be dropped, got %s", duplicate)+ case <-time.After(20 * time.Millisecond):+ }+ if M.RuntimeGoneDeliveredHit.Load() != 1 || M.RuntimeGoneDeliveredMiss.Load() != 0 {+ t.Fatalf("runtime-gone delivery metrics after loopback: hit=%d miss=%d, want 1/0", M.RuntimeGoneDeliveredHit.Load(), M.RuntimeGoneDeliveredMiss.Load())+ }+ if M.RuntimeGoneReceivedTotal.Load() != 2 || M.WakeupReceivedTotal.Load() != 0 {+ t.Fatalf("relay receive metrics: runtime-gone=%d wakeup=%d, want 2/0", M.RuntimeGoneReceivedTotal.Load(), M.WakeupReceivedTotal.Load())+ }+ if M.WakeupDeliveredHit.Load() != 0 || M.WakeupDeliveredMiss.Load() != 0 {+ t.Fatalf("runtime-gone polluted wakeup delivery metrics: hit=%d miss=%d", M.WakeupDeliveredHit.Load(), M.WakeupDeliveredMiss.Load())+ }+}++func TestRelayNotifierRuntimeGonePublishErrorDoesNotPolluteWakeupMetrics(t *testing.T) {+ M.Reset()+ defer M.Reset()++ NewRelayNotifier(nil, failingRelayPublisher{}).NotifyRuntimeGone("runtime-1")++ if M.RuntimeGonePublishedTotal.Load() != 0 || M.RuntimeGonePublishErrors.Load() != 1 {+ t.Fatalf("runtime-gone publish metrics: published=%d errors=%d, want 0/1", M.RuntimeGonePublishedTotal.Load(), M.RuntimeGonePublishErrors.Load())+ }+ if M.WakeupPublishedTotal.Load() != 0 || M.WakeupPublishErrors.Load() != 0 {+ t.Fatalf("runtime-gone polluted wakeup publish metrics: published=%d errors=%d", M.WakeupPublishedTotal.Load(), M.WakeupPublishErrors.Load())+ }+}++func TestDeliverDaemonRuntimeInvalidRuntimeGoneDoesNotPolluteWakeupMetrics(t *testing.T) {+ M.Reset()+ defer M.Reset()++ frame, err := json.Marshal(protocol.Message{+ Type: protocol.EventDaemonHeartbeatAck,+ Payload: mustMarshalRaw(protocol.DaemonHeartbeatAckPayload{+ RuntimeID: "runtime-1",+ Status: "invalid",+ }),+ })+ if err != nil {+ t.Fatalf("marshal invalid runtime-gone frame: %v", err)+ }+ NewHub().DeliverDaemonRuntime("runtime-1", frame, "event-1")++ if M.RuntimeGoneReceivedTotal.Load() != 1 || M.RuntimeGoneDeliveredMiss.Load() != 1 {+ t.Fatalf("invalid runtime-gone metrics: received=%d miss=%d, want 1/1", M.RuntimeGoneReceivedTotal.Load(), M.RuntimeGoneDeliveredMiss.Load())+ }+ if M.WakeupReceivedTotal.Load() != 0 || M.WakeupDeliveredMiss.Load() != 0 {+ t.Fatalf("invalid runtime-gone polluted wakeup metrics: received=%d miss=%d", M.WakeupReceivedTotal.Load(), M.WakeupDeliveredMiss.Load())+ }+}++func TestRelayNotifierDedupsRuntimeGoneLoopback(t *testing.T) {+ M.Reset()+ defer M.Reset()++ hub := NewHub()+ client := attachDaemonTestClient(hub, "runtime-1")+ relay := &localFirstDaemonRelayPublisher{t: t, client: client}+ NewRelayNotifier(hub, relay).NotifyRuntimeGone("runtime-1")++ if !relay.called || relay.eventID == "" {+ t.Fatal("expected local delivery followed by relay publish")+ }+ if payload := decodeRuntimeGoneFrame(t, relay.localFrame); !payload.RuntimeGone {+ t.Fatalf("local payload = %+v, want runtime_gone acknowledgement", payload)+ }++ hub.DeliverDaemonRuntime(relay.scopeID, relay.frame, relay.eventID)+ select {+ case duplicate := <-client.send:+ t.Fatalf("expected Redis loopback to be deduped, got %s", duplicate)+ case <-time.After(20 * time.Millisecond):+ }+}++func readRuntimeGoneFrame(t *testing.T, frames <-chan []byte) protocol.DaemonHeartbeatAckPayload {+ t.Helper()+ select {+ case raw := <-frames:+ return decodeRuntimeGoneFrame(t, raw)+ case <-time.After(time.Second):+ t.Fatal("timed out waiting for runtime_gone frame")+ return protocol.DaemonHeartbeatAckPayload{}+ }+}++func decodeRuntimeGoneFrame(t *testing.T, raw []byte) protocol.DaemonHeartbeatAckPayload {+ t.Helper()+ var msg protocol.Message+ if err := json.Unmarshal(raw, &msg); err != nil {+ t.Fatalf("unmarshal message: %v", err)+ }+ if msg.Type != protocol.EventDaemonHeartbeatAck {+ t.Fatalf("message type = %q, want %q", msg.Type, protocol.EventDaemonHeartbeatAck)+ }+ var payload protocol.DaemonHeartbeatAckPayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {+ t.Fatalf("unmarshal payload: %v", err)+ }+ return payload+}++type failingRelayPublisher struct{}++func (failingRelayPublisher) PublishWithID(string, string, string, []byte, string) error {+ return errors.New("injected relay publish failure")+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 900043096a..568fd372db 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -873,6 +873,7 @@ func (h *Handler) mergeLegacyRuntime(ctx context.Context, newRuntimeID, oldRuntiif err := tx.Commit(ctx); err != nil {return fmt.Errorf("commit merge: %w", err)}+ h.NotifyRuntimeGone(uuidToString(oldRuntimeID))slog.Info("legacy runtime merged","legacy_daemon_id", legacyID,diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 726a270814..7772cfbc47 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -173,6 +173,12 @@ type DaemonPendingWorkNotifier interface {NotifyPendingWork(runtimeID, kind string)}+// RuntimeGoneNotifier invalidates a runtime that was deleted while its daemon+// still has an authenticated WebSocket connection.+type RuntimeGoneNotifier interface {+ NotifyRuntimeGone(runtimeID string)+}+type Handler struct {Queries *db.QueriesDB dbExecutor@@ -181,6 +187,7 @@ type Handler struct {DaemonHub *daemonws.HubDaemonProfileRefresh RuntimeProfileRefreshNotifierDaemonWorkspaceRefresh WorkspaceSetRefreshNotifier+ DaemonRuntimeGone RuntimeGoneNotifierBus *events.BusTaskService *service.TaskServicePluginService *service.PluginService@@ -412,9 +419,11 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event}var daemonProfileRefresh RuntimeProfileRefreshNotifiervar daemonWorkspaceRefresh WorkspaceSetRefreshNotifier+ var daemonRuntimeGone RuntimeGoneNotifierif daemonHub != nil {daemonProfileRefresh = daemonHubdaemonWorkspaceRefresh = daemonHub+ daemonRuntimeGone = daemonHub}llmClient := llm.New(llm.Config{@@ -452,6 +461,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventDaemonHub: daemonHub,DaemonProfileRefresh: daemonProfileRefresh,DaemonWorkspaceRefresh: daemonWorkspaceRefresh,+ DaemonRuntimeGone: daemonRuntimeGone,Bus: bus,TaskService: taskSvc,PluginService: service.NewPluginService(queries, txStarter),@@ -722,6 +732,15 @@ func (h *Handler) notifyDaemonWorkspacesChanged(userIDs ...string) {}}+// NotifyRuntimeGone emits the post-commit runtime invalidation signal. It is+// exported so the runtime GC can use the same publisher as request handlers.+func (h *Handler) NotifyRuntimeGone(runtimeID string) {+ if h == nil || h.DaemonRuntimeGone == nil || runtimeID == "" {+ return+ }+ h.DaemonRuntimeGone.NotifyRuntimeGone(runtimeID)+}+// publishTask is publish() plus a TaskID hint so the realtime layer can route// the event to the per-task scope rather than the whole workspace.func (h *Handler) publishTask(eventType, workspaceID, actorType, actorID, taskID string, payload any) {diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 01e9c8efd4..8d97111bd4 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -954,6 +954,7 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to delete runtime")return}+ h.NotifyRuntimeGone(uuidToString(rt.ID))slog.Info("runtime deleted","runtime_id", uuidToString(rt.ID),@@ -1167,6 +1168,7 @@ func (h *Handler) UnbindAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.RewriteError(w, http.StatusInternalServerError, "failed to commit transaction")return}+ h.NotifyRuntimeGone(uuidToString(rt.ID))h.publishRuntimeTeardown(r.Context(), teardown, wsID, userID)diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.goindex a2226fdf75..c76ebf13d1 100644--- a/server/internal/handler/runtime_profile.go+++ b/server/internal/handler/runtime_profile.go@@ -462,10 +462,11 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {// Now the runtime rows have no agent references; remove them, then the// profile itself.- if _, err := qtx.DeleteAgentRuntimesByProfile(r.Context(), db.DeleteAgentRuntimesByProfileParams{+ deletedRuntimes, err := qtx.DeleteAgentRuntimesByProfile(r.Context(), db.DeleteAgentRuntimesByProfileParams{ProfileID: profileUUID,WorkspaceID: wsUUID,- }); err != nil {+ })+ if err != nil {slog.Error("DeleteAgentRuntimesByProfile failed", "error", err, "profile_id", uuidToString(profileUUID))writeError(w, http.StatusInternalServerError, "failed to clean up runtime instances")return@@ -484,6 +485,9 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to commit transaction")return}+ for _, runtime := range deletedRuntimes {+ h.NotifyRuntimeGone(uuidToString(runtime.ID))+ }// Tell connected clients to refetch the runtime list (instances vanished),// and fan out the per-runtime teardown so unbound agents and cancelleddiff --git a/server/internal/handler/runtime_profile_handler_test.go b/server/internal/handler/runtime_profile_handler_test.goindex 5f9bb973e4..5d00f4ffd0 100644--- a/server/internal/handler/runtime_profile_handler_test.go+++ b/server/internal/handler/runtime_profile_handler_test.go@@ -105,7 +105,10 @@ VALUES ($1, $2, 'feishu', 'oc_rp', 'p2p')`, rpChat, rpInstallID); err != nil {w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)- testHandler.DeleteRuntimeProfile(w, req)+ notifier := &recordingRuntimeGoneNotifier{}+ h := *testHandler+ h.DaemonRuntimeGone = notifier+ h.DeleteRuntimeProfile(w, req)if w.Code != http.StatusNoContent {t.Fatalf("expected 204, got %d: %s", w.Code, w.Body.String())@@ -152,6 +155,9 @@ VALUES ($1, $2, 'feishu', 'oc_rp', 'p2p')`, rpChat, rpInstallID); err != nil {if bindingRows != 1 {t.Fatalf("surviving installation's chat-session binding was swept: %d rows", bindingRows)}+ if len(notifier.runtimeIDs) != 1 || notifier.runtimeIDs[0] != runtimeID {+ t.Fatalf("runtime-gone notifications = %v, want [%s]", notifier.runtimeIDs, runtimeID)+ }}// TestDeleteRuntimeProfile_ActiveAgentBlocks confirms the guard still refuses@@ -170,7 +176,10 @@ func TestDeleteRuntimeProfile_ActiveAgentBlocks(t *testing.T) {w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)- testHandler.DeleteRuntimeProfile(w, req)+ notifier := &recordingRuntimeGoneNotifier{}+ h := *testHandler+ h.DaemonRuntimeGone = notifier+ h.DeleteRuntimeProfile(w, req)if w.Code != http.StatusConflict {t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())@@ -189,6 +198,9 @@ func TestDeleteRuntimeProfile_ActiveAgentBlocks(t *testing.T) {if rtRows != 1 {t.Fatalf("expected runtime to survive 409, found %d", rtRows)}+ if len(notifier.runtimeIDs) != 0 {+ t.Fatalf("rollback/refusal emitted runtime-gone notifications: %v", notifier.runtimeIDs)+ }}func TestDeleteRuntimeProfile_WorkspaceMismatchReturnsStructuredConflict(t *testing.T) {diff --git a/server/internal/handler/runtime_unbind_delete_test.go b/server/internal/handler/runtime_unbind_delete_test.goindex 97759b39ef..665a101c63 100644--- a/server/internal/handler/runtime_unbind_delete_test.go+++ b/server/internal/handler/runtime_unbind_delete_test.go@@ -12,6 +12,14 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")+type recordingRuntimeGoneNotifier struct {+ runtimeIDs []string+}++func (n *recordingRuntimeGoneNotifier) NotifyRuntimeGone(runtimeID string) {+ n.runtimeIDs = append(n.runtimeIDs, runtimeID)+}+// parseExpectedActiveAgentIDs is the cascade endpoint's input validator.// Empty list is a valid plan ("no active agents" — cascade just deletes the// runtime); malformed UUIDs must surface as 400 so a bug in the front-end@@ -335,7 +343,10 @@ func TestDeleteAgentRuntime_OrphanedProfileAllowsDirectDelete(t *testing.T) {w := httptest.NewRecorder()req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)req = withURLParam(req, "runtimeId", runtimeID)- testHandler.DeleteAgentRuntime(w, req)+ notifier := &recordingRuntimeGoneNotifier{}+ h := *testHandler+ h.DaemonRuntimeGone = notifier+ h.DeleteAgentRuntime(w, req)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}@@ -347,6 +358,9 @@ func TestDeleteAgentRuntime_OrphanedProfileAllowsDirectDelete(t *testing.T) {if rtRows != 0 {t.Fatalf("expected orphaned custom runtime instance to be deleted, count=%d", rtRows)}+ if len(notifier.runtimeIDs) != 1 || notifier.runtimeIDs[0] != runtimeID {+ t.Fatalf("runtime-gone notifications = %v, want [%s]", notifier.runtimeIDs, runtimeID)+ }}// TestUnbindAgentsAndDeleteRuntime_HappyPath exercises the confirmed endpoint@@ -366,7 +380,10 @@ func TestUnbindAgentsAndDeleteRuntime_HappyPath(t *testing.T) {req := newRequest("POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete",map[string]any{"expected_active_agent_ids": []string{agentID}})req = withURLParam(req, "runtimeId", runtimeID)- testHandler.UnbindAgentsAndDeleteRuntime(w, req)+ notifier := &recordingRuntimeGoneNotifier{}+ h := *testHandler+ h.DaemonRuntimeGone = notifier+ h.UnbindAgentsAndDeleteRuntime(w, req)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}@@ -421,6 +438,9 @@ func TestUnbindAgentsAndDeleteRuntime_HappyPath(t *testing.T) {if body.AgentsArchived != 1 {t.Fatalf("agents_archived mirror = %d, want 1", body.AgentsArchived)}+ if len(notifier.runtimeIDs) != 1 || notifier.runtimeIDs[0] != runtimeID {+ t.Fatalf("runtime-gone notifications = %v, want [%s]", notifier.runtimeIDs, runtimeID)+ }}func TestUnbindAgentsAndDeleteRuntime_CustomProfileInstanceRefusesDirectDelete(t *testing.T) {diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex ffbef83f0d..fc58edd48a 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -1121,6 +1121,15 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {failWorkspaceDelete(w, r, workspaceID, "lock workspace", err)return}+ // Take a best-effort snapshot for post-commit daemon invalidation. Runtime+ // registration does not participate in the workspace delete lock protocol,+ // so PR1 retains the heartbeat lookup as the correctness fallback for a+ // registration that races this snapshot.+ runtimeIDs, err := qtx.ListAgentRuntimeIDsByWorkspace(r.Context(), requester.WorkspaceID)+ if err != nil {+ failWorkspaceDelete(w, r, workspaceID, "list runtimes", err)+ return+ }if _, err := qtx.LockChatSessionsByWorkspace(r.Context(), requester.WorkspaceID); err != nil {failWorkspaceDelete(w, r, workspaceID, "lock chat sessions", err)@@ -1314,6 +1323,9 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to delete workspace")return}+ for _, runtimeID := range runtimeIDs {+ h.NotifyRuntimeGone(uuidToString(runtimeID))+ }h.deleteS3Objects(r.Context(), append(sourceContextAttachmentURLs, sourceContextIntentURLs...))slog.Info("workspace deleted", append(logger.RequestAttrs(r), "workspace_id", workspaceID)...)diff --git a/server/internal/handler/workspace_delete_fence_test.go b/server/internal/handler/workspace_delete_fence_test.goindex 362a694523..bc6388f78c 100644--- a/server/internal/handler/workspace_delete_fence_test.go+++ b/server/internal/handler/workspace_delete_fence_test.go@@ -349,12 +349,15 @@ func TestMergeLegacyRuntime_KeepsOldRuntimeWhenFenceRefuses(t *testing.T) {}ctx := context.Background()f := newWorkspaceDeletePathFixture(t, "mergefence")+ notifier := &recordingRuntimeGoneNotifier{}+ h := *testHandler+ h.DaemonRuntimeGone = notifier// A target runtime id that does not resolve — the same state a merge sees when// the target's workspace was torn down a moment ago.vanishedTarget := parseUUID("00000000-0000-0000-0000-0000000000fe")- err := testHandler.mergeLegacyRuntime(ctx, vanishedTarget, parseUUID(f.victimRuntime), "legacy-daemon", "delete-test")+ err := h.mergeLegacyRuntime(ctx, vanishedTarget, parseUUID(f.victimRuntime), "legacy-daemon", "delete-test")if !errors.Is(err, errRuntimeMergeFenced) {t.Fatalf("mergeLegacyRuntime = %v, want errRuntimeMergeFenced", err)}@@ -374,6 +377,9 @@ func TestMergeLegacyRuntime_KeepsOldRuntimeWhenFenceRefuses(t *testing.T) {if !stillOnOldRuntime {t.Error("the task was re-pointed at the vanished runtime")}+ if len(notifier.runtimeIDs) != 0 {+ t.Fatalf("fenced merge emitted runtime-gone notifications: %v", notifier.runtimeIDs)+ }// And the happy path still merges, so the abort is not unconditional.var freshRuntime string@@ -384,7 +390,7 @@ RETURNING id`, f.victimID, testUserID).Scan(&freshRuntime); err != nil {t.Fatalf("create merge target: %v", err)}- if err := testHandler.mergeLegacyRuntime(ctx, parseUUID(freshRuntime), parseUUID(f.victimRuntime),+ if err := h.mergeLegacyRuntime(ctx, parseUUID(freshRuntime), parseUUID(f.victimRuntime),"legacy-daemon", "delete-test"); err != nil {t.Fatalf("merge onto a live runtime: %v", err)}@@ -394,6 +400,9 @@ RETURNING idif !rowExists(t, "agent_task_queue", f.taskViaRuntime) {t.Error("a completed merge lost the old runtime's task")}+ if len(notifier.runtimeIDs) != 1 || notifier.runtimeIDs[0] != f.victimRuntime {+ t.Fatalf("runtime-gone notifications = %v, want [%s]", notifier.runtimeIDs, f.victimRuntime)+ }}// TestMergeLegacyRuntime_RollsBackWhenAStepFails is the fault-injection half of thediff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.goindex b9874c5b20..748b68c1dd 100644--- a/server/internal/handler/workspace_test.go+++ b/server/internal/handler/workspace_test.go@@ -315,13 +315,19 @@ VALUES ($1, $2, gen_random_uuid(), gen_random_uuid(), 's3://workspace-delete/soureq := newRequest("DELETE", "/api/workspaces/"+wsID, nil)req = withURLParam(req, "id", wsID)- testutil.Call(t, testHandler.DeleteWorkspace, req).Want(http.StatusNoContent)+ notifier := &recordingRuntimeGoneNotifier{}+ h := *testHandler+ h.DaemonRuntimeGone = notifier+ testutil.Call(t, h.DeleteWorkspace, req).Want(http.StatusNoContent)var exists booldbfx.QueryRow(t, `SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)`, wsID).Scan(&exists)if exists {t.Fatal("workspace still exists after owner DELETE")}+ if len(notifier.runtimeIDs) != 1 || notifier.runtimeIDs[0] != runtimeID {+ t.Fatalf("runtime-gone notifications = %v, want [%s]", notifier.runtimeIDs, runtimeID)+ }var pendingCount intdbfx.QueryRow(t, `SELECT COUNT(*) FROM github_pending_check_suite WHERE workspace_id = $1`, wsID).Scan(&pendingCount)diff --git a/server/internal/metrics/daemonws.go b/server/internal/metrics/daemonws.goindex d935ddc1ad..8920a4c972 100644--- a/server/internal/metrics/daemonws.go+++ b/server/internal/metrics/daemonws.go@@ -17,6 +17,10 @@ type DaemonWSCollector struct {wakeupPublishErrors *prometheus.DescwakeupReceivedTotal *prometheus.DescwakeupDeliveredTotal *prometheus.Desc+ runtimeGonePublished *prometheus.Desc+ runtimeGoneErrors *prometheus.Desc+ runtimeGoneReceived *prometheus.Desc+ runtimeGoneDelivered *prometheus.Desc}func NewDaemonWSCollector(m *daemonws.Metrics) *DaemonWSCollector {@@ -31,6 +35,10 @@ func NewDaemonWSCollector(m *daemonws.Metrics) *DaemonWSCollector {wakeupPublishErrors: newDaemonWSDesc("wakeup_publish_errors_total", "Total daemon wakeup Redis publish errors."),wakeupReceivedTotal: newDaemonWSDesc("wakeup_received_total", "Total daemon wakeups received from the Redis relay."),wakeupDeliveredTotal: prometheus.NewDesc("multica_daemonws_wakeup_delivered_total", "Total daemon wakeup local delivery attempts.", []string{"result"}, nil),+ runtimeGonePublished: newDaemonWSDesc("runtime_gone_published_total", "Total runtime-gone notifications published to the Redis relay."),+ runtimeGoneErrors: newDaemonWSDesc("runtime_gone_publish_errors_total", "Total runtime-gone Redis publish errors."),+ runtimeGoneReceived: newDaemonWSDesc("runtime_gone_received_total", "Total runtime-gone notifications received from the Redis relay."),+ runtimeGoneDelivered: prometheus.NewDesc("multica_daemonws_runtime_gone_delivered_total", "Total runtime-gone local delivery attempts.", []string{"result"}, nil),}}@@ -48,6 +56,10 @@ func (c *DaemonWSCollector) Describe(ch chan<- *prometheus.Desc) {c.wakeupPublishErrors,c.wakeupReceivedTotal,c.wakeupDeliveredTotal,+ c.runtimeGonePublished,+ c.runtimeGoneErrors,+ c.runtimeGoneReceived,+ c.runtimeGoneDelivered,} {ch <- desc}@@ -67,4 +79,9 @@ func (c *DaemonWSCollector) Collect(ch chan<- prometheus.Metric) {ch <- prometheus.MustNewConstMetric(c.wakeupReceivedTotal, prometheus.CounterValue, float64(m.WakeupReceivedTotal.Load()))ch <- prometheus.MustNewConstMetric(c.wakeupDeliveredTotal, prometheus.CounterValue, float64(m.WakeupDeliveredHit.Load()), "hit")ch <- prometheus.MustNewConstMetric(c.wakeupDeliveredTotal, prometheus.CounterValue, float64(m.WakeupDeliveredMiss.Load()), "miss")+ ch <- prometheus.MustNewConstMetric(c.runtimeGonePublished, prometheus.CounterValue, float64(m.RuntimeGonePublishedTotal.Load()))+ ch <- prometheus.MustNewConstMetric(c.runtimeGoneErrors, prometheus.CounterValue, float64(m.RuntimeGonePublishErrors.Load()))+ ch <- prometheus.MustNewConstMetric(c.runtimeGoneReceived, prometheus.CounterValue, float64(m.RuntimeGoneReceivedTotal.Load()))+ ch <- prometheus.MustNewConstMetric(c.runtimeGoneDelivered, prometheus.CounterValue, float64(m.RuntimeGoneDeliveredHit.Load()), "hit")+ ch <- prometheus.MustNewConstMetric(c.runtimeGoneDelivered, prometheus.CounterValue, float64(m.RuntimeGoneDeliveredMiss.Load()), "miss")}diff --git a/server/internal/metrics/daemonws_test.go b/server/internal/metrics/daemonws_test.gonew file mode 100644index 0000000000..caa9cdd053--- /dev/null+++ b/server/internal/metrics/daemonws_test.go@@ -0,0 +1,50 @@+package metrics++import (+ "strings"+ "testing"++ "github.com/prometheus/client_golang/prometheus/testutil"++ "github.com/multica-ai/multica/server/internal/daemonws"+)++func TestDaemonWSCollectorSeparatesRuntimeGoneDelivery(t *testing.T) {+ m := &daemonws.Metrics{}+ m.WakeupDeliveredHit.Store(3)+ m.WakeupDeliveredMiss.Store(4)+ m.RuntimeGoneDeliveredHit.Store(5)+ m.RuntimeGoneDeliveredMiss.Store(6)+ m.RuntimeGonePublishedTotal.Store(7)+ m.RuntimeGonePublishErrors.Store(8)+ m.RuntimeGoneReceivedTotal.Store(9)++ err := testutil.CollectAndCompare(NewDaemonWSCollector(m), strings.NewReader(`+# HELP multica_daemonws_runtime_gone_delivered_total Total runtime-gone local delivery attempts.+# TYPE multica_daemonws_runtime_gone_delivered_total counter+multica_daemonws_runtime_gone_delivered_total{result="hit"} 5+multica_daemonws_runtime_gone_delivered_total{result="miss"} 6+# HELP multica_daemonws_runtime_gone_publish_errors_total Total runtime-gone Redis publish errors.+# TYPE multica_daemonws_runtime_gone_publish_errors_total counter+multica_daemonws_runtime_gone_publish_errors_total 8+# HELP multica_daemonws_runtime_gone_published_total Total runtime-gone notifications published to the Redis relay.+# TYPE multica_daemonws_runtime_gone_published_total counter+multica_daemonws_runtime_gone_published_total 7+# HELP multica_daemonws_runtime_gone_received_total Total runtime-gone notifications received from the Redis relay.+# TYPE multica_daemonws_runtime_gone_received_total counter+multica_daemonws_runtime_gone_received_total 9+# HELP multica_daemonws_wakeup_delivered_total Total daemon wakeup local delivery attempts.+# TYPE multica_daemonws_wakeup_delivered_total counter+multica_daemonws_wakeup_delivered_total{result="hit"} 3+multica_daemonws_wakeup_delivered_total{result="miss"} 4+`),+ "multica_daemonws_runtime_gone_delivered_total",+ "multica_daemonws_runtime_gone_publish_errors_total",+ "multica_daemonws_runtime_gone_published_total",+ "multica_daemonws_runtime_gone_received_total",+ "multica_daemonws_wakeup_delivered_total",+ )+ if err != nil {+ t.Fatalf("collect daemon websocket delivery metrics: %v", err)+ }+}diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 6096f7e94d..1203d0edf1 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -561,6 +561,32 @@ func (q *Queries) IsAgentRuntimeEligibleForGC(ctx context.Context, arg IsAgentRureturn eligible, err}+const listAgentRuntimeIDsByWorkspace = `-- name: ListAgentRuntimeIDsByWorkspace :many+SELECT id FROM agent_runtime+WHERE workspace_id = $1+ORDER BY id ASC+`++func (q *Queries) ListAgentRuntimeIDsByWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listAgentRuntimeIDsByWorkspace, workspaceID)+ if err != nil {+ return nil, err+ }+ 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 listAgentRuntimes = `-- name: ListAgentRuntimes :manySELECT 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_runtimeWHERE workspace_id = $1diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex cd008f32d4..10fdf68093 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -3,6 +3,11 @@ SELECT * FROM agent_runtimeWHERE workspace_id = $1ORDER BY created_at ASC;+-- name: ListAgentRuntimeIDsByWorkspace :many+SELECT id FROM agent_runtime+WHERE workspace_id = $1+ORDER BY id ASC;+-- name: ListVisibleAgentRuntimes :many-- A private runtime is another member's machine and must not leak into their-- runtime list. The owner can always see their own runtime; everyone else