Skip to content

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

Go

fix(issues): duplicate mark follow-ups from #8741 review (MUL-7349) (#8752)

Bohan Jiang4469bac6320f
diff --git a/server/cmd/server/activity_listeners.go b/server/cmd/server/activity_listeners.go
index 5a3814bd01..4dff79685a 100644
--- a/server/cmd/server/activity_listeners.go
+++ b/server/cmd/server/activity_listeners.go
@@ -65,8 +65,11 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
statusChanged, _ := payload["status_changed"].(bool)
// A duplicate mark change is a status change with a better name: the
// duplicate row names the other issue and where the status went, so
- // the generic status row would only repeat it (MUL-7349).
- if duplicateMarkChanged(payload) {
+ // the generic status row would only repeat it (MUL-7349). Only a row
+ // that was actually written stands in for it; when the original is
+ // gone there is no duplicate row and the status row still records
+ // the move.
+ if recordDuplicateMarkActivities(ctx, bus, queries, e, issue, payload) {
statusChanged = false
}
priorityChanged, _ := payload["priority_changed"].(bool)
@@ -255,8 +258,6 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
publishActivityEvent(bus, e, activity)
}
}
-
- recordDuplicateMarkActivities(ctx, bus, queries, e, issue, payload)
})
// task:completed — record "task_completed" activity
@@ -342,14 +343,15 @@ func publishActivityEvent(bus *events.Bus, original events.Event, activity db.Ac
// mark change carries both ends as duplicate_of_issue_id and
// prev_duplicate_of_issue_id. Details name the other issue by id, for
// linking, and by identifier, so the row still reads once that issue is gone.
-func recordDuplicateMarkActivities(ctx context.Context, bus *events.Bus, queries *db.Queries, e events.Event, issue handler.IssueResponse, payload map[string]any) {
+// It reports whether it wrote a row on the duplicate itself.
+func recordDuplicateMarkActivities(ctx context.Context, bus *events.Bus, queries *db.Queries, e events.Event, issue handler.IssueResponse, payload map[string]any) bool {
if !duplicateMarkChanged(payload) {
- return
+ return false
}
next := derefPayloadString(payload["duplicate_of_issue_id"])
prev := derefPayloadString(payload["prev_duplicate_of_issue_id"])
statusChanged, _ := payload["status_changed"].(bool)
- record := func(issueID, action string, details map[string]string) {
+ record := func(issueID, action string, details map[string]string) bool {
body, _ := json.Marshal(details)
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
ID: dbid.NewV7(),
@@ -363,11 +365,13 @@ func recordDuplicateMarkActivities(ctx context.Context, bus *events.Bus, queries
if err != nil {
slog.Error("activity: failed to record duplicate mark change",
"issue_id", issueID, "action", action, "error", err)
- return
+ return false
}
publishActivityEvent(bus, e, activity)
+ return true
}
self := map[string]string{"duplicate_id": issue.ID, "duplicate_identifier": issue.Identifier}
+ wroteOwnRow := false
if prev != "" {
if identifier, ok := lookupIssueIdentifier(ctx, queries, issue.WorkspaceID, prev); ok {
@@ -377,22 +381,23 @@ func recordDuplicateMarkActivities(ctx context.Context, bus *events.Bus, queries
// stands in for the status row, so it says where.
details["to"] = issue.Status
}
- record(issue.ID, "duplicate_unmarked", details)
+ wroteOwnRow = record(issue.ID, "duplicate_unmarked", details) || wroteOwnRow
record(prev, "duplicate_removed", self)
} else if identifier, _ := payload["prev_duplicate_of_identifier"].(string); identifier != "" {
// The original was deleted and took its own log with it; the delete
// path passes the identifier it can no longer be looked up by.
- record(issue.ID, "duplicate_unmarked", map[string]string{
+ wroteOwnRow = record(issue.ID, "duplicate_unmarked", map[string]string{
"original_id": prev, "original_identifier": identifier, "reason": "original_deleted",
- })
+ }) || wroteOwnRow
}
}
if next != "" {
if identifier, ok := lookupIssueIdentifier(ctx, queries, issue.WorkspaceID, next); ok {
- record(issue.ID, "duplicate_marked", map[string]string{"original_id": next, "original_identifier": identifier})
+ wroteOwnRow = record(issue.ID, "duplicate_marked", map[string]string{"original_id": next, "original_identifier": identifier}) || wroteOwnRow
record(next, "duplicate_added", self)
}
}
+ return wroteOwnRow
}
// duplicateMarkChanged reports whether an issue:updated payload carries a
diff --git a/server/cmd/server/activity_listeners_test.go b/server/cmd/server/activity_listeners_test.go
index fe9f5fb4df..1bcd3f4a3a 100644
--- a/server/cmd/server/activity_listeners_test.go
+++ b/server/cmd/server/activity_listeners_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"net/http"
+ "strings"
"testing"
"github.com/multica-ai/multica/server/internal/events"
@@ -662,3 +663,94 @@ func TestActivityDuplicateMarkThroughUpdateIssue(t *testing.T) {
t.Fatalf("after reopen, original activities = %v, want [duplicate_added duplicate_removed]", got)
}
}
+
+// A pointer an older server left behind is not a mark (MUL-7349). Servers
+// from before the column existed reopened duplicates and deleted originals
+// without touching it; the writes that later clear it must not log a mark
+// being removed, and a real status move keeps its status row.
+func TestActivityLeftoverDuplicatePointer(t *testing.T) {
+ queries := db.New(testPool)
+ send := func(t *testing.T, method, issueID string, body map[string]any) {
+ t.Helper()
+ resp := authRequest(t, method, "/api/issues/"+issueID, body)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
+ t.Fatalf("%s %s: status %d", method, issueID, resp.StatusCode)
+ }
+ }
+ raw := func(t *testing.T, sql, issueID string) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(), sql, issueID); err != nil {
+ t.Fatalf("%s: %v", sql, err)
+ }
+ }
+ marked := func(t *testing.T) (duplicateID, originalID string) {
+ t.Helper()
+ duplicateID = createTestIssue(t, testWorkspaceID, testUserID)
+ originalID = createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ cleanupActivities(t, duplicateID)
+ cleanupActivities(t, originalID)
+ cleanupTestIssue(t, duplicateID)
+ cleanupTestIssue(t, originalID)
+ })
+ send(t, "PUT", duplicateID, map[string]any{"duplicate_of_issue_id": originalID})
+ return duplicateID, originalID
+ }
+ const reopenedByOldServer = `UPDATE issue SET status = 'todo' WHERE id = $1`
+ const deletedByOldServer = `DELETE FROM issue WHERE id = $1`
+ wantActions := func(t *testing.T, issueID string, want ...string) {
+ t.Helper()
+ if got := activityActions(t, queries, issueID); strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Fatalf("activities on %s = %v, want %v", issueID, got, want)
+ }
+ }
+ wantStatusMove := func(t *testing.T, issueID, from, to string) {
+ t.Helper()
+ if got := activityDetails(t, queries, issueID, "status_changed"); got["from"] != from || got["to"] != to {
+ t.Fatalf("status_changed = %v, want %s -> %s", got, from, to)
+ }
+ }
+
+ t.Run("reopened, then moved", func(t *testing.T) {
+ duplicateID, originalID := marked(t)
+ raw(t, reopenedByOldServer, duplicateID)
+
+ send(t, "PUT", duplicateID, map[string]any{"status": "in_progress"})
+
+ wantActions(t, duplicateID, "duplicate_marked", "status_changed")
+ wantStatusMove(t, duplicateID, "todo", "in_progress")
+ wantActions(t, originalID, "duplicate_added")
+ })
+
+ t.Run("reopened, then edited", func(t *testing.T) {
+ duplicateID, originalID := marked(t)
+ raw(t, reopenedByOldServer, duplicateID)
+
+ send(t, "PUT", duplicateID, map[string]any{"title": "renamed after a rollback"})
+
+ wantActions(t, duplicateID, "duplicate_marked", "title_changed")
+ wantActions(t, originalID, "duplicate_added")
+ })
+
+ t.Run("reopened, then its original deleted", func(t *testing.T) {
+ duplicateID, originalID := marked(t)
+ raw(t, reopenedByOldServer, duplicateID)
+
+ send(t, "DELETE", originalID, nil)
+
+ wantActions(t, duplicateID, "duplicate_marked")
+ })
+
+ // The mark was live but its original is gone, so there is no duplicate
+ // row to name the move; the status row records it instead.
+ t.Run("original deleted, then reopened", func(t *testing.T) {
+ duplicateID, originalID := marked(t)
+ raw(t, deletedByOldServer, originalID)
+
+ send(t, "PUT", duplicateID, map[string]any{"status": "todo"})
+
+ wantActions(t, duplicateID, "duplicate_marked", "status_changed")
+ wantStatusMove(t, duplicateID, "cancelled", "todo")
+ })
+}
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index 6151f0df35..6d7acf34da 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -1970,8 +1970,8 @@ func (h *Handler) advanceIssueToDone(ctx context.Context, issue db.Issue, worksp
"source": "github_pr_merged",
// Reaching done clears a duplicate mark (MUL-7349); carry both ends so
// the activity log and clients see the mark go.
- "duplicate_of_issue_id": uuidToPtr(updated.DuplicateOfIssueID),
- "prev_duplicate_of_issue_id": uuidToPtr(issue.DuplicateOfIssueID),
+ "duplicate_of_issue_id": liveDuplicateMark(updated.Status, updated.DuplicateOfIssueID),
+ "prev_duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),
})
}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 28bfbd0696..f453d546fe 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -354,7 +354,11 @@ func validateIssueEnum(w http.ResponseWriter, field, value string, allowed []str
// Resolver includes ARCHIVED statuses, because an issue left on an archived
// status still belongs in its category's column. (MUL-6243)
func (h *Handler) fillStatusCategories(ctx context.Context, wsID pgtype.UUID, resps []IssueResponse) {
- fill := h.newStatusCategoryFiller(ctx, wsID)
+ var originals []pgtype.UUID
+ for i := range resps {
+ originals = appendDuplicateOriginal(originals, resps[i].Status, resps[i].duplicateOfIssueID)
+ }
+ fill := h.newStatusCategoryFiller(ctx, wsID, originals...)
for i := range resps {
fill(&resps[i])
}
@@ -365,16 +369,22 @@ func (h *Handler) fillStatusCategories(ctx context.Context, wsID pgtype.UUID, re
// the catalog at most once, so a page of custom-status rows costs one query
// rather than one per row. Creating a filler per row would reintroduce the N+1
// this exists to avoid. (MUL-6243)
-func (h *Handler) newStatusCategoryFiller(ctx context.Context, wsID pgtype.UUID) func(*IssueResponse) {
+//
+// originals are the duplicate originals the caller's rows point at, collected
+// with appendDuplicateOriginal. A page passes them so they resolve in one read
+// up front, the way labelsByIssue loads a page's labels; an original that was
+// not passed still resolves, one read per distinct original. (MUL-7349)
+func (h *Handler) newStatusCategoryFiller(ctx context.Context, wsID pgtype.UUID, originals ...pgtype.UUID) func(*IssueResponse) {
resolver := issuestatus.NewResolver(wsID)
- originals := map[pgtype.UUID]*IssueRefResponse{}
+ refs := duplicateOriginals{}
+ h.loadDuplicateOriginals(ctx, wsID, refs, originals)
return func(resp *IssueResponse) {
if resp == nil {
return
}
// Every response that resolves its status also resolves its duplicate
// mark, so the two never disagree about which endpoints carry them.
- h.fillDuplicateOf(ctx, wsID, resp, originals)
+ h.fillDuplicateOf(ctx, wsID, resp, refs)
if resp.StatusCategory != "" {
return
}
@@ -402,39 +412,66 @@ func duplicateOfPointer(status string, id pgtype.UUID) pgtype.UUID {
return id
}
-// fillDuplicateOf resolves a duplicate mark to its original (MUL-7349): a
-// primary-key read per distinct original, memoised in memo across one
-// response so many duplicates of one issue cost one read. A missing original
-// (memoised as nil) leaves DuplicateOf unset.
-func (h *Handler) fillDuplicateOf(ctx context.Context, wsID pgtype.UUID, resp *IssueResponse, memo map[pgtype.UUID]*IssueRefResponse) {
- if !resp.duplicateOfIssueID.Valid {
- return
+// duplicateOriginals memoises the originals a request's duplicates point at,
+// by id. A nil entry is an original that no longer exists (or could not be
+// read), so it is looked up once and then left off every response.
+type duplicateOriginals map[pgtype.UUID]*db.ListIssueRefsInWorkspaceRow
+
+// appendDuplicateOriginal adds the original a row points at, if the row
+// carries a live duplicate mark.
+func appendDuplicateOriginal(originals []pgtype.UUID, status string, id pgtype.UUID) []pgtype.UUID {
+ if pointer := duplicateOfPointer(status, id); pointer.Valid {
+ return append(originals, pointer)
}
- ref, seen := memo[resp.duplicateOfIssueID]
- if !seen {
- row, err := h.Queries.GetIssueRefInWorkspace(ctx, db.GetIssueRefInWorkspaceParams{
- ID: resp.duplicateOfIssueID,
- WorkspaceID: wsID,
- })
- switch {
- case err == nil:
- // The response already rendered its own identifier with the
- // workspace prefix; the original shares it.
- prefix := strings.TrimSuffix(resp.Identifier, "-"+strconv.Itoa(int(resp.Number)))
- ref = &IssueRefResponse{
- ID: uuidToString(row.ID),
- Identifier: prefix + "-" + strconv.Itoa(int(row.Number)),
- Title: row.Title,
- Status: row.Status,
- }
- case !isNotFound(err):
- slog.Warn("resolve duplicate original failed", "error", err, "issue_id", resp.ID)
+ return originals
+}
+
+// loadDuplicateOriginals reads every id not yet in refs in one query.
+func (h *Handler) loadDuplicateOriginals(ctx context.Context, wsID pgtype.UUID, refs duplicateOriginals, ids []pgtype.UUID) {
+ var missing []pgtype.UUID
+ for _, id := range ids {
+ if _, seen := refs[id]; !seen {
+ refs[id] = nil
+ missing = append(missing, id)
}
- memo[resp.duplicateOfIssueID] = ref
}
- if ref != nil {
- copied := *ref
- resp.DuplicateOf = &copied
+ if len(missing) == 0 {
+ return
+ }
+ rows, err := h.Queries.ListIssueRefsInWorkspace(ctx, db.ListIssueRefsInWorkspaceParams{
+ WorkspaceID: wsID,
+ Ids: missing,
+ })
+ if err != nil {
+ slog.Warn("resolve duplicate originals failed", "error", err, "count", len(missing))
+ return
+ }
+ for i := range rows {
+ refs[rows[i].ID] = &rows[i]
+ }
+}
+
+// fillDuplicateOf resolves a duplicate mark to its original (MUL-7349),
+// through refs so a page's originals cost one read (see
+// newStatusCategoryFiller). A missing original leaves DuplicateOf unset.
+func (h *Handler) fillDuplicateOf(ctx context.Context, wsID pgtype.UUID, resp *IssueResponse, refs duplicateOriginals) {
+ id := resp.duplicateOfIssueID
+ if !id.Valid {
+ return
+ }
+ h.loadDuplicateOriginals(ctx, wsID, refs, []pgtype.UUID{id})
+ row := refs[id]
+ if row == nil {
+ return
+ }
+ // The response already rendered its own identifier with the workspace
+ // prefix; the original shares it.
+ prefix := strings.TrimSuffix(resp.Identifier, "-"+strconv.Itoa(int(resp.Number)))
+ resp.DuplicateOf = &IssueRefResponse{
+ ID: uuidToString(row.ID),
+ Identifier: prefix + "-" + strconv.Itoa(int(row.Number)),
+ Title: row.Title,
+ Status: row.Status,
}
}
@@ -1189,7 +1226,11 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {
}
prefix := h.getIssuePrefix(ctx, wsUUID)
- fillSearch := h.newStatusCategoryFiller(ctx, wsUUID)
+ var originals []pgtype.UUID
+ for _, sr := range results {
+ originals = appendDuplicateOriginal(originals, sr.issue.Status, sr.issue.DuplicateOfIssueID)
+ }
+ fillSearch := h.newStatusCategoryFiller(ctx, wsUUID, originals...)
resp := make([]SearchIssueResponse, len(results))
for i, sr := range results {
sir := SearchIssueResponse{
@@ -1357,11 +1398,13 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
prefix := h.getIssuePrefix(ctx, wsUUID)
ids := make([]pgtype.UUID, len(issues))
+ var originals []pgtype.UUID
for i, issue := range issues {
ids[i] = issue.ID
+ originals = appendDuplicateOriginal(originals, issue.Status, issue.DuplicateOfIssueID)
}
labelsMap := h.labelsByIssue(ctx, wsUUID, ids)
- fillOpen := h.newStatusCategoryFiller(ctx, wsUUID)
+ fillOpen := h.newStatusCategoryFiller(ctx, wsUUID, originals...)
resp := make([]IssueResponse, len(issues))
for i, issue := range issues {
resp[i] = openIssueRowToResponse(issue, prefix)
@@ -2385,14 +2428,16 @@ ORDER BY
}
ids := make([]pgtype.UUID, len(groupedRows))
+ var originals []pgtype.UUID
for i, row := range groupedRows {
ids[i] = row.ID
+ originals = appendDuplicateOriginal(originals, row.Status, row.DuplicateOfIssueID)
}
labelsMap := h.labelsByIssue(ctx, wsUUID, ids)
prefix := h.getIssuePrefix(ctx, wsUUID)
// One Resolver for the whole page — a per-row filler would query the
// catalog once per custom-status row. (MUL-6243)
- fillGrouped := h.newStatusCategoryFiller(ctx, wsUUID)
+ fillGrouped := h.newStatusCategoryFiller(ctx, wsUUID, originals...)
groups := []IssueAssigneeGroupResponse{}
groupIndex := map[string]int{}
@@ -3999,10 +4044,10 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
"prev_description": textToPtr(prevIssue.Description),
"creator_type": prevIssue.CreatorType,
"creator_id": uuidToString(prevIssue.CreatorID),
- // The duplicate mark is not on IssueResponse, so both ends of a
- // change ride here for clients refreshing the two issues' relations.
- "duplicate_of_issue_id": uuidToPtr(issue.DuplicateOfIssueID),
- "prev_duplicate_of_issue_id": uuidToPtr(prevIssue.DuplicateOfIssueID),
+ // Both ends of a mark change ride here: the activity log records it
+ // and clients refresh the two issues' relations from it.
+ "duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),
+ "prev_duplicate_of_issue_id": liveDuplicateMark(prevIssue.Status, prevIssue.DuplicateOfIssueID),
})
if attachmentsChanged {
// The full owner snapshot must be admitted before an auxiliary event at
@@ -4423,8 +4468,8 @@ func (h *Handler) publishClearedDuplicates(ctx context.Context, cleared []cleare
h.fillStatusCategory(ctx, c.Issue.WorkspaceID, &response)
h.publish(protocol.EventIssueUpdated, uuidToString(c.Issue.WorkspaceID), actorType, actorID, map[string]any{
"issue": response,
- "duplicate_of_issue_id": uuidToPtr(c.Issue.DuplicateOfIssueID),
- "prev_duplicate_of_issue_id": uuidToPtr(c.Original.ID),
+ "duplicate_of_issue_id": liveDuplicateMark(c.Issue.Status, c.Issue.DuplicateOfIssueID),
+ "prev_duplicate_of_issue_id": liveDuplicateMark(c.Issue.Status, c.Original.ID),
"prev_duplicate_of_identifier": prefix + "-" + strconv.Itoa(int(c.Original.Number)),
})
}
@@ -4753,8 +4798,8 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
"status_changed": statusChanged,
"priority_changed": priorityChanged,
"project_changed": projectChanged,
- "duplicate_of_issue_id": uuidToPtr(issue.DuplicateOfIssueID),
- "prev_duplicate_of_issue_id": uuidToPtr(prevIssue.DuplicateOfIssueID),
+ "duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),
+ "prev_duplicate_of_issue_id": liveDuplicateMark(prevIssue.Status, prevIssue.DuplicateOfIssueID),
})
// Reassignment does not cancel existing tasks (#4963 / MUL-4113) —
diff --git a/server/internal/handler/issue_duplicate.go b/server/internal/handler/issue_duplicate.go
index 9fda57ab2d..d5de58d8ba 100644
--- a/server/internal/handler/issue_duplicate.go
+++ b/server/internal/handler/issue_duplicate.go
@@ -127,6 +127,14 @@ func writeDuplicateMarkError(w http.ResponseWriter, err error) bool {
return true
}
+// liveDuplicateMark renders one end of a mark change for an issue:updated
+// payload: the pointer only while it counts, i.e. the issue is cancelled. A
+// pointer an older server left on a reopened issue is no mark, so a write
+// that clears it is not a mark being removed.
+func liveDuplicateMark(status string, id pgtype.UUID) *string {
+ return uuidToPtr(duplicateOfPointer(status, id))
+}
+
// ListIssueDuplicates returns both sides of an issue's duplicate relation: the
// original it duplicates, if any, and the issues marked as its duplicates.
func (h *Handler) ListIssueDuplicates(w http.ResponseWriter, r *http.Request) {
diff --git a/server/internal/handler/issue_duplicate_originals_test.go b/server/internal/handler/issue_duplicate_originals_test.go
new file mode 100644
index 0000000000..1af8373328
--- /dev/null
+++ b/server/internal/handler/issue_duplicate_originals_test.go
@@ -0,0 +1,186 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// A page resolves the originals its duplicates point at in one read, the way
+// it loads their labels (MUL-7349). Per-row reads made a page of N duplicates
+// of N different issues cost N extra round trips.
+
+const (
+ queryIssueRefs = "-- name: ListIssueRefsInWorkspace :many"
+ queryIssueRef = "-- name: GetIssueRefInWorkspace :one"
+)
+
+// issueRefSpy passes every statement through to the real pool and records the
+// original lookups: how many ids each batched read was given, and how many
+// single reads ran.
+type issueRefSpy struct {
+ inner db.DBTX
+
+ mu sync.Mutex
+ batchedIDs []int
+ singleReads int
+}
+
+func (s *issueRefSpy) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
+ return s.inner.Exec(ctx, sql, args...)
+}
+
+func (s *issueRefSpy) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
+ if strings.Contains(sql, queryIssueRefs) {
+ s.mu.Lock()
+ s.batchedIDs = append(s.batchedIDs, uuidArgLen(args, 1))
+ s.mu.Unlock()
+ }
+ return s.inner.Query(ctx, sql, args...)
+}
+
+func (s *issueRefSpy) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ if strings.Contains(sql, queryIssueRef) {
+ s.mu.Lock()
+ s.singleReads++
+ s.mu.Unlock()
+ }
+ return s.inner.QueryRow(ctx, sql, args...)
+}
+
+func (s *issueRefSpy) reset() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.batchedIDs = nil
+ s.singleReads = 0
+}
+
+func (s *issueRefSpy) snapshot() (batched []int, single int) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return append([]int(nil), s.batchedIDs...), s.singleReads
+}
+
+func TestDuplicateOriginalsResolveInOneReadPerPage(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ spy := &issueRefSpy{inner: testPool}
+ h := New(db.New(spy), testPool, testHandler.Hub, testHandler.Bus, testHandler.EmailService,
+ nil, nil, analytics.NoopClient{}, Config{})
+
+ project := dbfx.Project(t, "dup-originals-page")
+ inProject := func(cols testutil.Cols) testutil.Cols {
+ cols["project_id"] = testutil.Raw("'" + project + "'::uuid")
+ return cols
+ }
+ markedAs := func(title, originalID, status string) string {
+ return dbfx.Issue(t, title, inProject(testutil.Cols{
+ "status": status,
+ "duplicate_of_issue_id": testutil.Raw("'" + originalID + "'::uuid"),
+ }))
+ }
+
+ originals := []string{
+ dbfx.Issue(t, "dup-originals-first"),
+ dbfx.Issue(t, "dup-originals-second"),
+ dbfx.Issue(t, "dup-originals-third"),
+ }
+ gone := "00000000-0000-4000-8000-00000000beef"
+ want := map[string]string{
+ markedAs("dup-originals-needle a", originals[0], "cancelled"): originals[0],
+ markedAs("dup-originals-needle b", originals[1], "cancelled"): originals[1],
+ markedAs("dup-originals-needle c", originals[2], "cancelled"): originals[2],
+ // Shares the first original, so it adds no id to the read.
+ markedAs("dup-originals-needle d", originals[0], "cancelled"): originals[0],
+ // An original an older server deleted is looked up with the rest and
+ // then left off the response.
+ markedAs("dup-originals-needle e", gone, "cancelled"): "",
+ // A pointer an older server left on a reopened issue is no mark, so
+ // it is not looked up at all.
+ markedAs("dup-originals-needle f", originals[1], "todo"): "",
+ }
+ // first, second, third and the deleted one; the shared and reopened
+ // pointers add nothing.
+ const wantIDs = 4
+
+ type page struct {
+ Issues []IssueResponse `json:"issues"`
+ }
+ for _, tc := range []struct {
+ name string
+ call func() page
+ }{
+ {"list", func() page {
+ var out page
+ testutil.Call(t, h.ListIssues, newRequest("GET", "/api/issues?project_id="+project+"&limit=50", nil)).
+ Want(http.StatusOK).JSON(&out)
+ return out
+ }},
+ {"search", func() page {
+ var out page
+ testutil.Call(t, h.SearchIssues, newRequest("GET", "/api/issues/search?q=dup-originals-needle&include_closed=true&limit=50", nil)).
+ Want(http.StatusOK).JSON(&out)
+ return out
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ spy.reset()
+ out := tc.call()
+
+ batched, single := spy.snapshot()
+ if len(batched) != 1 || batched[0] != wantIDs || single != 0 {
+ t.Fatalf("original reads: batched ids per read = %v, single reads = %d; want one read of %d ids and none single",
+ batched, single, wantIDs)
+ }
+
+ var seen []string
+ for _, issue := range out.Issues {
+ wantOriginal, ok := want[issue.ID]
+ if !ok {
+ continue
+ }
+ seen = append(seen, issue.ID)
+ got := ""
+ if issue.DuplicateOf != nil {
+ got = issue.DuplicateOf.ID
+ }
+ if got != wantOriginal {
+ t.Errorf("%s: duplicate_of = %q, want %q", issue.Title, got, wantOriginal)
+ }
+ }
+ if len(seen) != len(want) {
+ sort.Strings(seen)
+ t.Fatalf("page carried %d of the %d seeded issues: %v", len(seen), len(want), seen)
+ }
+ })
+ }
+}
+
+// A response built on its own, with nothing passed up front, still resolves
+// its original.
+func TestDuplicateOriginalResolvesWithoutPriming(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ original := dbfx.Issue(t, "dup-unprimed-original")
+ duplicate := seedDuplicate(t, "dup-unprimed-duplicate", original)
+ row, err := testHandler.Queries.GetIssue(context.Background(), parseUUID(duplicate))
+ if err != nil {
+ t.Fatalf("GetIssue: %v", err)
+ }
+ resp := issueToResponse(row, "MUL")
+ testHandler.newStatusCategoryFiller(context.Background(), row.WorkspaceID)(&resp)
+ if resp.DuplicateOf == nil || resp.DuplicateOf.ID != original {
+ t.Fatalf("duplicate_of = %+v, want %s", resp.DuplicateOf, original)
+ }
+}
diff --git a/server/internal/handler/issue_payload_shape_test.go b/server/internal/handler/issue_payload_shape_test.go
index 1fd8645636..3809599de5 100644
--- a/server/internal/handler/issue_payload_shape_test.go
+++ b/server/internal/handler/issue_payload_shape_test.go
@@ -1,13 +1,16 @@
package handler
import (
+ "context"
"encoding/json"
+ "reflect"
"sort"
"testing"
"time"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -181,3 +184,42 @@ func hasKey(keys []string, key string) bool {
}
return false
}
+
+// Events published outside the handler render the issue through
+// service.IssueToMapResolved. Its duplicate_of must match the HTTP rendering
+// exactly: clients patch the same cache entry from both.
+func TestResolvedBroadcastDuplicateOfMatchesResponse(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ original := dbfx.Issue(t, "dup-broadcast-original", testutil.Cols{"status": "in_review"})
+ duplicate := seedDuplicate(t, "dup-broadcast-duplicate", original)
+ row, err := testHandler.Queries.GetIssue(ctx, parseUUID(duplicate))
+ if err != nil {
+ t.Fatalf("GetIssue: %v", err)
+ }
+ prefix := testHandler.getIssuePrefix(ctx, row.WorkspaceID)
+
+ resp := issueToResponse(row, prefix)
+ testHandler.fillStatusCategory(ctx, row.WorkspaceID, &resp)
+ if resp.DuplicateOf == nil {
+ t.Fatal("HTTP rendering lost the mark")
+ }
+ decode := func(v any) map[string]any {
+ raw, err := json.Marshal(v)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var out map[string]any
+ if err := json.Unmarshal(raw, &out); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ return out
+ }
+ fromResponse := decode(resp.DuplicateOf)
+ fromBroadcast := decode(service.IssueToMapResolved(ctx, testHandler.Queries, row, prefix)["duplicate_of"])
+ if !reflect.DeepEqual(fromBroadcast, fromResponse) {
+ t.Fatalf("broadcast duplicate_of = %v, HTTP duplicate_of = %v", fromBroadcast, fromResponse)
+ }
+}
diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.go
index a410e9232f..5ec8fef955 100644
--- a/server/internal/handler/issue_table_rows.go
+++ b/server/internal/handler/issue_table_rows.go
@@ -501,12 +501,15 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
prefix := baseHandler.getIssuePrefix(r.Context(), compiled.workspaceID)
issueIDs := make([]pgtype.UUID, len(scanned))
+ var originals []pgtype.UUID
for index, row := range scanned {
issueIDs[index] = row.issue.ID
+ originals = appendDuplicateOriginal(originals, row.issue.Status, row.issue.DuplicateOfIssueID)
}
labelsByIssue := baseHandler.labelsByIssue(r.Context(), compiled.workspaceID, issueIDs)
- // One Resolver for the page — see newStatusCategoryFiller. (MUL-6243)
- fillTableRow := baseHandler.newStatusCategoryFiller(r.Context(), compiled.workspaceID)
+ // One Resolver and one originals read for the page — see
+ // newStatusCategoryFiller. (MUL-6243, MUL-7349)
+ fillTableRow := baseHandler.newStatusCategoryFiller(r.Context(), compiled.workspaceID, originals...)
responseRows := make([]issueTableRowResponse, len(scanned))
for index, row := range scanned {
issue := issueListRowToResponse(row.issue, prefix)
diff --git a/server/internal/service/issue_channel_media_test.go b/server/internal/service/issue_channel_media_test.go
index 3258bd51d1..1174353d5c 100644
--- a/server/internal/service/issue_channel_media_test.go
+++ b/server/internal/service/issue_channel_media_test.go
@@ -539,3 +539,95 @@ func TestHydrateDeferredChannelIssueTaskOverlayDoesNotOverwriteMergedCommentPlan
t.Fatalf("runtime_mcp_overlay = %s, want merged overlay %s", storedOverlay, mergedOverlay)
}
}
+
+// The channel router publishes this snapshot for the issue it created, but
+// the media download gives others up to DefaultMediaTimeout to act on it. A
+// duplicate mark made in that window is on the row the snapshot reads, and
+// clients patch their cache with the snapshot, so it must carry the mark
+// rather than a null that erases it (MUL-7349).
+func TestPublishAttachmentsChangedKeepsDuplicateMark(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, _, issueID := seedAttributionFixture(t, pool)
+ workspaceUUID := util.MustParseUUID(workspaceID)
+ created, err := q.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{
+ ID: util.MustParseUUID(issueID), WorkspaceID: workspaceUUID,
+ })
+ if err != nil {
+ t.Fatalf("load issue: %v", err)
+ }
+ var originalID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, number, title, creator_type, creator_id, priority, status)
+ VALUES ($1, (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1),
+ 'attr original', 'member', $2, 'none', 'in_progress')
+ RETURNING id`, workspaceID, userID).Scan(&originalID); err != nil {
+ t.Fatalf("seed original: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, originalID) })
+ original, err := q.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{
+ ID: util.MustParseUUID(originalID), WorkspaceID: workspaceUUID,
+ })
+ if err != nil {
+ t.Fatalf("load original: %v", err)
+ }
+ workspace, err := q.GetWorkspace(ctx, workspaceUUID)
+ if err != nil {
+ t.Fatalf("load workspace: %v", err)
+ }
+
+ for _, tc := range []struct {
+ name string
+ status string
+ want bool
+ }{
+ {"marked during the download", "cancelled", true},
+ // A pointer an older server left on a reopened issue is no mark.
+ {"pointer left on a reopened issue", "todo", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if _, err := pool.Exec(ctx, `UPDATE issue SET status = $1, duplicate_of_issue_id = $2 WHERE id = $3`,
+ tc.status, originalID, issueID); err != nil {
+ t.Fatalf("mark: %v", err)
+ }
+ bus := events.New()
+ svc := &IssueService{Bus: bus, Queries: q}
+ var updated events.Event
+ bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) { updated = e })
+
+ svc.PublishAttachmentsChanged(ctx, created, util.MustParseUUID(userID))
+
+ payload, _ := updated.Payload.(map[string]any)
+ snapshot, ok := payload["issue"].(map[string]any)
+ if !ok {
+ t.Fatalf("issue update payload = %#v", updated.Payload)
+ }
+ value, present := snapshot["duplicate_of"]
+ if !present {
+ t.Fatal("snapshot has no duplicate_of key")
+ }
+ ref, _ := value.(map[string]any)
+ if !tc.want {
+ if ref != nil {
+ t.Fatalf("duplicate_of = %v, want null", ref)
+ }
+ return
+ }
+ want := map[string]any{
+ "id": originalID,
+ "identifier": IssueIdentifier(workspace.IssuePrefix, original.Number),
+ "title": "attr original",
+ "status": "in_progress",
+ }
+ if len(ref) != len(want) {
+ t.Fatalf("duplicate_of = %v, want %v", ref, want)
+ }
+ for k, v := range want {
+ if ref[k] != v {
+ t.Fatalf("duplicate_of = %v, want %v", ref, want)
+ }
+ }
+ })
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index b85482e515..e1d57f84c0 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -7581,6 +7581,13 @@ func builtInStatusCategory(status string) string {
return ""
}
+// IssueMapQuerier is what IssueToMapResolved reads: the status catalog and,
+// for a duplicate, its original.
+type IssueMapQuerier interface {
+ issuestatus.Querier
+ GetIssueRefInWorkspace(ctx context.Context, arg db.GetIssueRefInWorkspaceParams) (db.GetIssueRefInWorkspaceRow, error)
+}
+
// IssueToMapResolved is IssueToMap with an AUTHORITATIVE status_category and
// status_name, both resolved through the catalog so a custom status is not
// emitted with blanks. Background events go through here; clients treat this
@@ -7589,14 +7596,47 @@ func builtInStatusCategory(status string) string {
// Both fields come from ONE catalog read. Resolving them separately would
// double the query on every event carrying a custom status, and the HTTP
// rendering already shares a single read through its Resolver. (MUL-6749)
-func IssueToMapResolved(ctx context.Context, q issuestatus.Querier, issue db.Issue, issuePrefix string) map[string]any {
+//
+// duplicate_of is resolved too: a client patches its cache with this
+// snapshot, so a null here would erase a mark the issue still carries
+// (MUL-7349). Only a cancelled issue with a pointer costs a read.
+func IssueToMapResolved(ctx context.Context, q IssueMapQuerier, issue db.Issue, issuePrefix string) map[string]any {
m := IssueToMap(issue, issuePrefix)
category, name := issuestatus.CategoryAndName(ctx, q, issue.WorkspaceID, issue.Status)
m["status_category"] = issuestatus.WireCategory(issue.Status, category)
m["status_name"] = name
+ if ref := resolveDuplicateOf(ctx, q, issue, issuePrefix); ref != nil {
+ m["duplicate_of"] = ref
+ }
return m
}
+// resolveDuplicateOf renders the original a duplicate points at, in the shape
+// of handler.IssueRefResponse, or nil when the issue carries no live mark: it
+// is not cancelled, has no pointer, or its original is gone.
+func resolveDuplicateOf(ctx context.Context, q IssueMapQuerier, issue db.Issue, issuePrefix string) map[string]any {
+ if issue.Status != issuestatus.Cancelled || !issue.DuplicateOfIssueID.Valid {
+ return nil
+ }
+ row, err := q.GetIssueRefInWorkspace(ctx, db.GetIssueRefInWorkspaceParams{
+ ID: issue.DuplicateOfIssueID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ if !errors.Is(err, pgx.ErrNoRows) {
+ slog.Warn("resolve duplicate original failed",
+ "issue_id", util.UUIDToString(issue.ID), "error", err)
+ }
+ return nil
+ }
+ return map[string]any{
+ "id": util.UUIDToString(row.ID),
+ "identifier": IssueIdentifier(issuePrefix, row.Number),
+ "title": row.Title,
+ "status": row.Status,
+ }
+}
+
func IssueToMap(issue db.Issue, issuePrefix string) map[string]any {
return map[string]any{
"id": util.UUIDToString(issue.ID),
@@ -7621,9 +7661,8 @@ func IssueToMap(issue db.Issue, issuePrefix string) map[string]any {
"creator_type": issue.CreatorType,
"creator_id": util.UUIDToString(issue.CreatorID),
"parent_issue_id": util.UUIDToPtr(issue.ParentIssueID),
- // Mirrors handler.IssueResponse.DuplicateOf. The paths that render this
- // map (autopilot creates, background status resets) never carry a live
- // duplicate mark, and a reset clears one, so null is the true value.
+ // Mirrors handler.IssueResponse.DuplicateOf. Null is only true for a
+ // row with no live mark; IssueToMapResolved resolves it for the rest.
"duplicate_of": nil,
"project_id": util.UUIDToPtr(issue.ProjectID),
"position": issue.Position,
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 4a0deade45..7ed7830626 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -1324,6 +1324,51 @@ func (q *Queries) ListIssueGCStatuses(ctx context.Context, arg ListIssueGCStatus
return items, nil
}
+const listIssueRefsInWorkspace = `-- name: ListIssueRefsInWorkspace :many
+SELECT id, number, title, status FROM issue
+WHERE workspace_id = $1
+ AND id = ANY($2::uuid[])
+`
+
+type ListIssueRefsInWorkspaceParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ids []pgtype.UUID `json:"ids"`
+}
+
+type ListIssueRefsInWorkspaceRow struct {
+ ID pgtype.UUID `json:"id"`
+ Number int32 `json:"number"`
+ Title string `json:"title"`
+ Status string `json:"status"`
+}
+
+// GetIssueRefInWorkspace for a page: every original the page's duplicates
+// point at, in one read.
+func (q *Queries) ListIssueRefsInWorkspace(ctx context.Context, arg ListIssueRefsInWorkspaceParams) ([]ListIssueRefsInWorkspaceRow, error) {
+ rows, err := q.db.Query(ctx, listIssueRefsInWorkspace, arg.WorkspaceID, arg.Ids)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListIssueRefsInWorkspaceRow{}
+ for rows.Next() {
+ var i ListIssueRefsInWorkspaceRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.Number,
+ &i.Title,
+ &i.Status,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listIssues = `-- name: ListIssues :many
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 0de8e7f182..0bc41314c0 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -384,6 +384,13 @@ ORDER BY created_at ASC, id ASC;
SELECT id, number, title, status FROM issue
WHERE id = $1 AND workspace_id = $2;
+-- name: ListIssueRefsInWorkspace :many
+-- GetIssueRefInWorkspace for a page: every original the page's duplicates
+-- point at, in one read.
+SELECT id, number, title, status FROM issue
+WHERE workspace_id = sqlc.arg('workspace_id')
+ AND id = ANY(sqlc.arg('ids')::uuid[]);
+
-- name: ClearIssueDuplicatesOf :many
-- Deleting an issue clears the pointers of its duplicates, the way deleting a
-- parent detaches its children. They stay cancelled. Issues deleted in the