Skip to content

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

Go

MUL-4158: allow deleting orphaned profile runtimes

Multica Eve1de0c7d14ca5
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index ac7d6017d9..88f996278e 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -3,6 +3,7 @@ package handler
import (
"context"
"encoding/json"
+ "errors"
"log/slog"
"net/http"
"strconv"
@@ -10,6 +11,7 @@ import (
"time"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/util"
"github.com/multica-ai/multica/server/pkg/agent"
@@ -485,6 +487,22 @@ func canEditRuntime(member db.Member, rt db.AgentRuntime) bool {
return rt.OwnerID.Valid && uuidToString(rt.OwnerID) == uuidToString(member.UserID)
}
+func (h *Handler) runtimeHasLiveProfile(ctx context.Context, rt db.AgentRuntime) (bool, error) {
+ if !rt.ProfileID.Valid {
+ return false, nil
+ }
+ if _, err := h.Queries.GetRuntimeProfileForWorkspace(ctx, db.GetRuntimeProfileForWorkspaceParams{
+ ID: rt.ProfileID,
+ WorkspaceID: rt.WorkspaceID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return false, nil
+ }
+ return false, err
+ }
+ return true, nil
+}
+
// canUseRuntimeForAgent reports whether a workspace member is allowed to
// bind a new agent to — or move an existing agent onto — the given runtime.
// Mirrors canEditRuntime but layers on the runtime's visibility flag so a
@@ -568,13 +586,25 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
}
userID := uuidToString(member.UserID)
- if rt.ProfileID.Valid {
+ hasLiveProfile, err := h.runtimeHasLiveProfile(r.Context(), rt)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to check runtime profile")
+ return
+ }
+ if hasLiveProfile {
writeJSON(w, http.StatusConflict, map[string]any{
"error": "cannot delete a custom runtime instance directly; delete its runtime profile instead.",
"code": "runtime_profile_instance_delete_unsupported",
})
return
}
+ if rt.ProfileID.Valid {
+ slog.Warn("deleting orphaned profile-backed runtime instance",
+ "runtime_id", uuidToString(rt.ID),
+ "profile_id", uuidToString(rt.ProfileID),
+ "workspace_id", wsID,
+ "deleted_by", userID)
+ }
// Check if any active (non-archived) agents are bound to this runtime.
// Surface them on the 409 so the dialog can render the cascade plan
@@ -761,13 +791,25 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R
}
userID := uuidToString(member.UserID)
- if rt.ProfileID.Valid {
+ hasLiveProfile, err := h.runtimeHasLiveProfile(r.Context(), rt)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to check runtime profile")
+ return
+ }
+ if hasLiveProfile {
writeJSON(w, http.StatusConflict, map[string]any{
"error": "cannot delete a custom runtime instance directly; delete its runtime profile instead.",
"code": "runtime_profile_instance_delete_unsupported",
})
return
}
+ if rt.ProfileID.Valid {
+ slog.Warn("deleting orphaned profile-backed runtime instance via cascade",
+ "runtime_id", uuidToString(rt.ID),
+ "profile_id", uuidToString(rt.ProfileID),
+ "workspace_id", wsID,
+ "deleted_by", userID)
+ }
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
diff --git a/server/internal/handler/runtime_cascade_test.go b/server/internal/handler/runtime_cascade_test.go
index 0dbc2f8db6..292648cf5a 100644
--- a/server/internal/handler/runtime_cascade_test.go
+++ b/server/internal/handler/runtime_cascade_test.go
@@ -203,6 +203,34 @@ func TestDeleteAgentRuntime_CustomProfileInstanceRefusesDirectDelete(t *testing.
}
}
+func TestDeleteAgentRuntime_OrphanedProfileAllowsDirectDelete(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID, profileID := createProfileBackedRuntime(t, ctx, "Orphaned Custom Instance Delete")
+ if _, err := testPool.Exec(ctx, `DELETE FROM runtime_profile WHERE id = $1`, profileID); err != nil {
+ t.Fatalf("delete profile row: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var rtRows int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&rtRows); err != nil {
+ t.Fatalf("count runtime rows: %v", err)
+ }
+ if rtRows != 0 {
+ t.Fatalf("expected orphaned custom runtime instance to be deleted, count=%d", rtRows)
+ }
+}
+
// TestArchiveAgentsAndDeleteRuntime_HappyPath exercises the cascade endpoint
// end-to-end: with the correct expected_active_agent_ids snapshot, it must
// archive the active agent, delete the runtime row, and respond 200 with the
@@ -280,6 +308,35 @@ func TestArchiveAgentsAndDeleteRuntime_CustomProfileInstanceRefusesDirectDelete(
}
}
+func TestArchiveAgentsAndDeleteRuntime_OrphanedProfileAllowsCascade(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID, profileID := createProfileBackedRuntime(t, ctx, "Orphaned Custom Instance Cascade")
+ if _, err := testPool.Exec(ctx, `DELETE FROM runtime_profile WHERE id = $1`, profileID); err != nil {
+ t.Fatalf("delete profile row: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/runtimes/"+runtimeID+"/archive-agents-and-delete",
+ map[string]any{"expected_active_agent_ids": []string{}})
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.ArchiveAgentsAndDeleteRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var rtRows int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&rtRows); err != nil {
+ t.Fatalf("count runtime rows: %v", err)
+ }
+ if rtRows != 0 {
+ t.Fatalf("expected orphaned custom runtime instance to be deleted, count=%d", rtRows)
+ }
+}
+
// TestArchiveAgentsAndDeleteRuntime_PlanChanged proves the dialog-confirm
// race guard: if the user's snapshot of active agents drifts from the live
// set (somebody added or archived an agent while the dialog was open), the
diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.go
index 88cb6035f6..b66964ffe0 100644
--- a/server/internal/handler/runtime_profile.go
+++ b/server/internal/handler/runtime_profile.go
@@ -359,31 +359,48 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {
return
}
- // Confirm the profile exists in this workspace before mutating anything.
- if _, err := h.Queries.GetRuntimeProfileForWorkspace(r.Context(), db.GetRuntimeProfileForWorkspaceParams{
+ // Confirm the profile exists in this workspace. If the profile row is
+ // already gone but runtime rows still carry this workspace/profile pair,
+ // treat them as orphaned instances and clean them up below.
+ _, profileErr := h.Queries.GetRuntimeProfileForWorkspace(r.Context(), db.GetRuntimeProfileForWorkspaceParams{
ID: profileUUID,
WorkspaceID: wsUUID,
- }); err != nil {
+ })
+ profileMissing := errors.Is(profileErr, pgx.ErrNoRows)
+ if profileErr != nil && !profileMissing {
+ writeError(w, http.StatusInternalServerError, "failed to load runtime profile")
+ return
+ }
+
+ // Enumerate the runtime instance rows registered against this profile in
+ // this workspace. The workspace predicate is important because profile_id has
+ // no FK and should never let a malformed row in another workspace be cleaned
+ // up from this workspace's profile endpoint.
+ runtimeIDs, err := h.Queries.ListAgentRuntimeIDsByProfile(r.Context(), db.ListAgentRuntimeIDsByProfileParams{
+ ProfileID: profileUUID,
+ WorkspaceID: wsUUID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to enumerate profile runtimes")
+ return
+ }
+ if profileMissing && len(runtimeIDs) == 0 {
writeError(w, http.StatusNotFound, "runtime profile not found")
return
}
- // Enumerate the runtime instance rows registered against this profile.
// The profile-delete cascade must run the SAME teardown the runtime-delete
// path uses for each one: agent.runtime_id is ON DELETE RESTRICT, so an
// archived agent still pointing at one of these rows would turn a bare
// delete into a 500. We refuse active agents (409) and clean archived
// agents / their archived squad+autopilot references before deleting.
- runtimeIDs, err := h.Queries.ListAgentRuntimeIDsByProfile(r.Context(), profileUUID)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to enumerate profile runtimes")
- return
- }
-
// Guard 1: refuse while any active (non-archived) agent is bound to one of
// the profile's runtimes. Keep this a 409 — deleting would orphan live
// agents.
- agentCount, err := h.Queries.CountAgentsByProfile(r.Context(), profileUUID)
+ agentCount, err := h.Queries.CountAgentsByProfile(r.Context(), db.CountAgentsByProfileParams{
+ ProfileID: profileUUID,
+ WorkspaceID: wsUUID,
+ })
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to check profile usage")
return
@@ -449,18 +466,23 @@ 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(), profileUUID); err != nil {
+ if _, err := qtx.DeleteAgentRuntimesByProfile(r.Context(), db.DeleteAgentRuntimesByProfileParams{
+ ProfileID: profileUUID,
+ WorkspaceID: wsUUID,
+ }); err != nil {
slog.Error("DeleteAgentRuntimesByProfile failed", "error", err, "profile_id", uuidToString(profileUUID))
writeError(w, http.StatusInternalServerError, "failed to clean up runtime instances")
return
}
- if err := qtx.DeleteRuntimeProfile(r.Context(), db.DeleteRuntimeProfileParams{
- ID: profileUUID,
- WorkspaceID: wsUUID,
- }); err != nil {
- slog.Error("DeleteRuntimeProfile failed", "error", err, "profile_id", uuidToString(profileUUID))
- writeError(w, http.StatusInternalServerError, "failed to delete runtime profile")
- return
+ if !profileMissing {
+ if err := qtx.DeleteRuntimeProfile(r.Context(), db.DeleteRuntimeProfileParams{
+ ID: profileUUID,
+ WorkspaceID: wsUUID,
+ }); err != nil {
+ slog.Error("DeleteRuntimeProfile failed", "error", err, "profile_id", uuidToString(profileUUID))
+ writeError(w, http.StatusInternalServerError, "failed to delete runtime profile")
+ return
+ }
}
if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "failed to commit transaction")
diff --git a/server/internal/handler/runtime_profile_handler_test.go b/server/internal/handler/runtime_profile_handler_test.go
index b6850a0d99..b2c580d5b8 100644
--- a/server/internal/handler/runtime_profile_handler_test.go
+++ b/server/internal/handler/runtime_profile_handler_test.go
@@ -138,6 +138,52 @@ func TestDeleteRuntimeProfile_ActiveAgentBlocks(t *testing.T) {
}
}
+func TestDeleteRuntimeProfile_MissingProfileWithOrphanRuntimesCleansUp(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ profileID := insertRuntimeProfileFixture(t, ctx, "Orphaned Profile Cleanup", "codex", "orphaned-profile-codex")
+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "Orphaned Profile Runtime", "codex")
+ if _, err := testPool.Exec(ctx, `DELETE FROM runtime_profile WHERE id = $1`, profileID); err != nil {
+ t.Fatalf("delete profile row: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)
+ req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)
+ testHandler.DeleteRuntimeProfile(w, req)
+
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var rtRows int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&rtRows); err != nil {
+ t.Fatalf("count runtime rows: %v", err)
+ }
+ if rtRows != 0 {
+ t.Fatalf("expected orphaned runtime row deleted, found %d", rtRows)
+ }
+}
+
+func TestDeleteRuntimeProfile_MissingProfileNoOrphansStillReturns404(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ missingProfileID := "00000000-0000-0000-0000-000000415800"
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+missingProfileID, nil)
+ req = withURLParams(req, "id", testWorkspaceID, "profileId", missingProfileID)
+ testHandler.DeleteRuntimeProfile(w, req)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
// TestCreateRuntimeProfile_ForcesWorkspaceVisibility is the regression guard
// for the visibility leak: visibility=private is not user-settable in v1
// because the read paths don't enforce it. A client that POSTs
diff --git a/server/pkg/db/generated/runtime_profile.sql.go b/server/pkg/db/generated/runtime_profile.sql.go
index 2d39b9ff63..30cdb7f5ff 100644
--- a/server/pkg/db/generated/runtime_profile.sql.go
+++ b/server/pkg/db/generated/runtime_profile.sql.go
@@ -14,14 +14,19 @@ import (
const countAgentsByProfile = `-- name: CountAgentsByProfile :one
SELECT count(*) FROM agent a
JOIN agent_runtime ar ON ar.id = a.runtime_id
-WHERE ar.profile_id = $1 AND a.archived_at IS NULL
+WHERE ar.profile_id = $1 AND ar.workspace_id = $2 AND a.archived_at IS NULL
`
+type CountAgentsByProfileParams struct {
+ ProfileID pgtype.UUID `json:"profile_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
// Counts active (non-archived) agents bound to any runtime instance of this
// profile. The profile-delete path uses this to refuse deletion (409) while
// agents still depend on it, mirroring the runtime-delete guard.
-func (q *Queries) CountAgentsByProfile(ctx context.Context, profileID pgtype.UUID) (int64, error) {
- row := q.db.QueryRow(ctx, countAgentsByProfile, profileID)
+func (q *Queries) CountAgentsByProfile(ctx context.Context, arg CountAgentsByProfileParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countAgentsByProfile, arg.ProfileID, arg.WorkspaceID)
var count int64
err := row.Scan(&count)
return count, err
@@ -90,10 +95,15 @@ func (q *Queries) CreateRuntimeProfile(ctx context.Context, arg CreateRuntimePro
const deleteAgentRuntimesByProfile = `-- name: DeleteAgentRuntimesByProfile :many
DELETE FROM agent_runtime
-WHERE profile_id = $1
+WHERE profile_id = $1 AND workspace_id = $2
RETURNING id, workspace_id, owner_id, daemon_id, provider
`
+type DeleteAgentRuntimesByProfileParams struct {
+ ProfileID pgtype.UUID `json:"profile_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
type DeleteAgentRuntimesByProfileRow struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -106,8 +116,8 @@ type DeleteAgentRuntimesByProfileRow struct {
// the profile-delete path must remove the profile's registered runtime
// instances itself. Returns the deleted rows so the caller can broadcast /
// audit. Runs inside the same transaction as DeleteRuntimeProfile.
-func (q *Queries) DeleteAgentRuntimesByProfile(ctx context.Context, profileID pgtype.UUID) ([]DeleteAgentRuntimesByProfileRow, error) {
- rows, err := q.db.Query(ctx, deleteAgentRuntimesByProfile, profileID)
+func (q *Queries) DeleteAgentRuntimesByProfile(ctx context.Context, arg DeleteAgentRuntimesByProfileParams) ([]DeleteAgentRuntimesByProfileRow, error) {
+ rows, err := q.db.Query(ctx, deleteAgentRuntimesByProfile, arg.ProfileID, arg.WorkspaceID)
if err != nil {
return nil, err
}
@@ -204,16 +214,21 @@ func (q *Queries) GetRuntimeProfileForWorkspace(ctx context.Context, arg GetRunt
const listAgentRuntimeIDsByProfile = `-- name: ListAgentRuntimeIDsByProfile :many
SELECT id FROM agent_runtime
-WHERE profile_id = $1
+WHERE profile_id = $1 AND workspace_id = $2
`
+type ListAgentRuntimeIDsByProfileParams struct {
+ ProfileID pgtype.UUID `json:"profile_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
// Enumerates the runtime instance rows registered against a profile. The
// profile-delete cascade walks these so it can run the same archived-agent /
// archived-squad / autopilot teardown the runtime-delete path uses before
// removing each runtime row — agent.runtime_id is ON DELETE RESTRICT, so a
// bare delete would 500 whenever an archived agent still references the row.
-func (q *Queries) ListAgentRuntimeIDsByProfile(ctx context.Context, profileID pgtype.UUID) ([]pgtype.UUID, error) {
- rows, err := q.db.Query(ctx, listAgentRuntimeIDsByProfile, profileID)
+func (q *Queries) ListAgentRuntimeIDsByProfile(ctx context.Context, arg ListAgentRuntimeIDsByProfileParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listAgentRuntimeIDsByProfile, arg.ProfileID, arg.WorkspaceID)
if err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/runtime_profile.sql b/server/pkg/db/queries/runtime_profile.sql
index 65b1ddae52..a51e352cc5 100644
--- a/server/pkg/db/queries/runtime_profile.sql
+++ b/server/pkg/db/queries/runtime_profile.sql
@@ -62,7 +62,7 @@ WHERE id = $1 AND workspace_id = $2;
-- instances itself. Returns the deleted rows so the caller can broadcast /
-- audit. Runs inside the same transaction as DeleteRuntimeProfile.
DELETE FROM agent_runtime
-WHERE profile_id = $1
+WHERE profile_id = $1 AND workspace_id = $2
RETURNING id, workspace_id, owner_id, daemon_id, provider;
-- name: CountAgentsByProfile :one
@@ -71,7 +71,7 @@ RETURNING id, workspace_id, owner_id, daemon_id, provider;
-- agents still depend on it, mirroring the runtime-delete guard.
SELECT count(*) FROM agent a
JOIN agent_runtime ar ON ar.id = a.runtime_id
-WHERE ar.profile_id = $1 AND a.archived_at IS NULL;
+WHERE ar.profile_id = $1 AND ar.workspace_id = $2 AND a.archived_at IS NULL;
-- name: ListAgentRuntimeIDsByProfile :many
-- Enumerates the runtime instance rows registered against a profile. The
@@ -80,4 +80,4 @@ WHERE ar.profile_id = $1 AND a.archived_at IS NULL;
-- removing each runtime row — agent.runtime_id is ON DELETE RESTRICT, so a
-- bare delete would 500 whenever an archived agent still references the row.
SELECT id FROM agent_runtime
-WHERE profile_id = $1;
+WHERE profile_id = $1 AND workspace_id = $2;