Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): prevent duplicate runtime registration on profile switch (#906)
Jiayuan Zhangff5f6ac2eea8
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.goindex 4118ee4d34..e877ad7de2 100644--- a/server/cmd/server/runtime_sweeper.go+++ b/server/cmd/server/runtime_sweeper.go@@ -18,6 +18,9 @@ const (// staleThresholdSeconds marks runtimes offline if no heartbeat for this long.// The daemon heartbeat interval is 15s, so 45s = 3 missed heartbeats.staleThresholdSeconds = 45.0+ // offlineRuntimeTTLSeconds deletes offline runtimes with no active agents+ // after this duration. 7 days gives users plenty of time to restart daemons.+ offlineRuntimeTTLSeconds = 7 * 24 * 3600.0// dispatchTimeoutSeconds fails tasks stuck in 'dispatched' beyond this.// The dispatched→running transition should be near-instant, so 5 minutes// means something went wrong (e.g. StartTask API call failed silently).@@ -42,6 +45,7 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, bus *events.Buscase <-ticker.C:sweepStaleRuntimes(ctx, queries, bus)sweepStaleTasks(ctx, queries, bus)+ gcRuntimes(ctx, queries, bus)}}}@@ -89,6 +93,38 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, bus *events.Bu}}+// gcRuntimes deletes offline runtimes that have exceeded the TTL and have+// no active (non-archived) agents. Before deleting, it cleans up any+// archived agents so the FK constraint (ON DELETE RESTRICT) doesn't block.+func gcRuntimes(ctx context.Context, queries *db.Queries, bus *events.Bus) {+ deleted, err := queries.DeleteStaleOfflineRuntimes(ctx, offlineRuntimeTTLSeconds)+ if err != nil {+ slog.Warn("runtime GC: failed to delete stale offline runtimes", "error", err)+ return+ }+ if len(deleted) == 0 {+ return+ }++ gcWorkspaces := make(map[string]bool)+ for _, row := range deleted {+ gcWorkspaces[util.UUIDToString(row.WorkspaceID)] = true+ }++ slog.Info("runtime GC: deleted stale offline runtimes", "count", len(deleted), "workspaces", len(gcWorkspaces))++ for wsID := range gcWorkspaces {+ bus.Publish(events.Event{+ Type: protocol.EventDaemonRegister,+ WorkspaceID: wsID,+ ActorType: "system",+ Payload: map[string]any{+ "action": "runtime_gc",+ },+ })+ }+}+// sweepStaleTasks fails tasks stuck in dispatched/running for too long,// even when the runtime is still online. This handles cases where:// - The agent process hangs and the daemon is still heartbeatingdiff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 1d8ed6dbc6..38eb5886f5 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -164,11 +164,10 @@ func LoadConfig(overrides Overrides) (Config, error) {if overrides.DaemonID != "" {daemonID = overrides.DaemonID}- // Suffix daemon ID with profile name to avoid collisions when multiple- // daemons register against the same server.- if profile != "" && !strings.HasSuffix(daemonID, "-"+profile) {- daemonID = daemonID + "-" + profile- }+ // NOTE: daemon_id is intentionally stable (hostname or explicit override).+ // The unique constraint (workspace_id, daemon_id, provider) already prevents+ // collisions within the same workspace. Appending the profile name caused+ // duplicate runtimes when users switched profiles.deviceName := envOrDefault("MULTICA_DAEMON_DEVICE_NAME", host)if overrides.DeviceName != "" {diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 8890cb1e2b..4568707426 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -217,6 +217,26 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to register runtime: "+err.Error())return}++ // Migrate agents from old offline runtimes on the same machine to the+ // newly registered runtime. Scoped by daemon_id prefix so that only+ // old profile-suffixed runtimes (e.g. "hostname-staging") from this+ // machine are affected — runtimes from other machines are untouched.+ if ownerID.Valid {+ migrated, err := h.Queries.MigrateAgentsToRuntime(r.Context(), db.MigrateAgentsToRuntimeParams{+ NewRuntimeID: registered.ID,+ WorkspaceID: parseUUID(req.WorkspaceID),+ Provider: provider,+ OwnerID: ownerID,+ DaemonIDPrefix: strToText(req.DaemonID),+ })+ if err != nil {+ slog.Warn("failed to migrate agents to new runtime", "runtime_id", uuidToString(registered.ID), "error", err)+ } else if migrated > 0 {+ slog.Info("migrated agents to new runtime", "runtime_id", uuidToString(registered.ID), "provider", provider, "migrated_count", migrated)+ }+ }+resp = append(resp, runtimeToResponse(registered))}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex a4abf61638..fee7169900 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -145,7 +145,7 @@ func (h *Handler) GetRuntimeUsage(w http.ResponseWriter, r *http.Request) {rows, err := h.Queries.ListRuntimeUsage(r.Context(), db.ListRuntimeUsageParams{RuntimeID: parseUUID(runtimeID),- Since: since,+ Date: since,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list usage")diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 683d97b8dc..99dcef9079 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -40,6 +40,42 @@ func (q *Queries) DeleteArchivedAgentsByRuntime(ctx context.Context, runtimeID preturn err}+const deleteStaleOfflineRuntimes = `-- name: DeleteStaleOfflineRuntimes :many+DELETE FROM agent_runtime+WHERE status = 'offline'+ AND last_seen_at < now() - make_interval(secs => $1::double precision)+ AND id NOT IN (SELECT DISTINCT runtime_id FROM agent)+RETURNING id, workspace_id+`++type DeleteStaleOfflineRuntimesRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Deletes runtimes that have been offline for longer than the TTL and have+// no agents bound (active or archived). The FK constraint on agent.runtime_id+// is ON DELETE RESTRICT, so we must exclude all agent references.+func (q *Queries) DeleteStaleOfflineRuntimes(ctx context.Context, staleSeconds float64) ([]DeleteStaleOfflineRuntimesRow, error) {+ rows, err := q.db.Query(ctx, deleteStaleOfflineRuntimes, staleSeconds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []DeleteStaleOfflineRuntimesRow{}+ for rows.Next() {+ var i DeleteStaleOfflineRuntimesRow+ if err := rows.Scan(&i.ID, &i.WorkspaceID); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const failTasksForOfflineRuntimes = `-- name: FailTasksForOfflineRuntimes :manyUPDATE agent_task_queueSET status = 'failed', completed_at = now(), error = 'runtime went offline'@@ -253,6 +289,48 @@ func (q *Queries) MarkStaleRuntimesOffline(ctx context.Context, staleSeconds floreturn items, nil}+const migrateAgentsToRuntime = `-- name: MigrateAgentsToRuntime :execrows+UPDATE agent+SET runtime_id = $1+WHERE runtime_id IN (+ SELECT ar.id FROM agent_runtime ar+ WHERE ar.workspace_id = $2+ AND ar.provider = $3+ AND ar.owner_id = $4+ AND ar.id != $1+ AND ar.status = 'offline'+ AND ar.daemon_id LIKE $5 || '-%'+)+`++type MigrateAgentsToRuntimeParams struct {+ NewRuntimeID pgtype.UUID `json:"new_runtime_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Provider string `json:"provider"`+ OwnerID pgtype.UUID `json:"owner_id"`+ DaemonIDPrefix pgtype.Text `json:"daemon_id_prefix"`+}++// Migrates agents from stale offline runtimes to the newly registered runtime.+// Only migrates from runtimes that match the same workspace, provider, owner,+// AND whose daemon_id starts with the current daemon_id followed by '-'.+// This scopes migration to old profile-suffixed runtimes from the same machine+// (e.g. "MacBook-staging" matches daemon_id_prefix "MacBook") without touching+// runtimes from other machines belonging to the same user.+func (q *Queries) MigrateAgentsToRuntime(ctx context.Context, arg MigrateAgentsToRuntimeParams) (int64, error) {+ result, err := q.db.Exec(ctx, migrateAgentsToRuntime,+ arg.NewRuntimeID,+ arg.WorkspaceID,+ arg.Provider,+ arg.OwnerID,+ arg.DaemonIDPrefix,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const setAgentRuntimeOffline = `-- name: SetAgentRuntimeOffline :execUPDATE agent_runtimeSET status = 'offline', updated_at = now()diff --git a/server/pkg/db/generated/runtime_usage.sql.go b/server/pkg/db/generated/runtime_usage.sql.goindex 9683acc364..fa6a8aea7d 100644--- a/server/pkg/db/generated/runtime_usage.sql.go+++ b/server/pkg/db/generated/runtime_usage.sql.go@@ -101,11 +101,11 @@ ORDER BY date DESCtype ListRuntimeUsageParams struct {RuntimeID pgtype.UUID `json:"runtime_id"`- Since pgtype.Date `json:"since"`+ Date pgtype.Date `json:"date"`}func (q *Queries) ListRuntimeUsage(ctx context.Context, arg ListRuntimeUsageParams) ([]RuntimeUsage, error) {- rows, err := q.db.Query(ctx, listRuntimeUsage, arg.RuntimeID, arg.Since)+ rows, err := q.db.Query(ctx, listRuntimeUsage, arg.RuntimeID, arg.Date)if err != nil {return nil, err}diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex 1e70a53721..8a7d543fe6 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -78,3 +78,32 @@ SELECT count(*) FROM agent WHERE runtime_id = $1 AND archived_at IS NULL;-- name: DeleteArchivedAgentsByRuntime :execDELETE FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL;++-- name: MigrateAgentsToRuntime :execrows+-- Migrates agents from stale offline runtimes to the newly registered runtime.+-- Only migrates from runtimes that match the same workspace, provider, owner,+-- AND whose daemon_id starts with the current daemon_id followed by '-'.+-- This scopes migration to old profile-suffixed runtimes from the same machine+-- (e.g. "MacBook-staging" matches daemon_id_prefix "MacBook") without touching+-- runtimes from other machines belonging to the same user.+UPDATE agent+SET runtime_id = @new_runtime_id+WHERE runtime_id IN (+ SELECT ar.id FROM agent_runtime ar+ WHERE ar.workspace_id = @workspace_id+ AND ar.provider = @provider+ AND ar.owner_id = @owner_id+ AND ar.id != @new_runtime_id+ AND ar.status = 'offline'+ AND ar.daemon_id LIKE @daemon_id_prefix || '-%'+);++-- name: DeleteStaleOfflineRuntimes :many+-- Deletes runtimes that have been offline for longer than the TTL and have+-- no agents bound (active or archived). The FK constraint on agent.runtime_id+-- is ON DELETE RESTRICT, so we must exclude all agent references.+DELETE FROM agent_runtime+WHERE status = 'offline'+ AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)+ AND id NOT IN (SELECT DISTINCT runtime_id FROM agent)+RETURNING id, workspace_id;