Files
multica/server/internal/handler/comment_resolve_test.go
14c2e4e831 MUL-6243 feat(issue-status): board fetches by category; archive retires without migration (#7084)
* feat(issue-status): board fetches by category; archive retires without migration (MUL-6243)

Product decisions from the issue thread:

1. Board fetches by CATEGORY, not per status. PAGINATED_STATUSES becomes
   PAGINATED_CATEGORIES and the cache buckets by category, so the board's
   fan-out stays fixed at 7 parallel requests however many custom statuses a
   workspace defines — instead of one more request per status added. Adds
   status_category / status_categories filters to the issue list endpoints,
   backed by the existing issue_effective_status() SQL function.

3. Archiving retires a status from FUTURE use only. It no longer refuses while
   issues still carry it: those issues keep their status and keep resolving to
   their category's behavior (Effective ignores archived_at), while Resolve
   still rejects the status so nothing new can be assigned to it. The exclusive
   catalog lock stays — it is what makes "no NEW assignment after archive"
   exact rather than approximate.

Also lands the frontend catalog foundation: packages/core/issue-statuses with
useIssueStatuses(wsId) (React Query, keyed by wsId per the state rules) and a
pure buildIssueStatusCatalog for non-React callers, plus IssueStatusCategory as
a distinct type from the status key and status_category on issue payloads.

NOT included, and deliberately: widening IssueStatus to string. That change
forces every Record<IssueStatus, …> presentation lookup in packages/views to
resolve a key to its category first, and it is the first task of the follow-up
PR. Everything here is the groundwork that makes it mechanical.

Co-authored-by: multica-agent <[email protected]>

* fix(issue-status): restore the status index, make category authoritative, keep archived resolvable

Review round 1 on #7084 (MUL-6243):

1. Category filtering wrapped issue.status in issue_effective_status(), which
   makes the (workspace_id, status) index unusable — and the board switched to
   it unconditionally, so every workspace paid for it immediately. Categories
   are now expanded to concrete status keys (issuestatus.ExpandCategories) and
   filtered with an indexed status = ANY(...). Measured on a 100k-row table
   with the production index: seq scan cost 27013 -> index-only scan cost 6.07.
   A workspace with no custom statuses expands each category to exactly its own
   key, reproducing the pre-feature query. Archived keys are included, since
   issues left on them still belong in their category's column.

2. status_category was only filled for built-ins, so a custom-status issue
   arriving over the websocket was silently dropped by addIssueToBuckets and a
   cross-category update was skipped by the cache coordinator, drifting
   off-window totals permanently. List, grouped, get, create, update and batch
   responses now carry an authoritative category via a per-request Resolver
   (archived included), and the client invalidates instead of no-oping when a
   category is unresolvable.

3. The catalog was fetched without archived entries, so after archiving a
   status the issues still on it lost their name and colour and had their
   category guessed as todo — contradicting the decision that archiving leaves
   existing issues untouched. Resolution now includes archived entries;
   activeStatuses / inCategory expose only assignable ones to pickers.

Co-authored-by: multica-agent <[email protected]>

* fix(issue-status): category on every payload exit, one resolver per request, no same-category duplication

Review round 2 on #7084 (MUL-6243):

1. Category fill was incomplete and N+1. The create WEBSOCKET payload was
   unfilled — only the creator's HTTP response was, which is too late for the
   other tabs the event exists to serve. GetIssue, the open_only list, search,
   the duplicate-conflict response, the table rows, the GitHub PR update and
   the onboarding shim were also unfilled. Grouped and batch called the
   single-response helper per row, so each custom-status row hit the catalog
   separately.

   Every exit now goes through newStatusCategoryFiller, a request-scoped
   closure over ONE Resolver: built-in statuses still cost no query, and a page
   of custom-status rows costs one catalog read rather than one per row.

2. A status KEY change within one category duplicated the card and inflated the
   total. patchIssueInBuckets compared patch.status (a key) against loc.status
   (a bucket CATEGORY), so in_review -> a custom human_review took the
   cross-bucket path, then deleted from and re-inserted into the same bucket
   from a pre-delete snapshot. It now resolves the destination category first
   and compares category to category; same-category changes replace in place
   and leave the total alone.

   The destination category is resolved from the patch alone — the merged issue
   inherits the previous status_category, which would have kept a genuinely
   moved card in its old column. patchNeedsInvalidation lets the loaded branch
   of the cache coordinator invalidate instead of silently no-oping on a status
   it cannot resolve.

Also drops the unrelated share_link.sql.go churn from an sqlc version
difference, per the review nit.

The four cache cases were verified to fail against the previous logic (card
duplicated, total +1) before the fix was restored.

Co-authored-by: multica-agent <[email protected]>

* fix(issue-status): normalize status_category on every cache write; one filler per create

Review round 3 on #7084 (MUL-6243):

Must-fix — a cached entity kept the STALE status_category after a status
change. The server now sends a category on every issue, so a cached entity is
{status: "todo", status_category: "todo"}; an optimistic patch carries only
{status: "done"}, and a bare {...issue, ...patch} moved the card to the done
bucket while the entity still claimed todo. A single update self-heals from the
server response, but the batch API returns only {updated: n} and does not
refetch bucketed lists, so the inconsistency was permanent — and the next
off-window count then decremented the wrong bucket, recreating total drift.

normalizeStatusPatch now rewrites status_category to match status before any
cache write, applied at applyIssueChange's entry (covering the flat, table and
detail spreads), in patchIssueInBuckets, and in the children mutation. An
unresolvable custom key drops the inherited category rather than keeping it;
patchNeedsInvalidation still routes it to a refetch.

Test fixtures now carry status_category for built-ins, matching what the server
actually sends — without that the regression was invisible.

Non-blocking items also addressed:
- CreateIssue builds one filler and shares it between the broadcast payload and
  the HTTP response, so a custom-status create reads the catalog once.
- Background events via IssueToMap now resolve an authoritative category
  (IssueToMapWithCategory) for the task, issue and autopilot publishers. The
  channel router keeps plain IssueToMap and says why: it always creates with the
  built-in "todo", where key IS category.

The "one resolver serves a whole page" assertion was REMOVED rather than kept:
pg_stat counters lag, so a delta around one request passes even with a per-row
filler. Verified that directly before dropping it. The comment now states what
is and is not pinned instead of implying coverage that does not exist.

Co-authored-by: multica-agent <[email protected]>

* fix(issue-status): address review nits

- Normalize the single-update children optimistic patch too, matching the batch
  path. It self-healed on onSettled, but it broke the entity/bucket invariant
  for the duration of the request.
- Rename TestListEndpointsCarryStatusCategory: the old name claimed it covered
  "without per row queries", which the test explicitly does not assert.
- Drop the unrelated gofmt churn in empty_claim_cache.go.
- Add a background-event assertion: IssueToMap leaves a custom status
  uncategorized, IssueToMapWithCategory resolves it — the reason the publishers
  use the latter.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-18 03:00:21 +08:00

255 lines
8.0 KiB
Go

package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/pkg/protocol"
)
// resolveCommentHTTP drives the POST /api/comments/{id}/resolve handler and
// returns the decoded response. Mirrors the resolve path the web/desktop client
// hits.
func resolveCommentHTTP(t *testing.T, commentID string) CommentResponse {
t.Helper()
w := httptest.NewRecorder()
r := newRequest("POST", "/api/comments/"+commentID+"/resolve", nil)
r = withURLParam(r, "commentId", commentID)
testHandler.ResolveComment(w, r)
if w.Code != http.StatusOK {
t.Fatalf("resolve %s: status %d: %s", commentID, w.Code, w.Body.String())
}
var resp CommentResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode resolve response: %v", err)
}
return resp
}
// commentResolved reports whether a comment currently has resolved_at set,
// read straight from the row so the assertion sees committed state.
func commentResolved(t *testing.T, id string) bool {
t.Helper()
var resolvedAt *time.Time
if err := testPool.QueryRow(context.Background(),
`SELECT resolved_at FROM comment WHERE id = $1`, id,
).Scan(&resolvedAt); err != nil {
t.Fatalf("query resolved_at for %s: %v", id, err)
}
return resolvedAt != nil
}
// commentResolvedAt returns the raw resolved_at timestamp (nil when cleared).
func commentResolvedAt(t *testing.T, id string) *time.Time {
t.Helper()
var resolvedAt *time.Time
if err := testPool.QueryRow(context.Background(),
`SELECT resolved_at FROM comment WHERE id = $1`, id,
).Scan(&resolvedAt); err != nil {
t.Fatalf("query resolved_at for %s: %v", id, err)
}
return resolvedAt
}
// commentEventCapture records comment:resolved / comment:unresolved events for a
// single issue. The handler bus has no Unsubscribe, so the closure filters by
// issue id; events for other tests' issues are ignored.
type commentEventCapture struct {
mu sync.Mutex
events []struct {
Type string
CommentID string
}
}
func captureCommentEvents(t *testing.T, issueID string) *commentEventCapture {
t.Helper()
cap := &commentEventCapture{}
record := func(e events.Event) {
m, ok := e.Payload.(map[string]any)
if !ok {
return
}
c, ok := m["comment"].(CommentResponse)
if !ok || c.IssueID != issueID {
return
}
cap.mu.Lock()
cap.events = append(cap.events, struct {
Type string
CommentID string
}{e.Type, c.ID})
cap.mu.Unlock()
}
testHandler.Bus.Subscribe(protocol.EventCommentResolved, record)
testHandler.Bus.Subscribe(protocol.EventCommentUnresolved, record)
return cap
}
func (c *commentEventCapture) countFor(eventType, commentID string) int {
c.mu.Lock()
defer c.mu.Unlock()
n := 0
for _, e := range c.events {
if e.Type == eventType && e.CommentID == commentID {
n++
}
}
return n
}
// resolveTestFixture seeds an issue with two independent threads so the tests
// can prove the single-resolution invariant is thread-scoped, not issue-scoped:
//
// root1
// ├── a1
// └── b1
// root2 (separate thread)
// └── a2
type resolveTestFixture struct {
IssueID string
Root1 string
A1 string
B1 string
Root2 string
A2 string
}
func newResolveTestFixture(t *testing.T) resolveTestFixture {
t.Helper()
ctx := context.Background()
var issueID string
if err := testPool.QueryRow(ctx, `
INSERT INTO issue (workspace_id, creator_type, creator_id, title)
VALUES ($1, 'member', $2, $3)
RETURNING id
`, testWorkspaceID, testUserID, "resolve fixture").Scan(&issueID); err != nil {
t.Fatalf("create issue: %v", err)
}
t.Cleanup(func() {
testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
})
base := time.Now().UTC().Add(-1 * time.Hour).Truncate(time.Second)
insert := func(parent *string, offset time.Duration, body string) string {
t.Helper()
var id string
if err := testPool.QueryRow(ctx, `
INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, created_at)
VALUES ($1, $2, 'member', $3, $4, 'comment', $5, $6)
RETURNING id
`, issueID, testWorkspaceID, testUserID, body, parent, base.Add(offset)).Scan(&id); err != nil {
t.Fatalf("insert comment %q: %v", body, err)
}
return id
}
root1 := insert(nil, 0, "root1")
a1 := insert(&root1, 1*time.Minute, "a1")
b1 := insert(&root1, 2*time.Minute, "b1")
root2 := insert(nil, 10*time.Minute, "root2")
a2 := insert(&root2, 11*time.Minute, "a2")
return resolveTestFixture{IssueID: issueID, Root1: root1, A1: a1, B1: b1, Root2: root2, A2: a2}
}
// TestResolveComment_ReplacesPriorThreadResolution is the core regression for
// MUL-3180: a thread must have at most one resolved comment, and resolving a new
// one atomically clears the previous resolution (instead of leaving two resolved
// rows that the UI only papered over).
func TestResolveComment_ReplacesPriorThreadResolution(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
fx := newResolveTestFixture(t)
cap := captureCommentEvents(t, fx.IssueID)
// Resolve a1 → it is the resolution.
resolveCommentHTTP(t, fx.A1)
if !commentResolved(t, fx.A1) {
t.Fatalf("a1 should be resolved after first resolve")
}
// Resolve b1 → b1 becomes the resolution and a1 is cleared in the same write.
resolveCommentHTTP(t, fx.B1)
if !commentResolved(t, fx.B1) {
t.Fatalf("b1 should be resolved")
}
if commentResolved(t, fx.A1) {
t.Fatalf("a1 should have been cleared when b1 was resolved (single-resolution invariant)")
}
// The cleared sibling must broadcast comment:unresolved so granular realtime
// consumers drop the stale resolution; b1 must broadcast comment:resolved.
if got := cap.countFor(protocol.EventCommentUnresolved, fx.A1); got != 1 {
t.Fatalf("expected exactly 1 comment:unresolved for a1, got %d", got)
}
if got := cap.countFor(protocol.EventCommentResolved, fx.B1); got != 1 {
t.Fatalf("expected exactly 1 comment:resolved for b1, got %d", got)
}
}
// TestResolveComment_ScopedToThread proves the clear never reaches across into a
// sibling thread on the same issue.
func TestResolveComment_ScopedToThread(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
fx := newResolveTestFixture(t)
resolveCommentHTTP(t, fx.B1) // thread 1 resolution
resolveCommentHTTP(t, fx.A2) // thread 2 resolution — must NOT touch thread 1
if !commentResolved(t, fx.B1) {
t.Fatalf("b1 (thread 1) must stay resolved when a separate thread is resolved")
}
if !commentResolved(t, fx.A2) {
t.Fatalf("a2 (thread 2) should be resolved")
}
// Resolving the root of thread 1 overrides the reply resolution (override
// works in both directions: reply→reply and reply→root).
resolveCommentHTTP(t, fx.Root1)
if !commentResolved(t, fx.Root1) {
t.Fatalf("root1 should be resolved")
}
if commentResolved(t, fx.B1) {
t.Fatalf("b1 should be cleared when root1 becomes the resolution")
}
if !commentResolved(t, fx.A2) {
t.Fatalf("a2 (other thread) must remain resolved throughout")
}
}
// TestResolveComment_ReResolveIsIdempotent pins the COALESCE idempotency +
// event suppression: re-resolving the current resolution keeps its original
// timestamp and emits no second comment:resolved event.
func TestResolveComment_ReResolveIsIdempotent(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
fx := newResolveTestFixture(t)
cap := captureCommentEvents(t, fx.IssueID)
resolveCommentHTTP(t, fx.A1)
first := commentResolvedAt(t, fx.A1)
if first == nil {
t.Fatalf("a1 should be resolved")
}
resolveCommentHTTP(t, fx.A1) // re-resolve same comment
second := commentResolvedAt(t, fx.A1)
if second == nil || !second.Equal(*first) {
t.Fatalf("re-resolve must keep the original resolved_at (got %v, want %v)", second, first)
}
if got := cap.countFor(protocol.EventCommentResolved, fx.A1); got != 1 {
t.Fatalf("re-resolve no-op must not emit a second comment:resolved (got %d)", got)
}
}