Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6640: fix stale Autopilot subscribers after member removal (#7501)
Multica Eve2aa45853d986
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex dc9e951dcd..7d6de02f65 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -9,6 +9,7 @@ import ("io""log/slog""net/http"+ "sort""strconv""strings""time"@@ -664,8 +665,8 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {return}- // Validate before insert so a bad payload doesn't half-create the row.- subscriberUUIDs, ok := h.validateAutopilotSubscribers(w, r, req.Subscribers, workspaceID)+ // Parse before insert so a malformed payload doesn't open a transaction.+ subscribers, ok := parseAutopilotSubscribers(w, req.Subscribers)if !ok {return}@@ -678,6 +679,15 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)+ // This must be the first lock family in the transaction. Member revocation+ // takes the same per-(workspace, user) locks before pruning templates and+ // deleting member rows. Re-checking membership after those locks means+ // either this save commits first and revocation prunes it, or revocation+ // commits first and this save rejects the departed subscriber.+ if !h.lockAndValidateAutopilotSubscribers(w, r, qtx, subscribers, wsUUID) {+ return+ }+// Keep save-time readiness validation in the same transaction as the// insert. The assignment lock serializes this path with Runtime teardown,// so an active Autopilot cannot slip in after teardown's pause sweep.@@ -711,11 +721,11 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {return}- for _, uid := range subscriberUUIDs {+ for _, subscriber := range subscribers {if err := qtx.AddAutopilotSubscriber(r.Context(), db.AddAutopilotSubscriberParams{AutopilotID: autopilot.ID,UserType: "member",- UserID: uid,+ UserID: subscriber.UserID,}); err != nil {writeError(w, http.StatusInternalServerError, "failed to add autopilot subscriber")return@@ -742,19 +752,19 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusCreated, resp)}-// Writes an HTTP error and returns ok=false on the first invalid entry.-// Returns (nil, true) when raw is empty — caller distinguishes "leave alone"-// from "replace with empty" via the raw-fields map, not this return.-func (h *Handler) validateAutopilotSubscribers(- w http.ResponseWriter,- r *http.Request,- raw []SubscriberInput,- workspaceID string,-) ([]pgtype.UUID, bool) {+type autopilotSubscriberCandidate struct {+ UserID pgtype.UUID+ InputIndex int+}++// parseAutopilotSubscribers validates the wire shape without reading mutable+// membership state. Membership is checked only after the write transaction+// owns the same serialization locks as member revocation.+func parseAutopilotSubscribers(w http.ResponseWriter, raw []SubscriberInput) ([]autopilotSubscriberCandidate, bool) {if len(raw) == 0 {return nil, true}- out := make([]pgtype.UUID, 0, len(raw))+ out := make([]autopilotSubscriberCandidate, 0, len(raw))seen := make(map[string]bool, len(raw))for i, entry := range raw {if entry.UserType != "member" {@@ -769,19 +779,59 @@ func (h *Handler) validateAutopilotSubscribers(if !ok {return nil, false}- if seen[entry.UserID] {+ canonicalID := uuidToString(uid)+ if seen[canonicalID] {continue}- seen[entry.UserID] = true- if !h.isWorkspaceEntity(r.Context(), entry.UserType, entry.UserID, workspaceID) {- writeError(w, http.StatusBadRequest, fmt.Sprintf("subscribers[%d] is not a member of this workspace", i))- return nil, false- }- out = append(out, uid)+ seen[canonicalID] = true+ out = append(out, autopilotSubscriberCandidate{UserID: uid, InputIndex: i})}return out, true}+// lockAndValidateAutopilotSubscribers serializes subscriber-template writes+// with member revocation. Locks and row checks both use canonical UUID order,+// so two saves containing the same members in different request orders cannot+// deadlock each other.+func (h *Handler) lockAndValidateAutopilotSubscribers(+ w http.ResponseWriter,+ r *http.Request,+ qtx *db.Queries,+ subscribers []autopilotSubscriberCandidate,+ workspaceID pgtype.UUID,+) bool {+ ordered := append([]autopilotSubscriberCandidate(nil), subscribers...)+ sort.Slice(ordered, func(i, j int) bool {+ return uuidToString(ordered[i].UserID) < uuidToString(ordered[j].UserID)+ })++ for _, subscriber := range ordered {+ if err := qtx.LockSubscriberWrites(r.Context(), db.LockSubscriberWritesParams{+ WorkspaceID: workspaceID,+ UserID: subscriber.UserID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to validate autopilot subscribers")+ return false+ }+ }+ for _, subscriber := range ordered {+ if _, err := qtx.LockActiveMember(r.Context(), db.LockActiveMemberParams{+ UserID: subscriber.UserID,+ WorkspaceID: workspaceID,+ }); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusBadRequest, fmt.Sprintf(+ "subscribers[%d] is not a member of this workspace", subscriber.InputIndex,+ ))+ return false+ }+ writeError(w, http.StatusInternalServerError, "failed to validate autopilot subscribers")+ return false+ }+ }+ return true+}+func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {id := chi.URLParam(r, "id")workspaceID := h.resolveWorkspaceID(r)@@ -890,19 +940,19 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {}}- // Subscribers are validated up-front (before any write) so a bad payload- // doesn't leave the autopilot row updated but the template stale.+ // Parse subscriber wire values up-front. Mutable membership is revalidated+ // under the revocation serialization locks after the transaction starts.var (- subscriberUUIDs []pgtype.UUID+ subscribers []autopilotSubscriberCandidatereplaceSubscribers bool)if _, sent := rawFields["subscribers"]; sent {replaceSubscribers = true- validated, vok := h.validateAutopilotSubscribers(w, r, req.Subscribers, workspaceID)+ validated, vok := parseAutopilotSubscribers(w, req.Subscribers)if !vok {return}- subscriberUUIDs = validated+ subscribers = validated}tx, err := h.TxStarter.Begin(r.Context())@@ -913,6 +963,12 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)+ // Lock subscriber identities before assignment and autopilot rows. This is+ // the same global order used by CreateAutopilot and member revocation.+ if !h.lockAndValidateAutopilotSubscribers(w, r, qtx, subscribers, prev.WorkspaceID) {+ return+ }+// Retargeting must validate the polymorphic reference; resuming must also// validate Runtime readiness. Keep both in this transaction so Runtime// teardown either pauses an active row after it commits or wins first and@@ -986,11 +1042,11 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to update subscribers")return}- for _, uid := range subscriberUUIDs {+ for _, subscriber := range subscribers {if err := qtx.AddAutopilotSubscriber(r.Context(), db.AddAutopilotSubscriberParams{AutopilotID: autopilot.ID,UserType: "member",- UserID: uid,+ UserID: subscriber.UserID,}); err != nil {writeError(w, http.StatusInternalServerError, "failed to add autopilot subscriber")returndiff --git a/server/internal/handler/autopilot_subscriber_test.go b/server/internal/handler/autopilot_subscriber_test.goindex 2bb4d00cee..244962594c 100644--- a/server/internal/handler/autopilot_subscriber_test.go+++ b/server/internal/handler/autopilot_subscriber_test.go@@ -10,6 +10,7 @@ import ("time""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -147,6 +148,156 @@ func TestCreateAutopilotRejectsForeignSubscriber(t *testing.T) {}}+// TestAutopilotSubscriberSave_LosesToConcurrentRevoke covers the race between+// subscriber validation and member removal for both create and update. The+// revoke transaction has already pruned templates and deleted the member, but+// has not committed, so a validation outside the serialized write transaction+// can still see the old member snapshot and recreate a subscriber row behind+// the cleanup. Saves must wait for revoke's lock, then reject the departed+// member from their fresh in-transaction membership check.+func TestAutopilotSubscriberSave_LosesToConcurrentRevoke(t *testing.T) {+ ctx := context.Background()++ var agentID string+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("load test agent: %v", err)+ }++ for _, tc := range []struct {+ name string+ prepare func(t *testing.T, targetUserID string) func() (status int, body string, autopilotID string)+ }{+ {+ name: "create",+ prepare: func(t *testing.T, targetUserID string) func() (int, string, string) {+ title := fmt.Sprintf("Concurrent revoke create %d", time.Now().UnixNano())+ return func() (int, string, string) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "assignee_id": agentID,+ "execution_mode": "create_issue",+ "subscribers": []map[string]any{+ {"user_type": "member", "user_id": targetUserID},+ },+ })+ testHandler.CreateAutopilot(w, req)++ var autopilotID string+ testPool.QueryRow(ctx, `SELECT id FROM autopilot WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title).Scan(&autopilotID)+ return w.Code, w.Body.String(), autopilotID+ }+ },+ },+ {+ name: "update",+ prepare: func(t *testing.T, targetUserID string) func() (int, string, string) {+ createReq := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{+ "title": fmt.Sprintf("Concurrent revoke update %d", time.Now().UnixNano()),+ "assignee_id": agentID,+ "execution_mode": "create_issue",+ })+ var created AutopilotResponse+ testutil.Call(t, testHandler.CreateAutopilot, createReq).+ Want(http.StatusCreated).+ JSON(&created)++ return func() (int, string, string) {+ w := httptest.NewRecorder()+ req := newRequest("PATCH", "/api/autopilots/"+created.ID+"?workspace_id="+testWorkspaceID, map[string]any{+ "subscribers": []map[string]any{+ {"user_type": "member", "user_id": targetUserID},+ },+ })+ req = withURLParam(req, "id", created.ID)+ testHandler.UpdateAutopilot(w, req)+ return w.Code, w.Body.String(), created.ID+ }+ },+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ targetUserID := createPlainMember(t, fmt.Sprintf("autopilot-revoke-race-%s-%[email protected]", tc.name, time.Now().UnixNano()))+ run := tc.prepare(t, targetUserID)++ revokeTx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin revoke tx: %v", err)+ }+ defer revokeTx.Rollback(context.Background())+ qtx := testHandler.Queries.WithTx(revokeTx)++ if err := qtx.LockSubscriberWrites(ctx, db.LockSubscriberWritesParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ UserID: parseUUID(targetUserID),+ }); err != nil {+ t.Fatalf("revoke lock: %v", err)+ }+ if err := qtx.DeleteAutopilotSubscribersByMember(ctx, db.DeleteAutopilotSubscribersByMemberParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ UserID: parseUUID(targetUserID),+ }); err != nil {+ t.Fatalf("revoke cleanup: %v", err)+ }+ if _, err := revokeTx.Exec(ctx,+ `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`,+ testWorkspaceID, targetUserID,+ ); err != nil {+ t.Fatalf("revoke member delete: %v", err)+ }++ type result struct {+ status int+ body string+ autopilotID string+ }+ done := make(chan result, 1)+ go func() {+ status, body, autopilotID := run()+ done <- result{status: status, body: body, autopilotID: autopilotID}+ }()++ select {+ case got := <-done:+ t.Fatalf("autopilot %s completed (status %d: %s) while revoke held the subscriber lock", tc.name, got.status, got.body)+ case <-time.After(400 * time.Millisecond):+ }++ if err := revokeTx.Commit(context.Background()); err != nil {+ t.Fatalf("commit revoke: %v", err)+ }++ var got result+ select {+ case got = <-done:+ case <-time.After(10 * time.Second):+ t.Fatalf("autopilot %s never returned after revoke committed", tc.name)+ }+ if got.status != http.StatusBadRequest {+ t.Fatalf("autopilot %s status = %d, want 400 after subscriber left: %s", tc.name, got.status, got.body)+ }+ if got.autopilotID != "" {+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, got.autopilotID)+ })+ }++ var staleRows int+ if err := testPool.QueryRow(context.Background(), `+ SELECT count(*)+ FROM autopilot_subscriber s+ JOIN autopilot a ON a.id = s.autopilot_id+ WHERE a.workspace_id = $1 AND s.user_id = $2+ `, testWorkspaceID, targetUserID).Scan(&staleRows); err != nil {+ t.Fatalf("count stale subscriber rows: %v", err)+ }+ if staleRows != 0 {+ t.Fatalf("autopilot %s recreated %d subscriber row(s) after revoke cleanup", tc.name, staleRows)+ }+ })+ }+}+func TestCreateAutopilotRollsBackWhenSubscriberInsertFails(t *testing.T) {ctx := context.Background()title := fmt.Sprintf("Subscriber rollback create %d", time.Now().UnixNano())@@ -371,6 +522,68 @@ func TestUpdateAutopilotPreservesSubscribersWhenOmitted(t *testing.T) {}}+// TestAutopilotDepartedSubscriberReadRepair covers the MUL-6640 regression:+// older member-removal code could leave an autopilot_subscriber row behind.+// The member picker hid that user, but GET still returned the stale id and the+// edit dialog round-tripped it into PATCH, which then rejected every save.+//+// The read path must expose only current members. Sending that authoritative+// list back through the existing full-replace PATCH then removes the legacy+// row without weakening create/update validation for arbitrary foreign ids.+func TestAutopilotDepartedSubscriberReadRepair(t *testing.T) {+ ctx := context.Background()+ departedUserID := createPlainMember(t, fmt.Sprintf("autopilot-departed-%[email protected]", time.Now().UnixNano()))++ var agentID string+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("load test agent: %v", err)+ }++ createReq := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Departed subscriber read repair",+ "assignee_id": agentID,+ "execution_mode": "create_issue",+ "subscribers": []map[string]any{+ {"user_type": "member", "user_id": departedUserID},+ },+ })+ var created AutopilotResponse+ testutil.Call(t, testHandler.CreateAutopilot, createReq).+ Want(http.StatusCreated).+ JSON(&created)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, created.ID)+ })++ // Model a row produced before member-removal learned to prune autopilot+ // templates. Deliberately leave autopilot_subscriber intact.+ dbfx.Exec(t, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, departedUserID)++ getReq := newRequest("GET", "/api/autopilots/"+created.ID+"?workspace_id="+testWorkspaceID, nil)+ getReq = withURLParam(getReq, "id", created.ID)+ var detail struct {+ Autopilot AutopilotResponse `json:"autopilot"`+ }+ testutil.Call(t, testHandler.GetAutopilot, getReq).+ Want(http.StatusOK).+ JSON(&detail)+ if len(detail.Autopilot.Subscribers) != 0 {+ t.Fatalf("GET subscribers = %+v, want departed member omitted", detail.Autopilot.Subscribers)+ }++ updateReq := newRequest("PATCH", "/api/autopilots/"+created.ID+"?workspace_id="+testWorkspaceID, map[string]any{+ "subscribers": detail.Autopilot.Subscribers,+ })+ updateReq = withURLParam(updateReq, "id", created.ID)+ testutil.Call(t, testHandler.UpdateAutopilot, updateReq).Want(http.StatusOK)++ var count int+ dbfx.QueryRow(t, `SELECT count(*) FROM autopilot_subscriber WHERE autopilot_id = $1`, created.ID).Scan(&count)+ if count != 0 {+ t.Fatalf("legacy autopilot_subscriber rows after save = %d, want 0", count)+ }+}+// TestAutopilotDispatchFansOutSubscribersToIssue is the integration check// for the dispatch path: an autopilot with a default subscriber list must// auto-subscribe each entry to the issue it spawns, with reason='autopilot'.diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex a2c1b0b287..e4f6bbc3b1 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -14,8 +14,8 @@ import (// agent pinned to one of those runtimes is archived, every in-flight task on// those runtimes is cancelled (cancelled rather than failed so the daemon's// per-task status poller interrupts the running agent gracefully), the-// daemon_token rows for those runtimes are deleted, and finally the member row-// itself is removed.+// member's durable subscriptions and daemon_token rows are deleted, and+// finally the member row itself is removed.//// All DB writes run inside a single transaction so a partial revocation never// leaves the workspace half-converged — e.g. a member who is "gone" but whose@@ -194,6 +194,18 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userIDreturn empty, err}+ // autopilot_subscriber is another FK-free subscription template. Leaving+ // stale rows here made the detail API return a user the member picker could+ // no longer render; the next full-replace PATCH then failed membership+ // validation, blocking every edit to that autopilot. Prune only templates in+ // this workspace so the same user's subscriptions elsewhere survive.+ if err := qtx.DeleteAutopilotSubscribersByMember(ctx, db.DeleteAutopilotSubscribersByMemberParams{+ WorkspaceID: workspaceID,+ UserID: userID,+ }); err != nil {+ return empty, err+ }+// Member row deletion lives inside the same tx so a successful revoke is// never followed by a failed member-delete (which would leave the user// still a member with a dead runtime), and a failed revoke never leavesdiff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.goindex 657bcd82d0..6dbeef4033 100644--- a/server/internal/handler/workspace_test.go+++ b/server/internal/handler/workspace_test.go@@ -941,6 +941,102 @@ VALUES ($1, $2, $3, 'feishu', $4)}}+// TestDeleteMember_PrunesAutopilotSubscribers verifies the application-layer+// cleanup for the FK-free autopilot_subscriber table. DeleteMember and+// LeaveWorkspace both use revokeAndRemoveMember, so this pins their shared+// transaction while also proving the delete is scoped to the departed user.+func TestDeleteMember_PrunesAutopilotSubscribers(t *testing.T) {+ fx := setupRevocationFixture(t, "handler-tests-revoke-autopilot-subscriber", "daemon-revoke-autopilot-subscriber")++ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": fx.WorkspaceID,+ "title": "Revocation autopilot subscriber",+ "assignee_type": "agent",+ "assignee_id": fx.AgentID,+ "status": "active",+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": testUserID,+ })+ dbfx.Exec(t, `+INSERT INTO autopilot_subscriber (autopilot_id, user_type, user_id)+VALUES ($1, 'member', $2), ($1, 'member', $3)+`, autopilotID, fx.TargetUserID, testUserID)++ // The same person belongs to another workspace and subscribes there too.+ // Removing them from fx.WorkspaceID must not cross this tenant boundary.+ otherWorkspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Revocation subscriber other workspace",+ "slug": fmt.Sprintf("handler-tests-revoke-autopilot-subscriber-other-%d", time.Now().UnixNano()),+ "description": "tenant-scope regression fixture",+ "issue_prefix": "RAO",+ })+ dbfx.Insert(t, "member", testutil.Cols{+ "workspace_id": otherWorkspaceID,+ "user_id": fx.TargetUserID,+ "role": "owner",+ })+ otherRuntimeID := dbfx.Runtime(t, "Other workspace runtime", testutil.Cols{+ "workspace_id": otherWorkspaceID,+ "daemon_id": "daemon-revoke-autopilot-subscriber-other",+ "runtime_mode": "local",+ "provider": "multica_daemon",+ "owner_id": fx.TargetUserID,+ })+ otherAgentID := dbfx.Agent(t, "Other workspace agent", otherRuntimeID, testutil.Cols{+ "workspace_id": otherWorkspaceID,+ "runtime_mode": "local",+ "visibility": "workspace",+ "owner_id": fx.TargetUserID,+ })+ otherAutopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": otherWorkspaceID,+ "title": "Other workspace autopilot subscriber",+ "assignee_type": "agent",+ "assignee_id": otherAgentID,+ "status": "active",+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": fx.TargetUserID,+ })+ dbfx.Exec(t, `+INSERT INTO autopilot_subscriber (autopilot_id, user_type, user_id)+VALUES ($1, 'member', $2)+`, otherAutopilotID, fx.TargetUserID)++ req := newRequest("DELETE", "/api/workspaces/"+fx.WorkspaceID+"/members/"+fx.MemberID, nil)+ req.Header.Set("X-Workspace-ID", fx.WorkspaceID)+ req = withURLParams(req, "id", fx.WorkspaceID, "memberId", fx.MemberID)+ testutil.Call(t, testHandler.DeleteMember, req).Want(http.StatusNoContent)++ var removedCount int+ dbfx.QueryRow(t, `+SELECT count(*) FROM autopilot_subscriber+WHERE autopilot_id = $1 AND user_id = $2+`, autopilotID, fx.TargetUserID).Scan(&removedCount)+ if removedCount != 0 {+ t.Fatalf("departed member autopilot subscribers = %d, want 0", removedCount)+ }++ var remainingCount int+ dbfx.QueryRow(t, `+SELECT count(*) FROM autopilot_subscriber+WHERE autopilot_id = $1 AND user_id = $2+`, autopilotID, testUserID).Scan(&remainingCount)+ if remainingCount != 1 {+ t.Fatalf("remaining member autopilot subscribers = %d, want 1", remainingCount)+ }++ var otherWorkspaceCount int+ dbfx.QueryRow(t, `+SELECT count(*) FROM autopilot_subscriber+WHERE autopilot_id = $1 AND user_id = $2+`, otherAutopilotID, fx.TargetUserID).Scan(&otherWorkspaceCount)+ if otherWorkspaceCount != 1 {+ t.Fatalf("other workspace autopilot subscribers = %d, want 1", otherWorkspaceCount)+ }+}+// TestLeaveWorkspace_RevokesOwnRuntimes is the self-removal counterpart: when// a member leaves a workspace voluntarily, their own runtimes are revoked// with the same atomic write set as DeleteMember.diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex e176917103..3cc7eb491d 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -506,6 +506,28 @@ func (q *Queries) DeleteAutopilotCollaboratorsForAutopilot(ctx context.Context,return err}+const deleteAutopilotSubscribersByMember = `-- name: DeleteAutopilotSubscribersByMember :exec+DELETE FROM autopilot_subscriber AS s+USING autopilot AS a+WHERE s.autopilot_id = a.id+ AND a.workspace_id = $1+ AND s.user_type = 'member'+ AND s.user_id = $2+`++type DeleteAutopilotSubscribersByMemberParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++// Autopilot subscribers carry no FK, so member removal must prune them in the+// same application transaction. Scope through the autopilot's workspace: the+// same user may remain subscribed to autopilots in another workspace.+func (q *Queries) DeleteAutopilotSubscribersByMember(ctx context.Context, arg DeleteAutopilotSubscribersByMemberParams) error {+ _, err := q.db.Exec(ctx, deleteAutopilotSubscribersByMember, arg.WorkspaceID, arg.UserID)+ return err+}+const deleteAutopilotSubscribersForAutopilot = `-- name: DeleteAutopilotSubscribersForAutopilot :execDELETE FROM autopilot_subscriberWHERE autopilot_id = $1@@ -1199,14 +1221,23 @@ func (q *Queries) ListAutopilotRuns(ctx context.Context, arg ListAutopilotRunsPaconst listAutopilotSubscribers = `-- name: ListAutopilotSubscribers :many-SELECT autopilot_id, user_type, user_id, created_at FROM autopilot_subscriber-WHERE autopilot_id = $1-ORDER BY created_at ASC, user_id ASC+SELECT s.autopilot_id, s.user_type, s.user_id, s.created_at FROM autopilot_subscriber AS s+JOIN autopilot AS a ON a.id = s.autopilot_id+JOIN member AS m+ ON m.workspace_id = a.workspace_id+ AND m.user_id = s.user_id+WHERE s.autopilot_id = $1+ AND s.user_type = 'member'+ORDER BY s.created_at ASC, s.user_id ASC`// =====================// Autopilot Subscribers// =====================+// Only current workspace members are effective subscribers. The membership+// join makes legacy rows left behind by older member-removal code inert on+// both the detail response and the dispatch path, so clients never round-trip+// a hidden departed member into an otherwise valid update.// ORDER BY created_at keeps chip rendering stable across refreshes.func (q *Queries) ListAutopilotSubscribers(ctx context.Context, autopilotID pgtype.UUID) ([]AutopilotSubscriber, error) {rows, err := q.db.Query(ctx, listAutopilotSubscribers, autopilotID)diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex dbe3e15070..29b715bc70 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -698,10 +698,19 @@ RETURNING *;-- =====================-- name: ListAutopilotSubscribers :many+-- Only current workspace members are effective subscribers. The membership+-- join makes legacy rows left behind by older member-removal code inert on+-- both the detail response and the dispatch path, so clients never round-trip+-- a hidden departed member into an otherwise valid update.-- ORDER BY created_at keeps chip rendering stable across refreshes.-SELECT * FROM autopilot_subscriber-WHERE autopilot_id = $1-ORDER BY created_at ASC, user_id ASC;+SELECT s.* FROM autopilot_subscriber AS s+JOIN autopilot AS a ON a.id = s.autopilot_id+JOIN member AS m+ ON m.workspace_id = a.workspace_id+ AND m.user_id = s.user_id+WHERE s.autopilot_id = $1+ AND s.user_type = 'member'+ORDER BY s.created_at ASC, s.user_id ASC;-- name: AddAutopilotSubscriber :execINSERT INTO autopilot_subscriber (autopilot_id, user_type, user_id)@@ -713,6 +722,17 @@ ON CONFLICT (autopilot_id, user_type, user_id) DO NOTHING;DELETE FROM autopilot_subscriberWHERE autopilot_id = $1;+-- name: DeleteAutopilotSubscribersByMember :exec+-- Autopilot subscribers carry no FK, so member removal must prune them in the+-- same application transaction. Scope through the autopilot's workspace: the+-- same user may remain subscribed to autopilots in another workspace.+DELETE FROM autopilot_subscriber AS s+USING autopilot AS a+WHERE s.autopilot_id = a.id+ AND a.workspace_id = sqlc.arg(workspace_id)+ AND s.user_type = 'member'+ AND s.user_id = sqlc.arg(user_id);+-- =====================-- Autopilot Collaborators-- =====================