Skip to content

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

Go

MUL-5492: fix timeline cap dropping newest entries + stop double-broadcasting descriptions (#6175)

Multica Evec3f5df8bf438
diff --git a/server/cmd/server/cors_headers_test.go b/server/cmd/server/cors_headers_test.go
index 36fcabf9ee..8e8ae51e66 100644
--- a/server/cmd/server/cors_headers_test.go
+++ b/server/cmd/server/cors_headers_test.go
@@ -4,6 +4,7 @@ import (
"slices"
"testing"
+ "github.com/multica-ai/multica/server/internal/handler"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -21,3 +22,20 @@ func TestCORSAllowedHeaders_IncludeClientCapabilities(t *testing.T) {
t.Fatal("AppCapabilityChatDraftRestoreV1 must be a non-empty capability token")
}
}
+
+// Timeline and comment-list endpoints report defensive hard-cap clamps with
+// custom response headers.
+// Custom response headers are not readable from browser JS unless the server
+// exposes them, and only the CORS-safelisted headers are exposed by default — so
+// an entry missing here is not a degraded signal, it is no signal at all: the
+// header arrives on the wire and the client cannot see it (MUL-5492).
+func TestCORSExposedHeaders_IncludeTruncationSignals(t *testing.T) {
+ for _, want := range []string{
+ handler.HeaderCommentsTruncated,
+ handler.HeaderTimelineTruncated,
+ } {
+ if !slices.Contains(corsExposedHeaders, want) {
+ t.Errorf("%s missing from CORS exposed headers: %v", want, corsExposedHeaders)
+ }
+ }
+}
diff --git a/server/cmd/server/issue_updated_projection_test.go b/server/cmd/server/issue_updated_projection_test.go
new file mode 100644
index 0000000000..74f0051841
--- /dev/null
+++ b/server/cmd/server/issue_updated_projection_test.go
@@ -0,0 +1,170 @@
+package main
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Regression tests for the second half of MUL-5492: `issue:updated` used to
+// broadcast prev_description alongside the new description, so every debounced
+// description autosave pushed TWO full copies of the description to every
+// connection in the workspace — including users who did not have the issue open.
+//
+// The projection has two halves and both must hold: the keys must not reach the
+// wire, AND the in-process listeners that genuinely need them must still see
+// them. A test that only checks the first half would pass just as happily if the
+// producer had stopped populating the keys altogether, which would silently
+// break mention notifications and the title-change activity.
+
+// issueUpdatedPayload mirrors the map published by handler.UpdateIssue, trimmed
+// to the fields these tests care about.
+func issueUpdatedPayload() map[string]any {
+ return map[string]any{
+ "issue": map[string]any{
+ "id": "issue-1",
+ "title": "New title",
+ "description": strings.Repeat("new body ", 1024),
+ },
+ "description_changed": true,
+ "title_changed": true,
+ "prev_title": "Old title",
+ "prev_description": strings.Repeat("old body ", 1024),
+ "prev_status": "todo",
+ }
+}
+
+func TestIssueUpdatedBroadcast_OmitsFullPreviousDescription(t *testing.T) {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+
+ // A type-specific listener stands in for the real in-process consumers
+ // (subscriber_listeners, notification_listeners, activity_listeners). Publish
+ // dispatches these before the SubscribeAll forwarder, so this also pins the
+ // ordering the projection relies on.
+ var seenByListener map[string]any
+ bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {
+ if p, ok := e.Payload.(map[string]any); ok {
+ seenByListener = p
+ }
+ })
+
+ registerListeners(bus, fb)
+
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueUpdated,
+ WorkspaceID: "ws-1",
+ ActorID: "member-1",
+ ActorType: "member",
+ Payload: issueUpdatedPayload(),
+ })
+
+ if len(fb.workspaceCalls) != 1 {
+ t.Fatalf("BroadcastToWorkspace calls = %d, want 1", len(fb.workspaceCalls))
+ }
+ raw := fb.workspaceCalls[0].msg
+
+ // Half 1: the internal-only keys must not be on the wire at all. Assert on
+ // the raw bytes too — a nested copy would still cost the bandwidth this fix
+ // is about, even if the top-level key were gone.
+ if strings.Contains(string(raw), "prev_description") {
+ t.Error("broadcast frame still contains prev_description")
+ }
+ if strings.Contains(string(raw), "prev_title") {
+ t.Error("broadcast frame still contains prev_title")
+ }
+
+ var frame struct {
+ Type string `json:"type"`
+ Payload map[string]any `json:"payload"`
+ }
+ if err := json.Unmarshal(raw, &frame); err != nil {
+ t.Fatalf("unmarshal frame: %v", err)
+ }
+ if frame.Type != protocol.EventIssueUpdated {
+ t.Errorf("frame type = %q, want %q", frame.Type, protocol.EventIssueUpdated)
+ }
+ if _, present := frame.Payload["prev_description"]; present {
+ t.Error("payload still carries prev_description")
+ }
+ if _, present := frame.Payload["prev_title"]; present {
+ t.Error("payload still carries prev_title")
+ }
+
+ // Everything clients actually consume must survive untouched. The issue
+ // object keeps its description: clients apply it to their cache, and
+ // stripping it would just trade fanout bytes for N refetches.
+ issue, ok := frame.Payload["issue"].(map[string]any)
+ if !ok {
+ t.Fatal("payload lost the issue object")
+ }
+ if issue["description"] == "" || issue["description"] == nil {
+ t.Error("issue.description was stripped; clients need it for cache updates")
+ }
+ if frame.Payload["description_changed"] != true {
+ t.Error("description_changed flag was lost")
+ }
+ if frame.Payload["title_changed"] != true {
+ t.Error("title_changed flag was lost")
+ }
+ // Cheap scalar prev_* fields are deliberately kept.
+ if frame.Payload["prev_status"] != "todo" {
+ t.Error("prev_status should be preserved; only the large fields are internal-only")
+ }
+
+ // Half 2: the in-process listener still received the full payload.
+ if seenByListener == nil {
+ t.Fatal("in-process listener did not run")
+ }
+ if _, present := seenByListener["prev_description"]; !present {
+ t.Error("in-process listener lost prev_description; mention diffing would break")
+ }
+ if _, present := seenByListener["prev_title"]; !present {
+ t.Error("in-process listener lost prev_title; the title-change activity would break")
+ }
+}
+
+// TestProjectOutbound_DoesNotMutateProducerPayload guards the copy-on-project
+// behaviour. Mutating the producer's map in place would corrupt it for any
+// listener or forwarder that reads it afterwards.
+func TestProjectOutbound_DoesNotMutateProducerPayload(t *testing.T) {
+ original := issueUpdatedPayload()
+
+ projected := projectOutbound(protocol.EventIssueUpdated, original)
+
+ if _, present := original["prev_description"]; !present {
+ t.Error("projectOutbound mutated the producer's payload map")
+ }
+ pm, ok := projected.(map[string]any)
+ if !ok {
+ t.Fatalf("projected payload type = %T, want map[string]any", projected)
+ }
+ if _, present := pm["prev_description"]; present {
+ t.Error("projected payload still has prev_description")
+ }
+ if len(pm) != len(original)-2 {
+ t.Errorf("projected key count = %d, want %d (exactly two keys removed)", len(pm), len(original)-2)
+ }
+}
+
+// TestProjectOutbound_PassesThroughUnlistedEvents keeps the projection from
+// becoming a general-purpose payload filter: an event type with no entry in the
+// table must be forwarded byte-for-byte, and a non-map payload must survive.
+func TestProjectOutbound_PassesThroughUnlistedEvents(t *testing.T) {
+ payload := map[string]any{"prev_description": "kept"}
+ if got := projectOutbound(protocol.EventIssueCreated, payload); got == nil {
+ t.Fatal("unlisted event type returned nil payload")
+ } else if m, ok := got.(map[string]any); !ok || m["prev_description"] != "kept" {
+ t.Error("unlisted event type must pass through untouched")
+ }
+
+ // Typed (non-map) payloads are common elsewhere in the bus.
+ type typedPayload struct{ ID string }
+ tp := typedPayload{ID: "x"}
+ if got := projectOutbound(protocol.EventIssueUpdated, tp); got != any(tp) {
+ t.Errorf("non-map payload was altered: got %#v, want %#v", got, tp)
+ }
+}
diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.go
index 8e17441625..3ea90b3e97 100644
--- a/server/cmd/server/listeners.go
+++ b/server/cmd/server/listeners.go
@@ -12,6 +12,57 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
+// internalOnlyPayloadKeys lists payload keys that exist purely for in-process
+// listeners and must never be serialized to a WebSocket client.
+//
+// `issue:updated` carries prev_description and prev_title so the in-process
+// listeners can diff against the new values: subscriber_listeners.go adds newly
+// @mentioned users, notification_listeners.go builds mention notifications, and
+// activity_listeners.go records the title change. Those all run on
+// bus.Subscribe, which Publish dispatches BEFORE the SubscribeAll forwarder
+// below, so removing the keys on the way out cannot affect them.
+//
+// No client reads either key — IssueUpdatedPayload in
+// packages/core/types/events.ts does not declare them. They reached the wire
+// only because the forwarder reuses the producer's payload map verbatim, which
+// meant every description autosave broadcast TWO full copies of the description
+// (the new one inside `issue`, plus prev_description) to every connection in the
+// workspace, including users who did not have the issue open. The DB write is
+// O(1); the fanout was O(workspace connections × description size) (MUL-5492).
+//
+// This is a table rather than an `if` on one event type because the bug was
+// structural, not a typo: the next large field added to a published payload
+// inherits the same cost silently. Keeping the list declarative puts the
+// internal/external payload boundary in one reviewable place.
+var internalOnlyPayloadKeys = map[string][]string{
+ protocol.EventIssueUpdated: {"prev_description", "prev_title"},
+}
+
+// projectOutbound returns payload with the event type's internal-only keys
+// removed, ready to serialize for external consumers.
+//
+// The input map is never mutated. In-process listeners have already run by the
+// time this is called, but the producer still owns the map and a second
+// forwarder may yet read it, so mutating it in place would be a landmine.
+func projectOutbound(eventType string, payload any) any {
+ keys := internalOnlyPayloadKeys[eventType]
+ if len(keys) == 0 {
+ return payload
+ }
+ m, ok := payload.(map[string]any)
+ if !ok {
+ return payload
+ }
+ projected := make(map[string]any, len(m))
+ for k, v := range m {
+ projected[k] = v
+ }
+ for _, k := range keys {
+ delete(projected, k)
+ }
+ return projected
+}
+
// registerListeners wires up event bus listeners for WS broadcasting.
// Personal events (inbox, invites) are sent only to the target user via
// SendToUser. All other events are broadcast to the workspace room.
@@ -39,7 +90,7 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
if recipientID == "" {
return
}
- data, err := json.Marshal(map[string]any{"type": e.Type, "payload": e.Payload, "actor_id": e.ActorID, "actor_type": e.ActorType})
+ data, err := json.Marshal(map[string]any{"type": e.Type, "payload": projectOutbound(e.Type, e.Payload), "actor_id": e.ActorID, "actor_type": e.ActorType})
if err != nil {
return
}
@@ -88,7 +139,7 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
// Fallback for map encoding.
if invMap, ok := payload["invitation"].(map[string]any); ok {
if uid, _ := invMap["invitee_user_id"].(*string); uid != nil && *uid != "" {
- data, err := json.Marshal(map[string]any{"type": e.Type, "payload": e.Payload, "actor_id": e.ActorID, "actor_type": e.ActorType})
+ data, err := json.Marshal(map[string]any{"type": e.Type, "payload": projectOutbound(e.Type, e.Payload), "actor_id": e.ActorID, "actor_type": e.ActorType})
if err != nil {
return
}
@@ -99,7 +150,7 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
return
}
if inv.InviteeUserID != nil && *inv.InviteeUserID != "" {
- data, err := json.Marshal(map[string]any{"type": e.Type, "payload": e.Payload, "actor_id": e.ActorID, "actor_type": e.ActorType})
+ data, err := json.Marshal(map[string]any{"type": e.Type, "payload": projectOutbound(e.Type, e.Payload), "actor_id": e.ActorID, "actor_type": e.ActorType})
if err != nil {
return
}
@@ -140,7 +191,7 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
if userID == "" {
return
}
- data, err := json.Marshal(map[string]any{"type": e.Type, "payload": e.Payload, "actor_id": e.ActorID, "actor_type": e.ActorType})
+ data, err := json.Marshal(map[string]any{"type": e.Type, "payload": projectOutbound(e.Type, e.Payload), "actor_id": e.ActorID, "actor_type": e.ActorType})
if err != nil {
return
}
@@ -157,7 +208,7 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
msg := map[string]any{
"type": e.Type,
- "payload": e.Payload,
+ "payload": projectOutbound(e.Type, e.Payload),
"actor_id": e.ActorID,
"actor_type": e.ActorType,
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index abab0168bf..e809e9356f 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -69,6 +69,19 @@ var corsAllowedHeaders = []string{
"X-Client-Capabilities",
}
+// corsExposedHeaders lists response headers browser clients are allowed to read.
+// Without this a custom response header is silently unreadable from JS on a
+// cross-origin request (only the CORS-safelisted response headers are exposed by
+// default) — the header arrives on the wire and then disappears, which looks
+// exactly like the server never sent it.
+//
+// Referencing the handler constant rather than re-typing the string keeps a
+// rename from quietly switching the signal off (MUL-5492).
+var corsExposedHeaders = []string{
+ handler.HeaderCommentsTruncated,
+ handler.HeaderTimelineTruncated,
+}
+
func allowedOrigins() []string {
raw := strings.TrimSpace(os.Getenv("CORS_ALLOWED_ORIGINS"))
if raw == "" {
@@ -708,6 +721,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
AllowedOrigins: origins,
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: corsAllowedHeaders,
+ ExposedHeaders: corsExposedHeaders,
AllowCredentials: true,
MaxAge: 300,
}))
diff --git a/server/internal/handler/activity.go b/server/internal/handler/activity.go
index 7cbd86e0ee..71f623b669 100644
--- a/server/internal/handler/activity.go
+++ b/server/internal/handler/activity.go
@@ -45,13 +45,67 @@ type TimelineEntry struct {
// data-shape rationale (#1929).
const timelineHardCap = 2000
+// timelineProbeLimit reads one row past the cap so "we hit the cap" can be
+// distinguished from "the issue happens to have exactly timelineHardCap rows".
+// Without the probe row an issue sitting exactly on the boundary would report a
+// complete timeline as truncated and pay a needless ancestor-backfill query.
+const timelineProbeLimit = timelineHardCap + 1
+
+// Truncation is signalled with a response header rather than a body field
+// because the unpaginated response is a bare JSON array (TimelineEntriesSchema =
+// z.array(TimelineEntrySchema) in packages/core/api/schemas.ts) with nowhere to
+// put a flag. The header is additive: existing clients keep validating.
+//
+// The value names which kinds were truncated ("activity", "comment", or
+// "activity,comment") because the two caps are independent — in practice it is
+// almost always activity alone.
+//
+// There is deliberately no companion "window from" header. An earlier revision
+// emitted one, but TimestampToString is second-precision RFC3339 while the real
+// ordering key is (created_at, id) at full precision, so it could not be used to
+// resume a read without skipping or repeating rows inside a shared second. A
+// resumable cursor needs to be opaque and carry both halves; that is worth
+// designing when there is a consumer, not shipping as a lossy approximation.
+//
+// Exported so the CORS layer can reference the same identifier
+// (corsExposedHeaders in server/cmd/server/router.go). A custom response header
+// is invisible to browser JS unless explicitly exposed, so a rename here that
+// did not reach the CORS list would silently switch the signal back off.
+const HeaderTimelineTruncated = "X-Timeline-Truncated"
+
+// truncatedKinds renders the X-Timeline-Truncated value, "" when nothing was
+// truncated.
+func truncatedKinds(comments, activities bool) string {
+ switch {
+ case comments && activities:
+ return "activity,comment"
+ case comments:
+ return "comment"
+ case activities:
+ return "activity"
+ default:
+ return ""
+ }
+}
+
+// takeNewest trims a timelineProbeLimit read down to timelineHardCap and reports
+// whether the probe row proved older rows exist. rows must be ascending, so the
+// newest timelineHardCap entries are the tail.
+func takeNewest[T any](rows []T) ([]T, bool) {
+ if len(rows) <= timelineHardCap {
+ return rows, false
+ }
+ return rows[len(rows)-timelineHardCap:], true
+}
+
// timelinePaginatedResponse mirrors the wrapper shape produced by the prior
// cursor-paginated ListTimeline (#2128). It is preserved as a backward-compat
// surface for installed Desktop builds and stale Web bundles between #2128 and
// #1929 that send `?limit=`/`?before=`/`?after=`/`?around=` and parse the
// response with the old TimelinePageSchema (entries + cursors). Cursors are
-// always nil and `has_more_*` are always false: the new server returns the
-// whole timeline in one shot.
+// always nil and `has_more_after` is always false: the new server returns the
+// whole timeline in one shot. `has_more_before` is now truthful — it reports the
+// hard-cap clamp — instead of being hardcoded false.
type timelinePaginatedResponse struct {
Entries []TimelineEntry `json:"entries"`
NextCursor *string `json:"next_cursor"`
@@ -67,7 +121,7 @@ type timelinePaginatedResponse struct {
// - No pagination params → flat ASC `TimelineEntry[]`. Matches the legacy
// desktop contract (Multica.app ≤ v0.2.25) and the new client.
// - Any of `limit` / `before` / `after` / `around` present → wrapped object
-// with DESC entries + null cursors + has_more_*=false. Matches what a
+// with DESC entries + null cursors + has_more_after=false. Matches what a
// stale v0.2.26+ build expects when it parses the response with
// TimelinePageSchema; cursor-walking is now a no-op so the client just
// sees a single full page.
@@ -76,6 +130,11 @@ type timelinePaginatedResponse struct {
// Time-based pagination was removed because it split reply threads at page
// boundaries, and at observed data sizes (p99 ~30 comments per issue) the
// cursor machinery was pure overhead.
+//
+// When the hard cap fires each list is independently reduced to its newest
+// entries and X-Timeline-Truncated names which kinds were affected. Comment
+// threads cut by the window are completed afterwards within a bounded context
+// budget; a thread that cannot be completed is omitted as one unit (MUL-5492).
func (h *Handler) ListTimeline(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
issue, ok := h.loadIssueForUser(w, r, id)
@@ -87,7 +146,7 @@ func (h *Handler) ListTimeline(w http.ResponseWriter, r *http.Request) {
comments, err := h.Queries.ListCommentsForIssue(ctx, db.ListCommentsForIssueParams{
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
- Limit: timelineHardCap,
+ Limit: timelineProbeLimit,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list comments")
@@ -95,7 +154,7 @@ func (h *Handler) ListTimeline(w http.ResponseWriter, r *http.Request) {
}
activities, err := h.Queries.ListActivitiesForIssue(ctx, db.ListActivitiesForIssueParams{
IssueID: issue.ID,
- Limit: timelineHardCap,
+ Limit: timelineProbeLimit,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list activities")
@@ -106,12 +165,53 @@ func (h *Handler) ListTimeline(w http.ResponseWriter, r *http.Request) {
wantWrapped := q.Get("limit") != "" || q.Get("before") != "" ||
q.Get("after") != "" || q.Get("around") != ""
+ // Each list is capped independently and reports its own truncation. The two
+ // are deliberately NOT clamped to a shared floor.
+ //
+ // An earlier revision did clamp them, to guarantee the returned window was a
+ // contiguous correctly-interleaved slice with no region holding only one of
+ // the two kinds. That traded the wrong way round. Comments are human-paced
+ // (p99 ~30, max ever observed ~1.1k) so they essentially never reach the cap,
+ // while activity is machine-paced and reaches it routinely — so the shared
+ // floor was almost always the ACTIVITY floor cutting away comments that had
+ // been fetched successfully and would have rendered fine. It deleted real
+ // content to buy a cosmetic property, and on a busy issue with thirty
+ // comments it was pure loss.
+ //
+ // Not clamping costs only activity density in the older part of the range,
+ // which is metadata, not content — and it is reported rather than hidden.
+ // It also keeps the comment set from being cut at an arbitrary row, which is
+ // why completeCommentThreads repairs any affected thread below.
+ comments, commentsTruncated := takeNewest(comments)
+ activities, activitiesTruncated := takeNewest(activities)
+
+ // Timeline clients derive resolution bars, author lists, and folded counts
+ // from the comments in this response. A parent-only repair would therefore
+ // make a partial thread look complete. Restore all missing siblings and
+ // descendants for affected roots within the shared context budget; if the
+ // walk cannot prove a thread complete, omit that thread as one unit.
+ if commentsTruncated {
+ var err error
+ comments, err = h.completeCommentThreads(ctx, issue.ID, issue.WorkspaceID, comments)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to complete comment threads")
+ return
+ }
+ }
+
+ if kinds := truncatedKinds(commentsTruncated, activitiesTruncated); kinds != "" {
+ w.Header().Set(HeaderTimelineTruncated, kinds)
+ }
+
if wantWrapped {
entries := h.mergeTimeline(r, comments, activities, false)
if entries == nil {
entries = []TimelineEntry{}
}
- resp := timelinePaginatedResponse{Entries: entries}
+ resp := timelinePaginatedResponse{
+ Entries: entries,
+ HasMoreBefore: commentsTruncated || activitiesTruncated,
+ }
// `around=<id>`: locate the anchor in the DESC slice so the legacy
// client can scroll-to-highlight without a follow-up request.
if anchor := q.Get("around"); anchor != "" {
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index cb8d53d6d1..0ffe9caa98 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1,6 +1,7 @@
package handler
import (
+ "bytes"
"context"
"encoding/json"
"errors"
@@ -274,11 +275,41 @@ func foldResolvedThreads(comments []db.Comment) ([]db.Comment, map[string]foldSt
// number of rows on a single issue.
const commentHardCap = 2000
-// ListComments returns comments for an issue. The default behaviour is
-// unchanged — full chronological dump capped at commentHardCap — so existing
-// callers and the desktop UI keep working as-is. Optional query params give
-// agent-style readers bounded views that scale to long issues without dragging
-// every prior reply into context:
+// HeaderCommentsTruncated tells browser and CLI callers that a defensive
+// comment-list cap omitted rows. It is deliberately separate from the timeline
+// header: /comments has several projections (roots, one thread, since) whose
+// truncation cannot be described as a timeline activity kind.
+const HeaderCommentsTruncated = "X-Comments-Truncated"
+
+// commentProbeLimit reads one row past the cap so a truncated read can be told
+// apart from an issue holding exactly commentHardCap comments. The difference
+// matters: exact-cap reads are complete and must not advertise data loss.
+const commentProbeLimit = commentHardCap + 1
+
+// Budgets for thread completion (completeCommentThreads).
+//
+// commentThreadContextBudget caps ALL context added outside the newest window:
+// ancestors first, then missing siblings/descendants for any thread whose root
+// had to be restored. A response is therefore bounded by commentHardCap +
+// commentThreadContextBudget comments regardless of thread shape.
+// commentThreadMaxDepth bounds each direction of the walk.
+//
+// Both are needed because reply depth is genuinely unbounded in stored data: the
+// general write path saves the exact comment being replied to, so chains can run
+// far deeper than the two levels the UI usually renders. Without a budget the
+// completion pass would defeat the row cap it is meant to preserve.
+const (
+ commentThreadContextBudget = 2000
+ commentThreadMaxDepth = 64
+)
+
+// ListComments returns comments for an issue. The default path returns the
+// newest commentHardCap comments in chronological order. If that defensive cap
+// fires, completeCommentThreads restores each affected thread within a bounded
+// context budget (or drops that thread as a unit), and the response sets
+// HeaderCommentsTruncated. Optional query params give agent-style readers
+// bounded views that scale to long issues without dragging every prior reply
+// into context:
//
// - roots_only=true — return only top-level comments (parent_id IS NULL),
// each annotated with reply_count + last_activity_at so the caller can
@@ -578,11 +609,16 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {
// Apply the resolve-aware fold before anything keys off the comment set
// (reaction/attachment grouping, the response array): folding drops comments,
// and the dropped ones should not pay a reactions/attachments round-trip or
- // appear in the response. fetchCommentsForList only ever returns complete
- // threads on the modes fold is allowed with (default, recent, untailed
- // thread), which is the precondition foldResolvedThreads documents.
+ // appear in the response.
+ //
+ // fetchCommentsForList marks FoldUnsafe only when a returned thread is known
+ // to be partial. The default capped path is safe: completeCommentThreads
+ // either restores every affected thread or removes it as one unit. An
+ // oversized untailed --thread read, however, intentionally keeps only the
+ // newest replies, so folding that partial thread would invent resolution
+ // state and folded_count.
var foldInfo map[string]foldStat
- if fold {
+ if fold && !result.FoldUnsafe {
result.Comments, foldInfo = foldResolvedThreads(result.Comments)
}
@@ -634,6 +670,9 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Multica-Next-Before", result.NextBefore)
w.Header().Set("X-Multica-Next-Before-Id", result.NextBeforeID)
}
+ if result.CommentsTruncated {
+ w.Header().Set(HeaderCommentsTruncated, "true")
+ }
writeJSON(w, http.StatusOK, resp)
}
@@ -670,6 +709,13 @@ type fetchCommentsResult struct {
// RootStats carries per-root orientation stats keyed by comment id string.
// Populated only on the roots_only path; nil for every other mode.
RootStats map[string]rootStat
+ // CommentsTruncated reports that a defensive cap omitted comments. Derived
+ // from a probe read, never from the final response length.
+ CommentsTruncated bool
+ // FoldUnsafe reports that the response contains a known-partial thread.
+ // Truncation alone does not imply this: completeCommentThreads makes the
+ // default newest window safe to fold by restoring or dropping whole threads.
+ FoldUnsafe bool
}
// rootStat is the per-thread orientation metadata attached to each root comment
@@ -749,6 +795,8 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
ResolvedAt: r.ResolvedAt,
ResolvedByType: r.ResolvedByType,
ResolvedByID: r.ResolvedByID,
+ SourceTaskID: r.SourceTaskID,
+ QuickActionID: r.QuickActionID,
}
if !r.ParentID.Valid {
root := c
@@ -807,11 +855,15 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
}
return res, nil
}
- rows, err := h.Queries.ListThreadCommentsForIssue(ctx, db.ListThreadCommentsForIssueParams{
+ // Untailed reads use the same newest-reply query as the paged path.
+ // Probe with commentHardCap replies: because the root is unconditional,
+ // 2000 replies proves the total thread exceeds the 2000-row response cap.
+ // We then drop the oldest reply and retain root + newest 1999 replies.
+ rows, err := h.Queries.ListThreadCommentsForIssuePaged(ctx, db.ListThreadCommentsForIssuePagedParams{
AnchorID: anchor,
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
- RowLimit: commentHardCap,
+ ReplyLimit: commentHardCap,
})
if err != nil {
return fetchCommentsResult{}, err
@@ -819,12 +871,10 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
if len(rows) == 0 {
return fetchCommentsResult{}, errCommentThreadNotFound
}
- out := make([]db.Comment, 0, len(rows))
+ var rootComment *db.Comment
+ replies := make([]db.Comment, 0, len(rows))
for _, r := range rows {
- if args.Since.Valid && !r.CreatedAt.Time.After(args.Since.Time) {
- continue
- }
- out = append(out, db.Comment{
+ c := db.Comment{
ID: r.ID,
IssueID: r.IssueID,
AuthorType: r.AuthorType,
@@ -838,9 +888,35 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
ResolvedAt: r.ResolvedAt,
ResolvedByType: r.ResolvedByType,
ResolvedByID: r.ResolvedByID,
- })
+ SourceTaskID: r.SourceTaskID,
+ QuickActionID: r.QuickActionID,
+ }
+ if !r.ParentID.Valid {
+ root := c
+ rootComment = &root
+ continue
+ }
+ replies = append(replies, c)
+ }
+ truncated := len(replies) >= commentHardCap
+ if truncated {
+ replies = replies[1:]
+ }
+ out := make([]db.Comment, 0, len(replies)+1)
+ if rootComment != nil && (!args.Since.Valid || rootComment.CreatedAt.Time.After(args.Since.Time)) {
+ out = append(out, *rootComment)
}
- return fetchCommentsResult{Comments: out}, nil
+ for _, reply := range replies {
+ if args.Since.Valid && !reply.CreatedAt.Time.After(args.Since.Time) {
+ continue
+ }
+ out = append(out, reply)
+ }
+ return fetchCommentsResult{
+ Comments: out,
+ CommentsTruncated: truncated,
+ FoldUnsafe: truncated,
+ }, nil
}
// Thread-grouped recent read: N most recently active threads.
@@ -899,6 +975,8 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
ResolvedAt: r.ResolvedAt,
ResolvedByType: r.ResolvedByType,
ResolvedByID: r.ResolvedByID,
+ SourceTaskID: r.SourceTaskID,
+ QuickActionID: r.QuickActionID,
})
}
@@ -939,11 +1017,17 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
Since: args.Since,
- RowLimit: commentHardCap,
+ RowLimit: commentProbeLimit,
})
if err != nil {
return fetchCommentsResult{}, err
}
+ truncated := len(rows) > commentHardCap
+ if truncated {
+ // Since is an incremental stream: keep the first page after the
+ // cursor so callers can advance without skipping a gap.
+ rows = rows[:commentHardCap]
+ }
comments := make([]db.Comment, len(rows))
for i, r := range rows {
comments[i] = db.Comment{
@@ -951,20 +1035,29 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
Content: r.Content, Type: r.Type, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
ParentID: r.ParentID, WorkspaceID: r.WorkspaceID, ResolvedAt: r.ResolvedAt,
ResolvedByType: r.ResolvedByType, ResolvedByID: r.ResolvedByID,
+ SourceTaskID: r.SourceTaskID, QuickActionID: r.QuickActionID,
}
stats[uuidToString(r.ID)] = rootStat{ReplyCount: int(r.ReplyCount), LastActivityAt: r.LastActivityAt}
}
- return fetchCommentsResult{Comments: comments, RootStats: stats}, nil
+ return fetchCommentsResult{
+ Comments: comments, RootStats: stats, CommentsTruncated: truncated,
+ }, nil
}
rows, err := h.Queries.ListRootCommentsForIssue(ctx, db.ListRootCommentsForIssueParams{
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
- RowLimit: commentHardCap,
+ RowLimit: commentProbeLimit,
})
if err != nil {
return fetchCommentsResult{}, err
}
+ truncated := len(rows) > commentHardCap
+ if truncated {
+ // The SQL returns selected roots chronologically after taking the
+ // newest probe window, so the overflow row is the oldest.
+ rows = rows[1:]
+ }
comments := make([]db.Comment, len(rows))
for i, r := range rows {
comments[i] = db.Comment{
@@ -972,29 +1065,388 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
Content: r.Content, Type: r.Type, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
ParentID: r.ParentID, WorkspaceID: r.WorkspaceID, ResolvedAt: r.ResolvedAt,
ResolvedByType: r.ResolvedByType, ResolvedByID: r.ResolvedByID,
+ SourceTaskID: r.SourceTaskID, QuickActionID: r.QuickActionID,
}
stats[uuidToString(r.ID)] = rootStat{ReplyCount: int(r.ReplyCount), LastActivityAt: r.LastActivityAt}
}
- return fetchCommentsResult{Comments: comments, RootStats: stats}, nil
+ return fetchCommentsResult{
+ Comments: comments, RootStats: stats, CommentsTruncated: truncated,
+ }, nil
}
- // Default + since paths preserved verbatim (no behavioural change for
- // existing callers).
+ // Since reads keep their chronological page shape. A probe makes the cap
+ // visible without skipping the next page of the incremental stream.
if args.Since.Valid {
comments, err := h.Queries.ListCommentsSinceForIssue(ctx, db.ListCommentsSinceForIssueParams{
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
CreatedAt: args.Since,
- Limit: commentHardCap,
+ Limit: commentProbeLimit,
})
- return fetchCommentsResult{Comments: comments}, err
+ if err != nil {
+ return fetchCommentsResult{}, err
+ }
+ truncated := len(comments) > commentHardCap
+ if truncated {
+ comments = comments[:commentHardCap]
+ }
+ return fetchCommentsResult{Comments: comments, CommentsTruncated: truncated}, nil
}
comments, err := h.Queries.ListCommentsForIssue(ctx, db.ListCommentsForIssueParams{
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
- Limit: commentHardCap,
+ Limit: commentProbeLimit,
})
- return fetchCommentsResult{Comments: comments}, err
+ if err != nil {
+ return fetchCommentsResult{}, err
+ }
+ // Probe read: an issue holding exactly commentHardCap comments is complete,
+ // and calling that truncated would needlessly suppress the thread fold below.
+ truncated := len(comments) > commentHardCap
+ if truncated {
+ comments = comments[len(comments)-commentHardCap:]
+ // The cap keeps the NEWEST comments (MUL-5492), so a thread can be cut
+ // in half: an old root or sibling outside the window, a fresh reply
+ // inside it. Complete every affected thread within the shared context
+ // budget. If a thread cannot be completed, it is dropped as one unit.
+ //
+ comments, err = h.completeCommentThreads(ctx, issue.ID, issue.WorkspaceID, comments)
+ if err != nil {
+ return fetchCommentsResult{}, err
+ }
+ }
+ return fetchCommentsResult{Comments: comments, CommentsTruncated: truncated}, nil
+}
+
+// completeCommentThreads restores complete renderable threads around a newest-N
+// comment window.
+//
+// Why this is needed at all: capping with the OLDEST n comments could never
+// orphan a reply, because a reply is always newer than its parent and so a
+// prefix of the timeline is closed under "parent of". A newest-n window is a
+// suffix and has no such property — an old thread root falls outside while a
+// fresh reply to it stays inside (MUL-5492).
+//
+// Parent closure comes first because an orphaned reply is not merely mis-nested,
+// it is invisible.
+// The timeline builds its top level from "activities + comments with no
+// parent_id" and renders replies by looking them up under their parent, so an
+// orphan sits in the map with no card to render it — the exact shape of MUL-1847
+// (1 root + 29 replies, root dropped, all 29 vanished from the UI while the API
+// returned them).
+//
+// Parent closure alone is insufficient for the human timeline. Web and Desktop
+// derive resolution bars and folded counts from the comments they receive, so a
+// backfilled root plus only its newest replies would make a partial thread look
+// complete. After reaching roots, this function walks DOWN from every restored
+// root and adds all missing siblings/descendants. If the shared budget or depth
+// bound cannot prove a whole affected thread complete, that thread is removed
+// as one unit; old installed clients can therefore never fold partial data.
+//
+// Both walks share commentThreadContextBudget, so the returned set remains
+// provably bounded by commentHardCap + commentThreadContextBudget. Descendants
+// are fetched one level at a time for every affected root in one query, avoiding
+// an N+1 query per thread. Each query carries issue + workspace predicates and a
+// probe limit.
+//
+// When a budget is exhausted, a parent row is missing, or a parent belongs to
+// another issue or workspace, keepRootConnected drops the affected replies. A
+// descendant overflow drops every affected thread rather than guessing which
+// root is complete. Returning fewer new replies is a conservative degradation
+// that the caller already signals as truncated; leaking another tenant's
+// comments, returning an unbounded response, or emitting partial threads are all
+// worse.
+func (h *Handler) completeCommentThreads(ctx context.Context, issueID, workspaceID pgtype.UUID, window []db.Comment) ([]db.Comment, error) {
+ if len(window) == 0 {
+ return window, nil
+ }
+
+ initialIDs := make(map[string]struct{}, len(window))
+ byID := make(map[string]db.Comment, len(window)+commentThreadContextBudget/8)
+ through := window[0]
+ for _, c := range window {
+ id := uuidToString(c.ID)
+ initialIDs[id] = struct{}{}
+ byID[id] = c
+ if c.CreatedAt.Time.After(through.CreatedAt.Time) ||
+ (c.CreatedAt.Time.Equal(through.CreatedAt.Time) &&
+ bytes.Compare(c.ID.Bytes[:], through.ID.Bytes[:]) > 0) {
+ through = c
+ }
+ }
+
+ added := 0
+ for depth := 0; depth < commentThreadMaxDepth; depth++ {
+ // Distinct parents referenced by the current set but not in it. Dedup is
+ // what keeps many replies sharing one ancestor from fetching it twice.
+ var missing []pgtype.UUID
+ seen := make(map[string]struct{})
+ for _, c := range byID {
+ if !c.ParentID.Valid {
+ continue
+ }
+ pid := uuidToString(c.ParentID)
+ if _, have := byID[pid]; have {
+ continue
+ }
+ if _, dup := seen[pid]; dup {
+ continue
+ }
+ seen[pid] = struct{}{}
+ missing = append(missing, c.ParentID)
+ }
+ if len(missing) == 0 {
+ break
+ }
+ if added+len(missing) > commentThreadContextBudget {
+ break
+ }
+
+ // Tenant-scoped: a parent in another issue or workspace simply does not
+ // come back, and keepRootConnected then prunes the reply that pointed at
+ // it. The filter is on every level, not just the first.
+ rows, err := h.Queries.ListCommentsByIDsForIssue(ctx, db.ListCommentsByIDsForIssueParams{
+ Ids: missing,
+ IssueID: issueID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(rows) == 0 {
+ break
+ }
+ for _, r := range rows {
+ id := uuidToString(r.ID)
+ if _, have := byID[id]; have {
+ continue
+ }
+ byID[id] = r
+ added++
+ }
+ }
+
+ // Remove every chain that did not reach a same-tenant root within the
+ // ancestor budget/depth. Rebuild the map so the descendant phase cannot
+ // accidentally revive a disconnected chain.
+ connected := keepRootConnected(byID)
+ byID = make(map[string]db.Comment, len(connected)+commentThreadContextBudget-added)
+ for _, c := range connected {
+ byID[uuidToString(c.ID)] = c
+ }
+
+ // A restored root identifies a thread that the newest window cut. Threads
+ // whose roots were already in the suffix are complete under the normal
+ // parent-before-reply timestamp contract and need no extra query.
+ affectedRoots := make(map[string]struct{})
+ for id, c := range byID {
+ if c.ParentID.Valid {
+ continue
+ }
+ if _, wasInWindow := initialIDs[id]; !wasInWindow {
+ affectedRoots[id] = struct{}{}
+ }
+ }
+
+ if len(affectedRoots) > 0 {
+ complete, err := h.addMissingCommentDescendants(
+ ctx,
+ issueID,
+ workspaceID,
+ byID,
+ affectedRoots,
+ through,
+ &added,
+ )
+ if err != nil {
+ return nil, err
+ }
+ if !complete {
+ dropCommentThreads(byID, affectedRoots)
+ }
+ }
+
+ out := make([]db.Comment, 0, len(byID))
+ for _, c := range byID {
+ out = append(out, c)
+ }
+ sortCommentsChronologically(out)
+ return out, nil
+}
+
+// addMissingCommentDescendants walks every affected thread breadth-first. It
+// returns false when the remaining context budget or depth bound cannot prove
+// all affected threads complete; callers then drop those threads as one unit.
+func (h *Handler) addMissingCommentDescendants(
+ ctx context.Context,
+ issueID, workspaceID pgtype.UUID,
+ byID map[string]db.Comment,
+ affectedRoots map[string]struct{},
+ through db.Comment,
+ added *int,
+) (bool, error) {
+ frontier := make(map[string]string, len(affectedRoots)) // comment id -> root id
+ for rootID := range affectedRoots {
+ frontier[rootID] = rootID
+ }
+
+ // Every returned child is unique in a tree walk. The scan budget includes
+ // rows already present in the window plus the remaining add budget, so all
+ // descendant queries together inspect at most the response bound (+1 probe).
+ scanBudget := len(byID) + commentThreadContextBudget - *added
+ for depth := 0; depth <= commentThreadMaxDepth; depth++ {
+ parentKeys := make([]string, 0, len(frontier))
+ for id := range frontier {
+ parentKeys = append(parentKeys, id)
+ }
+ sort.Strings(parentKeys)
+
+ parentIDs := make([]pgtype.UUID, len(parentKeys))
+ for i, id := range parentKeys {
+ parentIDs[i] = byID[id].ID
+ }
+
+ rows, err := h.Queries.ListChildCommentsForParents(ctx, db.ListChildCommentsForParentsParams{
+ ParentIds: parentIDs,
+ IssueID: issueID,
+ WorkspaceID: workspaceID,
+ ThroughAt: through.CreatedAt,
+ ThroughID: through.ID,
+ RowLimit: int32(scanBudget + 1),
+ })
+ if err != nil {
+ return false, err
+ }
+ if len(rows) == 0 {
+ return true, nil
+ }
+ if len(rows) > scanBudget || depth == commentThreadMaxDepth {
+ return false, nil
+ }
+ scanBudget -= len(rows)
+
+ next := make(map[string]string, len(rows))
+ for _, row := range rows {
+ parentID := uuidToString(row.ParentID)
+ rootID, ok := frontier[parentID]
+ if !ok {
+ // The query is constrained to frontier parent ids, so this is
+ // defensive fail-closed handling for malformed query output.
+ return false, nil
+ }
+ id := uuidToString(row.ID)
+ next[id] = rootID
+ if _, exists := byID[id]; exists {
+ continue
+ }
+ if *added >= commentThreadContextBudget {
+ return false, nil
+ }
+ byID[id] = row
+ *added = *added + 1
+ }
+ frontier = next
+ }
+ return false, nil
+}
+
+// dropCommentThreads removes every comment whose root is in roots. It is used
+// only after a bounded descendant walk could not prove the affected threads
+// complete.
+func dropCommentThreads(byID map[string]db.Comment, roots map[string]struct{}) {
+ for id := range byID {
+ rootID, ok := commentRootID(id, byID)
+ if !ok {
+ delete(byID, id)
+ continue
+ }
+ if _, drop := roots[rootID]; drop {
+ delete(byID, id)
+ }
+ }
+}
+
+func commentRootID(id string, byID map[string]db.Comment) (string, bool) {
+ seen := make(map[string]struct{})
+ for current := id; ; {
+ if _, loop := seen[current]; loop {
+ return "", false
+ }
+ seen[current] = struct{}{}
+
+ comment, ok := byID[current]
+ if !ok {
+ return "", false
+ }
+ if !comment.ParentID.Valid {
+ return current, true
+ }
+ current = uuidToString(comment.ParentID)
+ }
+}
+
+func sortCommentsChronologically(comments []db.Comment) {
+ sort.Slice(comments, func(i, j int) bool {
+ if !comments[i].CreatedAt.Time.Equal(comments[j].CreatedAt.Time) {
+ return comments[i].CreatedAt.Time.Before(comments[j].CreatedAt.Time)
+ }
+ return bytes.Compare(comments[i].ID.Bytes[:], comments[j].ID.Bytes[:]) < 0
+ })
+}
+
+// keepRootConnected returns only the comments whose parent chain terminates at a
+// root (parent_id IS NULL) inside the set.
+//
+// A comment whose chain leaves the set, loops, or dead-ends is unrenderable: the
+// UI needs a top-level card to hang the thread from. Dropping such a comment also
+// drops its descendants, because their chains run through it and therefore fail
+// the same test — no separate descendant pass is needed.
+//
+// The walk is bounded by the visited set, so a cycle in stored data terminates
+// instead of hanging. Real cycles are impossible via the write path, but a graph
+// walk over stored data should never assume that.
+func keepRootConnected(byID map[string]db.Comment) []db.Comment {
+ connected := make(map[string]bool, len(byID))
+
+ for id := range byID {
+ if _, decided := connected[id]; decided {
+ continue
+ }
+ var path []string
+ visited := make(map[string]struct{})
+ verdict := false
+ for cur := id; ; {
+ if v, decided := connected[cur]; decided {
+ verdict = v
+ break
+ }
+ if _, loop := visited[cur]; loop {
+ break // cycle: nothing on this path reaches a root
+ }
+ c, present := byID[cur]
+ if !present {
+ break // chain leaves the set
+ }
+ visited[cur] = struct{}{}
+ path = append(path, cur)
+ if !c.ParentID.Valid {
+ verdict = true // a real root, inside the set
+ break
+ }
+ cur = uuidToString(c.ParentID)
+ }
+ for _, p := range path {
+ connected[p] = verdict
+ }
+ }
+
+ out := make([]db.Comment, 0, len(byID))
+ for id, c := range byID {
+ if connected[id] {
+ out = append(out, c)
+ }
+ }
+ return out
}
type CreateCommentRequest struct {
diff --git a/server/internal/handler/comment_cap_thread_test.go b/server/internal/handler/comment_cap_thread_test.go
new file mode 100644
index 0000000000..251526189c
--- /dev/null
+++ b/server/internal/handler/comment_cap_thread_test.go
@@ -0,0 +1,548 @@
+package handler
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+// The comment-list endpoint shares ListCommentsForIssue with the timeline, so the
+// newest-N window (MUL-5492) can cut a thread in half here too: an old root
+// outside the window, a fresh reply inside it.
+//
+// Two separate properties are at stake:
+//
+// - PARENT-CHAIN CLOSURE makes a reply renderable.
+// - THREAD COMPLETENESS is what foldResolvedThreads needs. Closure does NOT
+// provide it: older siblings and descendants of a retained reply stay outside
+// the window.
+//
+// completeCommentThreads now handles both: it restores a whole affected thread
+// within explicit budgets or drops that thread as one unit. A completed default
+// window is therefore safe to fold even though the endpoint still advertises
+// that unrelated older comments were truncated.
+
+// seedCommentRow inserts one comment at an exact timestamp and returns its id.
+// resolvedAt marks it as the thread's resolution when non-nil.
+func seedCommentRow(t *testing.T, issueID string, at time.Time, content string, parentID *string, resolvedAt *time.Time) string {
+ t.Helper()
+ var id string
+ err := testPool.QueryRow(context.Background(), `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type,
+ created_at, updated_at, parent_id, resolved_at, resolved_by_type, resolved_by_id)
+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5, $5, $6, $7,
+ CASE WHEN $7::timestamptz IS NULL THEN NULL ELSE 'member' END,
+ CASE WHEN $7::timestamptz IS NULL THEN NULL ELSE $3::uuid END)
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID, content, at, parentID, resolvedAt).Scan(&id)
+ if err != nil {
+ t.Fatalf("seed comment %q: %v", content, err)
+ }
+ return id
+}
+
+// assertNoOrphanCommentRows pins the invariant the UI depends on: every returned
+// reply's parent is in the same response.
+func assertNoOrphanCommentRows(t *testing.T, rows []CommentResponse) {
+ t.Helper()
+ present := make(map[string]struct{}, len(rows))
+ for _, c := range rows {
+ present[c.ID] = struct{}{}
+ }
+ for _, c := range rows {
+ if c.ParentID == nil || *c.ParentID == "" {
+ continue
+ }
+ if _, ok := present[*c.ParentID]; !ok {
+ t.Errorf("comment %s references parent %s absent from the response", c.ID, *c.ParentID)
+ }
+ }
+}
+
+// TestListComments_ExactlyAtCapStillFolds pins the probe read. An issue holding
+// exactly commentHardCap comments is complete, so the fold must still run —
+// inferring truncation from the row count would silently stop folding here.
+func TestListComments_ExactlyAtCapStillFolds(t *testing.T) {
+ issueID := createIssueForTimeline(t, "exactly at cap still folds")
+
+ base := time.Now().UTC().Add(-2 * time.Hour).Truncate(time.Second)
+ rootID := seedCommentRow(t, issueID, base, "root question", nil, nil)
+ seedCommentRow(t, issueID, base.Add(time.Second), "chatter", &rootID, nil)
+ resolvedAt := base.Add(2 * time.Second)
+ seedCommentRow(t, issueID, resolvedAt, "the conclusion", &rootID, &resolvedAt)
+ // Fill to exactly the cap.
+ bulkSeedComments(t, issueID, base.Add(time.Minute), commentHardCap-3)
+
+ w, rows := listComments(t, issueID, "fold=true")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+ if got := w.Header().Get(HeaderCommentsTruncated); got != "" {
+ t.Errorf("%s = %q, want unset at exact cap", HeaderCommentsTruncated, got)
+ }
+ var root *CommentResponse
+ for i := range rows {
+ if rows[i].ID == rootID {
+ root = &rows[i]
+ }
+ }
+ if root == nil {
+ t.Fatal("thread root missing")
+ }
+ if root.ThreadResolved == nil || !*root.ThreadResolved {
+ t.Error("thread_resolved not set: exactly-at-cap is complete, so the fold must run")
+ }
+}
+
+// TestListComments_TruncatedCompleteThreadStillFolds covers the review finding. The
+// resolution reply is inside the window while older ordinary replies on the same
+// thread are outside it. completeCommentThreads restores those replies before
+// folding, so folded_count reflects the complete thread rather than a partial
+// window.
+func TestListComments_TruncatedCompleteThreadStillFolds(t *testing.T) {
+ issueID := createIssueForTimeline(t, "truncated complete thread still folds")
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ rootID := seedCommentRow(t, issueID, base, "root question", nil, nil)
+ // Older ordinary replies that the window will cut away.
+ for i := 0; i < 3; i++ {
+ seedCommentRow(t, issueID, base.Add(time.Duration(i+1)*time.Second), "old reply", &rootID, nil)
+ }
+
+ // Push root + the old replies out of the newest-cap window.
+ bulkSeedComments(t, issueID, base.Add(time.Minute), commentHardCap+50)
+
+ // Inside the window: an ordinary reply the fold would discard, plus the
+ // resolution that would make the fold fire.
+ now := time.Now().UTC().Truncate(time.Second)
+ keptReplyID := seedCommentRow(t, issueID, now, "fresh ordinary reply", &rootID, nil)
+ resolvedAt := now.Add(time.Second)
+ conclusionID := seedCommentRow(t, issueID, resolvedAt, "the conclusion", &rootID, &resolvedAt)
+
+ w, rows := listComments(t, issueID, "fold=true")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+ if got := w.Header().Get(HeaderCommentsTruncated); got != "true" {
+ t.Errorf("%s = %q, want true", HeaderCommentsTruncated, got)
+ }
+
+ byID := make(map[string]CommentResponse, len(rows))
+ for _, c := range rows {
+ byID[c.ID] = c
+ }
+
+ // Thread completion restores the root and every old reply before folding.
+ root, ok := byID[rootID]
+ if !ok {
+ t.Fatal("the old thread root was not backfilled")
+ }
+ if _, ok := byID[conclusionID]; !ok {
+ t.Error("the resolution reply is missing")
+ }
+ if _, ok := byID[keptReplyID]; ok {
+ t.Error("fresh ordinary reply was not folded from a completed resolved thread")
+ }
+ if root.ThreadResolved == nil || !*root.ThreadResolved {
+ t.Error("thread_resolved missing after the truncated window was completed")
+ }
+ if root.FoldedCount == nil {
+ t.Error("folded_count missing, want 4 complete ordinary replies")
+ } else if *root.FoldedCount != 4 {
+ t.Errorf("folded_count = %d, want 4 complete ordinary replies", *root.FoldedCount)
+ }
+ assertNoOrphanCommentRows(t, rows)
+}
+
+// TestListComments_RootResolvedTruncatedUsesCompleteFoldedCount is the
+// root-resolved variant: completion restores all six replies before folding.
+func TestListComments_RootResolvedTruncatedUsesCompleteFoldedCount(t *testing.T) {
+ issueID := createIssueForTimeline(t, "root resolved truncated")
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ resolvedAt := base
+ rootID := seedCommentRow(t, issueID, base, "settled topic", nil, &resolvedAt)
+ for i := 0; i < 5; i++ {
+ seedCommentRow(t, issueID, base.Add(time.Duration(i+1)*time.Second), "old reply", &rootID, nil)
+ }
+
+ bulkSeedComments(t, issueID, base.Add(time.Minute), commentHardCap+50)
+ seedCommentRow(t, issueID, time.Now().UTC().Truncate(time.Second), "fresh reply", &rootID, nil)
+
+ w, rows := listComments(t, issueID, "fold=true")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+ if got := w.Header().Get(HeaderCommentsTruncated); got != "true" {
+ t.Errorf("%s = %q, want true", HeaderCommentsTruncated, got)
+ }
+ foundRoot := false
+ for _, c := range rows {
+ if c.ID != rootID {
+ continue
+ }
+ foundRoot = true
+ if c.FoldedCount == nil {
+ t.Error("folded_count missing, want all 6 replies")
+ } else if *c.FoldedCount != 6 {
+ t.Errorf("folded_count = %d, want all 6 replies", *c.FoldedCount)
+ }
+ if c.ThreadResolved == nil || !*c.ThreadResolved {
+ t.Error("thread_resolved missing after completion")
+ }
+ }
+ if !foundRoot {
+ t.Fatal("resolved root missing")
+ }
+ assertNoOrphanCommentRows(t, rows)
+}
+
+// TestListComments_RootsOnlyHardCapKeepsNewestRoots pins the roots-only window:
+// the API must not retain the oldest 2000 roots and silently lose new discussion.
+func TestListComments_RootsOnlyHardCapKeepsNewestRoots(t *testing.T) {
+ issueID := createIssueForTimeline(t, "roots only keeps newest")
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ oldestID := seedCommentRow(t, issueID, base, "oldest root", nil, nil)
+ bulkSeedComments(t, issueID, base.Add(time.Second), commentHardCap+20)
+ newestID := seedCommentRow(t, issueID, base.Add(2*time.Hour), "newest root", nil, nil)
+
+ w, rows := listComments(t, issueID, "roots_only=true")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+ if got := w.Header().Get(HeaderCommentsTruncated); got != "true" {
+ t.Errorf("%s = %q, want true", HeaderCommentsTruncated, got)
+ }
+ if len(rows) != commentHardCap {
+ t.Fatalf("root count = %d, want %d", len(rows), commentHardCap)
+ }
+ present := make(map[string]struct{}, len(rows))
+ for _, row := range rows {
+ present[row.ID] = struct{}{}
+ }
+ if _, ok := present[oldestID]; ok {
+ t.Error("oldest root survived the newest-root cap")
+ }
+ if _, ok := present[newestID]; !ok {
+ t.Error("newest root was dropped by the roots-only cap")
+ }
+}
+
+func TestListComments_RootsOnlyExactCapIsNotTruncated(t *testing.T) {
+ issueID := createIssueForTimeline(t, "roots only exact cap")
+ base := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)
+ bulkSeedComments(t, issueID, base, commentHardCap)
+
+ w, rows := listComments(t, issueID, "roots_only=true")
+ if len(rows) != commentHardCap {
+ t.Fatalf("root count = %d, want %d", len(rows), commentHardCap)
+ }
+ if got := w.Header().Get(HeaderCommentsTruncated); got != "" {
+ t.Errorf("%s = %q, want unset at exact cap", HeaderCommentsTruncated, got)
+ }
+}
+
+// TestListComments_UntailedThreadHardCapKeepsNewestReplies proves that a plain
+// --thread read cannot lose the newest resolution reply. The returned thread is
+// partial, so fold must remain suppressed even though the resolution is visible.
+func TestListComments_UntailedThreadHardCapKeepsNewestReplies(t *testing.T) {
+ issueID := createIssueForTimeline(t, "thread keeps newest replies")
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ rootID := seedCommentRow(t, issueID, base, "thread root", nil, nil)
+ oldestReplyID := seedCommentRow(t, issueID, base.Add(time.Second), "oldest reply", &rootID, nil)
+ bulkSeedReplies(t, issueID, rootID, base.Add(2*time.Second), commentHardCap)
+ resolvedAt := base.Add(2 * time.Hour)
+ newestReplyID := seedCommentRow(t, issueID, resolvedAt, "newest resolution", &rootID, &resolvedAt)
+
+ w, rows := listComments(t, issueID, "thread="+rootID+"&fold=true")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+ if got := w.Header().Get(HeaderCommentsTruncated); got != "true" {
+ t.Errorf("%s = %q, want true", HeaderCommentsTruncated, got)
+ }
+ if len(rows) != commentHardCap {
+ t.Fatalf("thread row count = %d, want %d", len(rows), commentHardCap)
+ }
+ present := make(map[string]CommentResponse, len(rows))
+ for _, row := range rows {
+ present[row.ID] = row
+ }
+ if _, ok := present[rootID]; !ok {
+ t.Error("thread root missing")
+ }
+ if _, ok := present[oldestReplyID]; ok {
+ t.Error("oldest reply survived the newest-reply cap")
+ }
+ if _, ok := present[newestReplyID]; !ok {
+ t.Error("newest resolution reply was dropped")
+ }
+ if root := present[rootID]; root.ThreadResolved != nil || root.FoldedCount != nil {
+ t.Error("partial oversized thread was folded")
+ }
+}
+
+func TestListComments_UntailedThreadExactCapStillFolds(t *testing.T) {
+ issueID := createIssueForTimeline(t, "thread exact cap still folds")
+
+ base := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)
+ resolvedAt := base
+ rootID := seedCommentRow(t, issueID, base, "resolved root", nil, &resolvedAt)
+ bulkSeedReplies(t, issueID, rootID, base.Add(time.Second), commentHardCap-1)
+
+ w, rows := listComments(t, issueID, "thread="+rootID+"&fold=true")
+ if got := w.Header().Get(HeaderCommentsTruncated); got != "" {
+ t.Errorf("%s = %q, want unset at exact cap", HeaderCommentsTruncated, got)
+ }
+ if len(rows) != 1 || rows[0].ID != rootID {
+ t.Fatalf("exact-cap resolved thread did not fold to its root: ids=%v", ids(rows))
+ }
+ if rows[0].FoldedCount == nil || *rows[0].FoldedCount != commentHardCap-1 {
+ t.Fatalf("folded_count = %v, want %d", rows[0].FoldedCount, commentHardCap-1)
+ }
+}
+
+// TestListComments_DeepChainBeyondBudgetIsPrunedNotOrphaned exercises the depth
+// budget. A chain deeper than commentThreadMaxDepth cannot be closed, so the
+// affected reply is dropped rather than returned as an unrenderable orphan. The
+// response must stay bounded and must terminate.
+func TestListComments_DeepChainBeyondBudgetIsPrunedNotOrphaned(t *testing.T) {
+ issueID := createIssueForTimeline(t, "deep chain beyond budget")
+
+ base := time.Now().UTC().Add(-6 * time.Hour).Truncate(time.Second)
+ // A chain deeper than the walk is allowed to climb.
+ depth := commentThreadMaxDepth + 6
+ rootID := seedCommentRow(t, issueID, base, "chain root", nil, nil)
+ parent := rootID
+ for i := 0; i < depth; i++ {
+ parent = seedCommentRow(t, issueID, base.Add(time.Duration(i+1)*time.Second), "chain link", &parent, nil)
+ }
+ // Push the whole chain out of the window.
+ bulkSeedComments(t, issueID, base.Add(time.Hour), commentHardCap+50)
+ // The newest comment is a reply at the bottom of that chain.
+ deepReplyID := seedCommentRow(t, issueID, time.Now().UTC().Truncate(time.Second), "deep reply", &parent, nil)
+
+ _, rows := listComments(t, issueID, "")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+
+ // Bounded: window plus at most the ancestor budget.
+ if len(rows) > commentHardCap+commentThreadContextBudget {
+ t.Errorf("returned %d comments, exceeds the provable bound of %d",
+ len(rows), commentHardCap+commentThreadContextBudget)
+ }
+ // The chain could not be closed, so the deep reply is dropped rather than
+ // emitted as an orphan.
+ for _, c := range rows {
+ if c.ID == deepReplyID {
+ t.Error("the deep reply survived without a closed parent chain")
+ }
+ }
+ assertNoOrphanCommentRows(t, rows)
+}
+
+// TestListComments_SharedAncestorFetchedOnce checks the dedup in the walk: many
+// replies pointing at one old root must not duplicate that root.
+func TestListComments_SharedAncestorFetchedOnce(t *testing.T) {
+ issueID := createIssueForTimeline(t, "shared ancestor")
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ rootID := seedCommentRow(t, issueID, base, "shared root", nil, nil)
+ bulkSeedComments(t, issueID, base.Add(time.Minute), commentHardCap+50)
+
+ now := time.Now().UTC().Truncate(time.Second)
+ var replies []string
+ for i := 0; i < 3; i++ {
+ replies = append(replies, seedCommentRow(t, issueID, now.Add(time.Duration(i)*time.Second), "sibling reply", &rootID, nil))
+ }
+
+ _, rows := listComments(t, issueID, "")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+
+ seen := 0
+ present := make(map[string]struct{}, len(rows))
+ for _, c := range rows {
+ present[c.ID] = struct{}{}
+ if c.ID == rootID {
+ seen++
+ }
+ }
+ if seen != 1 {
+ t.Errorf("shared root appears %d times, want exactly 1", seen)
+ }
+ for _, id := range replies {
+ if _, ok := present[id]; !ok {
+ t.Errorf("reply %s missing", id)
+ }
+ }
+ assertNoOrphanCommentRows(t, rows)
+}
+
+// TestListComments_CrossIssueParentNeverCrossesBoundary is the negative tenant
+// test. parent_id carries a foreign key to comment(id) but NOT to a matching
+// issue, so a stray cross-issue parent reference is representable in stored data.
+// The walk filters on issue_id and workspace_id at every level, so the foreign
+// comment must never appear and the anomalous reply must be pruned.
+func TestListComments_CrossIssueParentNeverCrossesBoundary(t *testing.T) {
+ otherIssueID := createIssueForTimeline(t, "other issue")
+ issueID := createIssueForTimeline(t, "cross issue parent")
+
+ foreignID := seedCommentRow(t, otherIssueID, time.Now().UTC().Add(-time.Hour).Truncate(time.Second),
+ "comment belonging to another issue", nil, nil)
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ bulkSeedComments(t, issueID, base, commentHardCap+50)
+ // A reply in THIS issue whose parent lives in the other issue.
+ strayID := seedCommentRow(t, issueID, time.Now().UTC().Truncate(time.Second),
+ "reply with a foreign parent", &foreignID, nil)
+
+ _, rows := listComments(t, issueID, "")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+
+ for _, c := range rows {
+ if c.ID == foreignID {
+ t.Error("a comment from another issue leaked into this issue's response")
+ }
+ if c.ID == strayID {
+ t.Error("the reply with an out-of-issue parent was returned as an orphan")
+ }
+ }
+ assertNoOrphanCommentRows(t, rows)
+}
+
+// TestListComments_CrossWorkspaceParentNeverCrossesBoundary independently pins
+// the workspace predicate. The parent deliberately carries the target issue_id
+// but a different workspace_id, so retaining issue_id filtering while removing
+// workspace_id filtering must still make this test fail.
+func TestListComments_CrossWorkspaceParentNeverCrossesBoundary(t *testing.T) {
+ ctx := context.Background()
+ issueID := createIssueForTimeline(t, "cross workspace parent")
+
+ var otherWorkspaceID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description, issue_prefix)
+ VALUES ('Comment parent boundary', 'comment-parent-boundary-' || gen_random_uuid()::text,
+ 'Foreign workspace', 'CPB')
+ RETURNING id
+ `).Scan(&otherWorkspaceID); err != nil {
+ t.Fatalf("insert foreign workspace: %v", err)
+ }
+
+ var foreignID string
+ t.Cleanup(func() {
+ if foreignID != "" {
+ // Deleting the foreign parent cascades to the anomalous reply below.
+ testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, foreignID)
+ }
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, otherWorkspaceID)
+ })
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type,
+ created_at, updated_at)
+ VALUES ($1, $2, 'member', $3, 'comment belonging to another workspace', 'comment',
+ $4, $4)
+ RETURNING id
+ `, issueID, otherWorkspaceID, testUserID, time.Now().UTC().Add(-time.Hour)).Scan(&foreignID); err != nil {
+ t.Fatalf("seed foreign-workspace comment: %v", err)
+ }
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ bulkSeedComments(t, issueID, base, commentHardCap+50)
+ strayID := seedCommentRow(
+ t,
+ issueID,
+ time.Now().UTC().Truncate(time.Second),
+ "reply with a foreign-workspace parent",
+ &foreignID,
+ nil,
+ )
+
+ _, rows := listComments(t, issueID, "")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+
+ for _, c := range rows {
+ if c.ID == foreignID {
+ t.Error("a comment from another workspace leaked into this workspace's response")
+ }
+ if c.ID == strayID {
+ t.Error("the reply with an out-of-workspace parent was returned as an orphan")
+ }
+ }
+ assertNoOrphanCommentRows(t, rows)
+}
+
+// TestListComments_CrossWorkspaceDescendantNeverCrossesBoundary covers the
+// downward half of completeCommentThreads. The restored root belongs to this
+// workspace, but one of its stored children does not; the batched descendant
+// query must not pull that child into the response.
+func TestListComments_CrossWorkspaceDescendantNeverCrossesBoundary(t *testing.T) {
+ ctx := context.Background()
+ issueID := createIssueForTimeline(t, "cross workspace descendant")
+
+ var otherWorkspaceID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description, issue_prefix)
+ VALUES ('Comment descendant boundary', 'comment-descendant-boundary-' || gen_random_uuid()::text,
+ 'Foreign workspace', 'CDB')
+ RETURNING id
+ `).Scan(&otherWorkspaceID); err != nil {
+ t.Fatalf("insert foreign workspace: %v", err)
+ }
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ rootID := seedCommentRow(t, issueID, base, "old local root", nil, nil)
+ var foreignChildID string
+ t.Cleanup(func() {
+ if foreignChildID != "" {
+ testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, foreignChildID)
+ }
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, otherWorkspaceID)
+ })
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type,
+ created_at, updated_at, parent_id)
+ VALUES ($1, $2, 'member', $3, 'foreign-workspace child', 'comment', $4, $4, $5)
+ RETURNING id
+ `, issueID, otherWorkspaceID, testUserID, base.Add(time.Second), rootID).Scan(&foreignChildID); err != nil {
+ t.Fatalf("seed foreign-workspace child: %v", err)
+ }
+
+ bulkSeedComments(t, issueID, base.Add(time.Minute), commentHardCap+50)
+ freshReplyID := seedCommentRow(
+ t,
+ issueID,
+ time.Now().UTC().Truncate(time.Second),
+ "fresh local reply",
+ &rootID,
+ nil,
+ )
+
+ _, rows := listComments(t, issueID, "")
+ if rows == nil {
+ t.Fatal("ListComments returned no rows")
+ }
+
+ present := make(map[string]struct{}, len(rows))
+ for _, c := range rows {
+ present[c.ID] = struct{}{}
+ }
+ if _, leaked := present[foreignChildID]; leaked {
+ t.Error("a descendant from another workspace leaked into the response")
+ }
+ if _, ok := present[rootID]; !ok {
+ t.Error("the same-workspace root was not restored")
+ }
+ if _, ok := present[freshReplyID]; !ok {
+ t.Error("the same-workspace fresh reply is missing")
+ }
+ assertNoOrphanCommentRows(t, rows)
+}
diff --git a/server/internal/handler/comment_list_test.go b/server/internal/handler/comment_list_test.go
index 9cc404efd2..3d1bd73930 100644
--- a/server/internal/handler/comment_list_test.go
+++ b/server/internal/handler/comment_list_test.go
@@ -262,6 +262,46 @@ func TestListComments_RootsOnlyReturnsThreadStats(t *testing.T) {
}
}
+// TestListComments_RootAndThreadViewsPreserveAttributionFields guards explicit
+// SQL projections from drifting behind the comment table. Both fields affect
+// UI rendering and task lineage, so silently zeroing them changes behavior.
+func TestListComments_RootAndThreadViewsPreserveAttributionFields(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newCommentListFixture(t)
+
+ sourceTaskID := "11111111-2222-3333-4444-555555555555"
+ quickActionID := "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
+ for _, commentID := range []string{fx.Root1, fx.R1a} {
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE comment
+ SET source_task_id = $1, quick_action_id = $2
+ WHERE id = $3
+ `, sourceTaskID, quickActionID, commentID); err != nil {
+ t.Fatalf("stamp attribution fields on %s: %v", commentID, err)
+ }
+ }
+
+ assertFields := func(label string, row CommentResponse) {
+ t.Helper()
+ if row.SourceTaskID == nil || *row.SourceTaskID != sourceTaskID {
+ t.Errorf("%s source_task_id = %v, want %s", label, row.SourceTaskID, sourceTaskID)
+ }
+ if row.QuickActionID == nil || *row.QuickActionID != quickActionID {
+ t.Errorf("%s quick_action_id = %v, want %s", label, row.QuickActionID, quickActionID)
+ }
+ }
+
+ _, roots := listComments(t, fx.IssueID, "roots_only=true")
+ assertFields("roots-only root", byID(roots)[fx.Root1])
+
+ _, thread := listComments(t, fx.IssueID, "thread="+fx.R1a)
+ threadByID := byID(thread)
+ assertFields("thread root", threadByID[fx.Root1])
+ assertFields("thread reply", threadByID[fx.R1a])
+}
+
func assertRootStat(t *testing.T, c CommentResponse, label string, wantReplies int, wantLastActivity time.Time) {
t.Helper()
if c.ReplyCount == nil {
@@ -490,6 +530,29 @@ func TestListComments_ThreadAnchorErrors(t *testing.T) {
})
}
+// TestListComments_ThreadRootWalkFailsClosedAcrossIssueBoundary constructs the
+// anomalous shape the schema permits: a local reply whose parent belongs to
+// another issue. Every recursive root-walk level must keep the issue predicate,
+// so the foreign root is neither returned nor used to open a thread.
+func TestListComments_ThreadRootWalkFailsClosedAcrossIssueBoundary(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ foreignIssueID := createIssueForTimeline(t, "foreign thread root issue")
+ issueID := createIssueForTimeline(t, "local thread reply issue")
+ base := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)
+ foreignRootID := seedCommentRow(t, foreignIssueID, base, "foreign root", nil, nil)
+ localReplyID := seedCommentRow(t, issueID, base.Add(time.Second), "local anomalous reply", &foreignRootID, nil)
+
+ w, rows := listComments(t, issueID, "thread="+localReplyID)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("cross-issue root walk status = %d, want 404: %s", w.Code, w.Body.String())
+ }
+ if rows != nil {
+ t.Fatalf("cross-issue root walk returned rows: %v", ids(rows))
+ }
+}
+
// TestListComments_RecentReturnsMostRecentlyActiveThreads pins the
// thread-grouped semantics from #2340. Row-based "newest N comments" would
// have surfaced [root2, r2a, r2b] for N=3 — a single thread's tail. The
diff --git a/server/internal/handler/timeline_hardcap_test.go b/server/internal/handler/timeline_hardcap_test.go
new file mode 100644
index 0000000000..b30e9a095f
--- /dev/null
+++ b/server/internal/handler/timeline_hardcap_test.go
@@ -0,0 +1,540 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Regression tests for MUL-5492: the per-issue timeline cap used to be applied
+// with ORDER BY created_at ASC, so once an issue accumulated more than
+// timelineHardCap rows the cap discarded the NEWEST ones and the timeline
+// silently appeared to stop at some point in the past.
+//
+// These tests pin four properties:
+// 1. the cap keeps the newest window, not the oldest;
+// 2. each list is capped independently — activity truncation must never delete
+// comments, so the range may legitimately hold comments older than the
+// oldest activity;
+// 3. every retained reply arrives with a parent chain that reaches a root in
+// the same response, because an orphaned reply is invisible in the UI;
+// 4. truncation is reported instead of being silent, naming which kinds were
+// affected.
+
+// fetchTimelineRecorder issues GET /timeline and returns the raw recorder so
+// tests can assert on response headers as well as the body.
+func fetchTimelineRecorder(t *testing.T, issueID, rawQuery string) *httptest.ResponseRecorder {
+ t.Helper()
+ target := "/api/issues/" + issueID + "/timeline"
+ if rawQuery != "" {
+ target += "?" + rawQuery
+ }
+ w := httptest.NewRecorder()
+ req := newRequest("GET", target, nil)
+ req = withURLParam(req, "id", issueID)
+ testHandler.ListTimeline(w, req)
+ return w
+}
+
+func decodeTimelineEntries(t *testing.T, w *httptest.ResponseRecorder) []TimelineEntry {
+ t.Helper()
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var entries []TimelineEntry
+ if err := json.Unmarshal(w.Body.Bytes(), &entries); err != nil {
+ t.Fatalf("decode timeline: %v", err)
+ }
+ return entries
+}
+
+// bulkSeedActivities inserts n activities one second apart starting at start.
+// One statement, because these tests need thousands of rows.
+func bulkSeedActivities(t *testing.T, issueID string, start time.Time, n int) {
+ t.Helper()
+ _, err := testPool.Exec(context.Background(), `
+ INSERT INTO activity_log (workspace_id, issue_id, actor_type, actor_id, action, details, created_at)
+ SELECT $1, $2, 'member', $3, 'status_changed', '{"from":"todo","to":"in_progress"}'::jsonb,
+ $4::timestamptz + (g * interval '1 second')
+ FROM generate_series(0, $5::int - 1) AS g
+ `, testWorkspaceID, issueID, testUserID, start, n)
+ if err != nil {
+ t.Fatalf("bulk seed %d activities: %v", n, err)
+ }
+}
+
+// bulkSeedComments inserts n comments one second apart starting at start.
+func bulkSeedComments(t *testing.T, issueID string, start time.Time, n int) {
+ t.Helper()
+ _, err := testPool.Exec(context.Background(), `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at, updated_at)
+ SELECT $1, $2, 'member', $3, 'bulk comment ' || g, 'comment',
+ $4::timestamptz + (g * interval '1 second'),
+ $4::timestamptz + (g * interval '1 second')
+ FROM generate_series(0, $5::int - 1) AS g
+ `, issueID, testWorkspaceID, testUserID, start, n)
+ if err != nil {
+ t.Fatalf("bulk seed %d comments: %v", n, err)
+ }
+}
+
+// bulkSeedReplies inserts n direct replies to parentID one second apart.
+func bulkSeedReplies(t *testing.T, issueID, parentID string, start time.Time, n int) {
+ t.Helper()
+ _, err := testPool.Exec(context.Background(), `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type,
+ created_at, updated_at, parent_id)
+ SELECT $1, $2, 'member', $3, 'bulk reply ' || g, 'comment',
+ $4::timestamptz + (g * interval '1 second'),
+ $4::timestamptz + (g * interval '1 second'),
+ $5
+ FROM generate_series(0, $6::int - 1) AS g
+ `, issueID, testWorkspaceID, testUserID, start, parentID, n)
+ if err != nil {
+ t.Fatalf("bulk seed %d replies: %v", n, err)
+ }
+}
+
+// seedComment inserts a single comment at an exact timestamp, optionally as a
+// reply, and returns its id.
+func seedComment(t *testing.T, issueID string, at time.Time, content string, parentID *string) string {
+ t.Helper()
+ var id string
+ err := testPool.QueryRow(context.Background(), `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at, updated_at, parent_id)
+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5, $5, $6)
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID, content, at, parentID).Scan(&id)
+ if err != nil {
+ t.Fatalf("seed comment %q: %v", content, err)
+ }
+ return id
+}
+
+func countByType(entries []TimelineEntry) (comments, activities int) {
+ for _, e := range entries {
+ switch e.Type {
+ case "comment":
+ comments++
+ case "activity":
+ activities++
+ }
+ }
+ return
+}
+
+// mustParseTS parses a timeline timestamp into an instant. Tests compare
+// instants, never strings: the API renders timestamps in the DB session's
+// offset, so two equal instants can have different textual forms and a string
+// comparison would silently pass for the wrong reason.
+func mustParseTS(t *testing.T, label, raw string) time.Time {
+ t.Helper()
+ parsed, err := time.Parse(time.RFC3339, raw)
+ if err != nil {
+ t.Fatalf("parse %s timestamp %q: %v", label, raw, err)
+ }
+ return parsed
+}
+
+// TestListTimeline_HardCapKeepsNewestActivities is the direct regression: with
+// more activities than the cap, the response must be the newest window. Before
+// the fix the LAST seeded activity was missing and the FIRST one was present.
+func TestListTimeline_HardCapKeepsNewestActivities(t *testing.T) {
+ issueID := createIssueForTimeline(t, "hard cap keeps newest")
+
+ // 100 rows past the cap, ending "now" so the newest row is unambiguous.
+ const total = timelineHardCap + 100
+ start := time.Now().UTC().Add(-time.Duration(total) * time.Second).Truncate(time.Second)
+ bulkSeedActivities(t, issueID, start, total)
+
+ oldest := start
+ newest := start.Add(time.Duration(total-1) * time.Second)
+
+ w := fetchTimelineRecorder(t, issueID, "")
+ entries := decodeTimelineEntries(t, w)
+ _, activityCount := countByType(entries)
+
+ if activityCount != timelineHardCap {
+ t.Errorf("activity count = %d, want %d (the cap)", activityCount, timelineHardCap)
+ }
+
+ // The newest row must be present: this is the assertion that failed before.
+ if got := mustParseTS(t, "last entry", entries[len(entries)-1].CreatedAt); !got.Equal(newest) {
+ t.Errorf("last entry created_at = %s, want newest seeded %s", got, newest)
+ }
+ // ...and the oldest must have been the one dropped.
+ if got := mustParseTS(t, "first entry", entries[0].CreatedAt); got.Equal(oldest) {
+ t.Errorf("oldest seeded row %s survived the cap; the cap is still trimming the wrong end", got)
+ }
+
+ if got := w.Header().Get(HeaderTimelineTruncated); got != "activity" {
+ t.Errorf("%s = %q, want \"activity\": truncation must not be silent", HeaderTimelineTruncated, got)
+ }
+}
+
+// TestListTimeline_ActivityTruncationDoesNotDropComments replaces an earlier
+// test that asserted the opposite. That test pinned a cross-kind clamp: both
+// lists trimmed to a shared floor so the window was provably contiguous. The
+// clamp was wrong — comments essentially never reach the cap while activity does,
+// so the shared floor was almost always the activity floor deleting comments that
+// had been fetched successfully. Deleting content to buy a cosmetic property is
+// the worse trade, and it is what created orphaned replies.
+//
+// The window is now allowed to hold comments older than the oldest activity. That
+// costs activity density in the older range, which is metadata, and it is
+// reported rather than hidden.
+func TestListTimeline_ActivityTruncationDoesNotDropComments(t *testing.T) {
+ issueID := createIssueForTimeline(t, "activity truncation keeps comments")
+
+ const activityTotal = timelineHardCap + 100
+ activityStart := time.Now().UTC().Add(-time.Duration(activityTotal) * time.Second).Truncate(time.Second)
+ // Comments reach far further back than the activity window can.
+ commentStart := activityStart.Add(-2 * time.Hour)
+
+ bulkSeedActivities(t, issueID, activityStart, activityTotal)
+ bulkSeedComments(t, issueID, commentStart, 50)
+
+ w := fetchTimelineRecorder(t, issueID, "")
+ entries := decodeTimelineEntries(t, w)
+ commentCount, activityCount := countByType(entries)
+
+ // Every comment survives even though all 50 predate the oldest activity.
+ if commentCount != 50 {
+ t.Errorf("comment count = %d, want 50: activity truncation must not delete comments", commentCount)
+ }
+ if activityCount != timelineHardCap {
+ t.Errorf("activity count = %d, want %d", activityCount, timelineHardCap)
+ }
+ // Only the activity list was truncated, and the header says exactly that.
+ if got := w.Header().Get(HeaderTimelineTruncated); got != "activity" {
+ t.Errorf("%s = %q, want \"activity\"", HeaderTimelineTruncated, got)
+ }
+}
+
+// TestListTimeline_NoOrphanedReplies is the regression for the review finding.
+// Scenario: a thread root older than the comment window, a fresh reply to it
+// inside the window. The reply must not come back without its parent — an orphan
+// is invisible in the UI, not merely mis-nested (MUL-1847 / #2263).
+func TestListTimeline_NoOrphanedReplies(t *testing.T) {
+ issueID := createIssueForTimeline(t, "no orphaned replies")
+
+ // An old root, then enough newer comments to push it out of the window,
+ // then a fresh reply to that old root.
+ base := time.Now().UTC().Add(-3 * time.Hour).Truncate(time.Second)
+ rootID := seedComment(t, issueID, base, "old thread root", nil)
+ bulkSeedComments(t, issueID, base.Add(time.Minute), timelineHardCap+50)
+ replyID := seedComment(t, issueID, time.Now().UTC().Truncate(time.Second), "fresh reply to old root", &rootID)
+
+ w := fetchTimelineRecorder(t, issueID, "")
+ entries := decodeTimelineEntries(t, w)
+
+ ids := make(map[string]TimelineEntry, len(entries))
+ for _, e := range entries {
+ ids[e.ID] = e
+ }
+
+ if _, ok := ids[replyID]; !ok {
+ t.Fatal("the fresh reply is missing entirely")
+ }
+ if _, ok := ids[rootID]; !ok {
+ t.Error("the reply's parent (an old thread root) was not backfilled: the reply would be invisible in the UI")
+ }
+ assertNoOrphanedReplies(t, entries)
+}
+
+// TestListTimeline_RootResolvedThreadIsComplete is the root-resolution variant
+// of the partial-thread regression. The timeline UI folds immediately when the
+// root has resolved_at, so returning only a backfilled root plus the newest
+// reply would make its collapsed count and author list look complete while five
+// older replies were missing.
+func TestListTimeline_RootResolvedThreadIsComplete(t *testing.T) {
+ issueID := createIssueForTimeline(t, "root-resolved thread is complete")
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ resolvedAt := base
+ rootID := seedCommentRow(t, issueID, base, "settled topic", nil, &resolvedAt)
+ oldReplyIDs := make([]string, 0, 5)
+ for i := 0; i < 5; i++ {
+ oldReplyIDs = append(oldReplyIDs, seedCommentRow(
+ t,
+ issueID,
+ base.Add(time.Duration(i+1)*time.Second),
+ "old reply",
+ &rootID,
+ nil,
+ ))
+ }
+
+ bulkSeedComments(t, issueID, base.Add(time.Minute), timelineHardCap+50)
+ freshReplyID := seedCommentRow(
+ t,
+ issueID,
+ time.Now().UTC().Truncate(time.Second),
+ "fresh reply",
+ &rootID,
+ nil,
+ )
+
+ w := fetchTimelineRecorder(t, issueID, "")
+ entries := decodeTimelineEntries(t, w)
+ byID := make(map[string]TimelineEntry, len(entries))
+ for _, entry := range entries {
+ byID[entry.ID] = entry
+ }
+
+ if _, ok := byID[rootID]; !ok {
+ t.Fatal("resolved root is missing")
+ }
+ for _, id := range append(oldReplyIDs, freshReplyID) {
+ if _, ok := byID[id]; !ok {
+ t.Errorf("resolved thread is partial: comment %s is missing", id)
+ }
+ }
+ assertNoOrphanedReplies(t, entries)
+}
+
+// TestListTimeline_ReplyResolutionOutsideWindowIsRestored covers the opposite
+// stale-state failure. When the resolution reply falls outside the newest
+// window but a later reply remains, deriveThreadResolution would otherwise see
+// no resolution and render an already-resolved thread as unresolved.
+func TestListTimeline_ReplyResolutionOutsideWindowIsRestored(t *testing.T) {
+ issueID := createIssueForTimeline(t, "reply resolution is restored")
+
+ base := time.Now().UTC().Add(-4 * time.Hour).Truncate(time.Second)
+ rootID := seedCommentRow(t, issueID, base, "root question", nil, nil)
+ resolvedAt := base.Add(time.Second)
+ resolutionID := seedCommentRow(
+ t,
+ issueID,
+ resolvedAt,
+ "the conclusion",
+ &rootID,
+ &resolvedAt,
+ )
+
+ bulkSeedComments(t, issueID, base.Add(time.Minute), timelineHardCap+50)
+ freshReplyID := seedCommentRow(
+ t,
+ issueID,
+ time.Now().UTC().Truncate(time.Second),
+ "later follow-up",
+ &rootID,
+ nil,
+ )
+
+ w := fetchTimelineRecorder(t, issueID, "")
+ entries := decodeTimelineEntries(t, w)
+ byID := make(map[string]TimelineEntry, len(entries))
+ for _, entry := range entries {
+ byID[entry.ID] = entry
+ }
+
+ resolution, ok := byID[resolutionID]
+ if !ok {
+ t.Fatal("resolution reply outside the newest window was not restored")
+ }
+ if resolution.ResolvedAt == nil {
+ t.Fatal("restored resolution reply lost resolved_at")
+ }
+ if _, ok := byID[freshReplyID]; !ok {
+ t.Fatal("fresh reply is missing")
+ }
+ assertNoOrphanedReplies(t, entries)
+}
+
+// TestListTimeline_OversizedAffectedThreadIsDroppedWhole pins the bounded
+// fallback. If one cut thread cannot fit in the shared context budget, returning
+// its root plus an arbitrary suffix would let old clients fold partial data.
+// The whole affected thread must disappear while truncation remains explicit.
+func TestListTimeline_OversizedAffectedThreadIsDroppedWhole(t *testing.T) {
+ issueID := createIssueForTimeline(t, "oversized affected thread is dropped")
+
+ base := time.Now().UTC().Add(-6 * time.Hour).Truncate(time.Second)
+ rootID := seedComment(t, issueID, base, "oversized thread root", nil)
+ bulkSeedReplies(
+ t,
+ issueID,
+ rootID,
+ base.Add(time.Second),
+ commentHardCap+commentThreadContextBudget+1,
+ )
+
+ w := fetchTimelineRecorder(t, issueID, "")
+ entries := decodeTimelineEntries(t, w)
+ commentCount, _ := countByType(entries)
+ if commentCount != 0 {
+ t.Errorf("comment count = %d, want 0: an over-budget affected thread must be dropped whole", commentCount)
+ }
+ if got := w.Header().Get(HeaderTimelineTruncated); got != "comment" {
+ t.Errorf("%s = %q, want \"comment\"", HeaderTimelineTruncated, got)
+ }
+}
+
+// assertNoOrphanedReplies pins the invariant issue-detail.tsx relies on and
+// foldResolvedThreads requires: every returned reply's parent is in the same set.
+// More valuable than any single scenario — it holds for every shape of response.
+func assertNoOrphanedReplies(t *testing.T, entries []TimelineEntry) {
+ t.Helper()
+ present := make(map[string]struct{}, len(entries))
+ for _, e := range entries {
+ present[e.ID] = struct{}{}
+ }
+ for _, e := range entries {
+ if e.Type != "comment" || e.ParentID == nil || *e.ParentID == "" {
+ continue
+ }
+ if _, ok := present[*e.ParentID]; !ok {
+ t.Errorf("comment %s references parent %s which is absent from the response", e.ID, *e.ParentID)
+ }
+ }
+}
+
+// TestListTimeline_BackfilledRootKeepsQuickActionID guards the projection of
+// newly-added comment columns through parent-chain completion. An earlier
+// revision hand-copied SQL rows into db.Comment field by field, which silently
+// dropped quick_action_id when main added it — a backfilled quick-action root
+// would have rendered as a raw prompt instead of a quick-action card. The query
+// now returns db.Comment directly so new columns cannot be lost this way.
+func TestListTimeline_BackfilledRootKeepsQuickActionID(t *testing.T) {
+ issueID := createIssueForTimeline(t, "backfilled root keeps quick_action_id")
+
+ base := time.Now().UTC().Add(-3 * time.Hour).Truncate(time.Second)
+ quickActionID := "11111111-2222-3333-4444-555555555555"
+ var rootID string
+ err := testPool.QueryRow(context.Background(), `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type,
+ created_at, updated_at, quick_action_id)
+ VALUES ($1, $2, 'member', $3, 'quick action root', 'comment', $4, $4, $5)
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID, base, quickActionID).Scan(&rootID)
+ if err != nil {
+ t.Fatalf("seed quick-action root: %v", err)
+ }
+
+ // Push the root out of the window, then reply to it from inside the window.
+ bulkSeedComments(t, issueID, base.Add(time.Minute), timelineHardCap+50)
+ seedComment(t, issueID, time.Now().UTC().Truncate(time.Second), "reply to quick action root", &rootID)
+
+ w := fetchTimelineRecorder(t, issueID, "")
+ entries := decodeTimelineEntries(t, w)
+
+ var root *TimelineEntry
+ for i := range entries {
+ if entries[i].ID == rootID {
+ root = &entries[i]
+ }
+ }
+ if root == nil {
+ t.Fatal("the quick-action root was not backfilled")
+ }
+ if root.QuickActionID == nil {
+ t.Fatal("quick_action_id was dropped on the backfilled root: the UI would show a raw prompt instead of a quick-action card")
+ }
+ if *root.QuickActionID != quickActionID {
+ t.Errorf("quick_action_id = %s, want %s", *root.QuickActionID, quickActionID)
+ }
+ assertNoOrphanedReplies(t, entries)
+}
+
+// TestListTimeline_ExactlyAtCapIsNotTruncated pins the cap+1 probe read. An
+// issue that happens to hold exactly timelineHardCap rows is complete, so
+// reporting it as truncated would be a lie and would trigger a needless
+// ancestor-backfill query.
+func TestListTimeline_ExactlyAtCapIsNotTruncated(t *testing.T) {
+ issueID := createIssueForTimeline(t, "exactly at cap")
+
+ start := time.Now().UTC().Add(-time.Duration(timelineHardCap) * time.Second).Truncate(time.Second)
+ bulkSeedActivities(t, issueID, start, timelineHardCap)
+
+ w := fetchTimelineRecorder(t, issueID, "")
+ entries := decodeTimelineEntries(t, w)
+
+ if got := w.Header().Get(HeaderTimelineTruncated); got != "" {
+ t.Errorf("%s = %q, want unset: exactly-at-cap is a complete timeline", HeaderTimelineTruncated, got)
+ }
+ _, activityCount := countByType(entries)
+ if activityCount != timelineHardCap {
+ t.Errorf("activity count = %d, want %d", activityCount, timelineHardCap)
+ }
+}
+
+// TestListTimeline_WrappedShapeReportsHasMoreBefore checks the legacy wrapped
+// response also stops claiming the timeline is complete. has_more_before was
+// hardcoded false.
+func TestListTimeline_WrappedShapeReportsHasMoreBefore(t *testing.T) {
+ issueID := createIssueForTimeline(t, "wrapped has_more_before")
+
+ const total = timelineHardCap + 10
+ start := time.Now().UTC().Add(-time.Duration(total) * time.Second).Truncate(time.Second)
+ bulkSeedActivities(t, issueID, start, total)
+
+ w := fetchTimelineRecorder(t, issueID, "limit=50")
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var resp timelinePaginatedResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode wrapped response: %v", err)
+ }
+ if !resp.HasMoreBefore {
+ t.Error("has_more_before = false, want true when the cap clamped the window")
+ }
+ if resp.HasMoreAfter {
+ t.Error("has_more_after = true, want false: the newest end is always complete now")
+ }
+ // The wrapped shape is newest-first, so entry 0 is the newest row.
+ newest := start.Add(time.Duration(total-1) * time.Second)
+ if len(resp.Entries) == 0 {
+ t.Fatal("wrapped response returned no entries")
+ }
+ if got := mustParseTS(t, "newest entry", resp.Entries[0].CreatedAt); !got.Equal(newest) {
+ t.Errorf("first (newest-first) entry created_at = %s, want %s", got, newest)
+ }
+}
+
+// TestListCommentsForIssue_KeepsNewestWindow covers the same query from the
+// comment-list endpoint's side, since ListCommentsForIssue is shared. The
+// ascending contract must be preserved while the cap now bites at the old end.
+func TestListCommentsForIssue_KeepsNewestWindow(t *testing.T) {
+ issueID := createIssueForTimeline(t, "comment cap keeps newest")
+
+ const total = 30
+ start := time.Now().UTC().Add(-time.Duration(total) * time.Second).Truncate(time.Second)
+ bulkSeedComments(t, issueID, start, total)
+
+ issueUUID := parseUUID(issueID)
+ wsUUID := parseUUID(testWorkspaceID)
+
+ const limit = 10
+ rows, err := testHandler.Queries.ListCommentsForIssue(context.Background(), db.ListCommentsForIssueParams{
+ IssueID: issueUUID,
+ WorkspaceID: wsUUID,
+ Limit: limit,
+ })
+ if err != nil {
+ t.Fatalf("ListCommentsForIssue: %v", err)
+ }
+ if len(rows) != limit {
+ t.Fatalf("row count = %d, want %d", len(rows), limit)
+ }
+ // Newest window: the last `limit` rows of the seeded range.
+ wantFirst := start.Add(time.Duration(total-limit) * time.Second)
+ wantLast := start.Add(time.Duration(total-1) * time.Second)
+ if got := rows[0].CreatedAt.Time.UTC(); !got.Equal(wantFirst) {
+ t.Errorf("first row created_at = %s, want %s (newest window, ascending)", got, wantFirst)
+ }
+ if got := rows[len(rows)-1].CreatedAt.Time.UTC(); !got.Equal(wantLast) {
+ t.Errorf("last row created_at = %s, want %s (newest row)", got, wantLast)
+ }
+ // Ascending order preserved for every existing caller.
+ for i := 1; i < len(rows); i++ {
+ if rows[i].CreatedAt.Time.Before(rows[i-1].CreatedAt.Time) {
+ t.Fatalf("row %d is older than row %d: ascending contract broken", i, i-1)
+ }
+ }
+}
diff --git a/server/migrations/241_comment_parent_lookup_index.down.sql b/server/migrations/241_comment_parent_lookup_index.down.sql
new file mode 100644
index 0000000000..0063c9893b
--- /dev/null
+++ b/server/migrations/241_comment_parent_lookup_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_workspace_issue_parent;
diff --git a/server/migrations/241_comment_parent_lookup_index.up.sql b/server/migrations/241_comment_parent_lookup_index.up.sql
new file mode 100644
index 0000000000..4b99fe802d
--- /dev/null
+++ b/server/migrations/241_comment_parent_lookup_index.up.sql
@@ -0,0 +1,6 @@
+-- Recursive thread expansion repeatedly looks up same-tenant children by
+-- parent_id. Keep this as the migration's only statement: production index
+-- builds must be concurrent so comment writes remain available.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comment_workspace_issue_parent
+ ON comment (workspace_id, issue_id, parent_id)
+ WHERE parent_id IS NOT NULL;
diff --git a/server/pkg/db/generated/activity.sql.go b/server/pkg/db/generated/activity.sql.go
index 515f7ebfa0..87f7db0bea 100644
--- a/server/pkg/db/generated/activity.sql.go
+++ b/server/pkg/db/generated/activity.sql.go
@@ -145,10 +145,13 @@ func (q *Queries) HasSquadLeaderNoActionEvaluationForTask(ctx context.Context, a
}
const listActivitiesForIssue = `-- name: ListActivitiesForIssue :many
-SELECT id, workspace_id, issue_id, actor_type, actor_id, action, details, created_at FROM activity_log
-WHERE issue_id = $1
+SELECT id, workspace_id, issue_id, actor_type, actor_id, action, details, created_at FROM (
+ SELECT id, workspace_id, issue_id, actor_type, actor_id, action, details, created_at FROM activity_log
+ WHERE issue_id = $1
+ ORDER BY created_at DESC, id DESC
+ LIMIT $2
+) AS recent
ORDER BY created_at ASC, id ASC
-LIMIT $2
`
type ListActivitiesForIssueParams struct {
@@ -156,8 +159,21 @@ type ListActivitiesForIssueParams struct {
Limit int32 `json:"limit"`
}
-// All activities for an issue in chronological order, capped at $2 (DB safety
-// net to bound the response).
+// The NEWEST $2 activities for an issue, returned in chronological order.
+//
+// The cap has to bite at the OLD end, not the new one. The inner query takes
+// the window with the keyset ordering (created_at DESC, id DESC), which
+// idx_activity_log_issue_keyset (migration 068) satisfies without a sort step —
+// it is not an index-only scan, since the index does not cover the columns
+// SELECT * needs, so the heap is still read for the rows in the window. The
+// outer query re-sorts ascending so every caller keeps the chronological
+// contract it already had.
+//
+// Capping with ORDER BY created_at ASC instead discards the newest rows, which
+// made a busy issue's timeline appear to stop at some point in the past with no
+// indication anything was missing. Activity is machine-paced (description
+// autosave, every agent run, status/assignee changes), so this was reachable in
+// normal use, not only on pathological issues (MUL-5492).
func (q *Queries) ListActivitiesForIssue(ctx context.Context, arg ListActivitiesForIssueParams) ([]ActivityLog, error) {
rows, err := q.db.Query(ctx, listActivitiesForIssue, arg.IssueID, arg.Limit)
if err != nil {
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index d2c3a0a60e..afe1454e96 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -440,11 +440,144 @@ func (q *Queries) HasAgentRepliedInThread(ctx context.Context, arg HasAgentRepli
return has_replied, err
}
-const listCommentsForIssue = `-- name: ListCommentsForIssue :many
+const listChildCommentsForParents = `-- name: ListChildCommentsForParents :many
SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment
-WHERE issue_id = $1 AND workspace_id = $2
+WHERE parent_id = ANY($1::uuid[])
+ AND issue_id = $2
+ AND workspace_id = $3
+ AND (created_at, id) <= ($4::timestamptz, $5::uuid)
+ORDER BY parent_id ASC, created_at ASC, id ASC
+LIMIT $6
+`
+
+type ListChildCommentsForParentsParams struct {
+ ParentIds []pgtype.UUID `json:"parent_ids"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ThroughAt pgtype.Timestamptz `json:"through_at"`
+ ThroughID pgtype.UUID `json:"through_id"`
+ RowLimit int32 `json:"row_limit"`
+}
+
+// Fetch one descendant level for a bounded set of parent comments. Each parent
+// maps back to its thread root in the Go breadth-first walk, avoiding one query
+// per root.
+//
+// Both tenant predicates apply at every level. row_limit is always a probe
+// limit owned by completeCommentThreads; it prevents a wide level from defeating
+// the response budget. through_at/through_id pin the walk to the newest row in
+// the original window, so replies created concurrently are left to realtime
+// delivery instead of making the multi-query snapshot internally inconsistent.
+func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChildCommentsForParentsParams) ([]Comment, error) {
+ rows, err := q.db.Query(ctx, listChildCommentsForParents,
+ arg.ParentIds,
+ arg.IssueID,
+ arg.WorkspaceID,
+ arg.ThroughAt,
+ arg.ThroughID,
+ arg.RowLimit,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Comment{}
+ for rows.Next() {
+ var i Comment
+ if err := rows.Scan(
+ &i.ID,
+ &i.IssueID,
+ &i.AuthorType,
+ &i.AuthorID,
+ &i.Content,
+ &i.Type,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.ParentID,
+ &i.WorkspaceID,
+ &i.ResolvedAt,
+ &i.ResolvedByType,
+ &i.ResolvedByID,
+ &i.SourceTaskID,
+ &i.QuickActionID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listCommentsByIDsForIssue = `-- name: ListCommentsByIDsForIssue :many
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment
+WHERE id = ANY($1::uuid[])
+ AND issue_id = $2
+ AND workspace_id = $3
+ORDER BY created_at ASC, id ASC
+`
+
+type ListCommentsByIDsForIssueParams struct {
+ Ids []pgtype.UUID `json:"ids"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// The subset of @ids that exists within this issue and workspace.
+//
+// Used to walk parent chains one level at a time (see completeCommentThreads).
+// Deliberately NOT a recursive CTE: an earlier revision walked parent_id upward
+// in SQL, which had no depth bound — a deep chain could pull tens of thousands of
+// ancestors back and defeat the whole point of the row cap — and its recursive
+// branch matched on parent_id alone, so a stray cross-workspace parent reference
+// would have dragged another tenant's comments into the response. Both tenant
+// columns are required here on every level, and the caller owns the budget.
+func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListCommentsByIDsForIssueParams) ([]Comment, error) {
+ rows, err := q.db.Query(ctx, listCommentsByIDsForIssue, arg.Ids, arg.IssueID, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Comment{}
+ for rows.Next() {
+ var i Comment
+ if err := rows.Scan(
+ &i.ID,
+ &i.IssueID,
+ &i.AuthorType,
+ &i.AuthorID,
+ &i.Content,
+ &i.Type,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.ParentID,
+ &i.WorkspaceID,
+ &i.ResolvedAt,
+ &i.ResolvedByType,
+ &i.ResolvedByID,
+ &i.SourceTaskID,
+ &i.QuickActionID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listCommentsForIssue = `-- name: ListCommentsForIssue :many
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM (
+ SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment
+ WHERE issue_id = $1 AND workspace_id = $2
+ ORDER BY created_at DESC, id DESC
+ LIMIT $3
+) AS recent
ORDER BY created_at ASC, id ASC
-LIMIT $3
`
type ListCommentsForIssueParams struct {
@@ -453,9 +586,23 @@ type ListCommentsForIssueParams struct {
Limit int32 `json:"limit"`
}
-// All comments for an issue in chronological order, capped at $3 (DB safety
-// net). Issue p99 is ~30 comments, max ever observed in prod is ~1.1k, so
-// the handler-side cap of 2000 is purely defensive.
+// The NEWEST $3 comments for an issue, returned in chronological order.
+//
+// Same shape and same reason as ListActivitiesForIssue: the inner query takes
+// the window with the keyset ordering so the cap discards the OLDEST rows, and
+// the outer query restores the ascending contract callers rely on. The ordering
+// of the inner window is satisfied by idx_comment_issue_keyset (migration 068);
+// the outer query sorts that bounded window back into chronological order.
+//
+// A newest-N window is a suffix of the timeline, and unlike a prefix it is NOT
+// closed under "parent of": a reply is always newer than its parent, so an old
+// thread root can fall outside the window while a fresh reply to it stays
+// inside. Callers that render threads must close the parent chains afterwards —
+// see completeCommentThreads (MUL-5492).
+//
+// The cap is still purely defensive here — issue p99 is ~30 comments and the max
+// ever observed in prod is ~1.1k — but "defensive" is not a reason to drop the
+// newest rows when it does fire (MUL-5492).
func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForIssueParams) ([]Comment, error) {
rows, err := q.db.Query(ctx, listCommentsForIssue, arg.IssueID, arg.WorkspaceID, arg.Limit)
if err != nil {
@@ -583,6 +730,7 @@ picked AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id,
p.root_id AS thread_root_id,
p.last_activity_at AS thread_last_activity_at
FROM picked p
@@ -614,6 +762,8 @@ type ListRecentThreadCommentsForIssueRow struct {
ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
ResolvedByType pgtype.Text `json:"resolved_by_type"`
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
ThreadRootID pgtype.UUID `json:"thread_root_id"`
ThreadLastActivityAt pgtype.Timestamptz `json:"thread_last_activity_at"`
}
@@ -676,6 +826,8 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List
&i.ResolvedAt,
&i.ResolvedByType,
&i.ResolvedByID,
+ &i.SourceTaskID,
+ &i.QuickActionID,
&i.ThreadRootID,
&i.ThreadLastActivityAt,
); err != nil {
@@ -776,7 +928,7 @@ WITH RECURSIVE selected_roots AS (
WHERE c.issue_id = $1
AND c.workspace_id = $2
AND c.parent_id IS NULL
- ORDER BY c.created_at ASC, c.id ASC
+ ORDER BY c.created_at DESC, c.id DESC
LIMIT $3
),
membership(id, root_id, comment_created_at) AS (
@@ -799,6 +951,7 @@ thread_stats AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -827,6 +980,8 @@ type ListRootCommentsForIssueRow struct {
ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
ResolvedByType pgtype.Text `json:"resolved_by_type"`
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
ReplyCount int32 `json:"reply_count"`
LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
}
@@ -838,13 +993,11 @@ type ListRootCommentsForIssueRow struct {
// discussion but also triage which thread to drill into (biggest / most
// recently active) before fetching any specific reply thread.
//
-// `selected_roots` picks the roots we will actually return first (the chrono
-// page of size @row_limit), so the recursive `membership` walk only expands
-// those threads' subtrees instead of every thread in the issue. membership
-// labels each comment with its thread root by walking down from the selected
-// roots, so the counts stay correct even if the schema ever allows
-// reply-of-reply (the write path collapses to root today, but does not enforce
-// it). Mirrors ListRecentThreadCommentsForIssue's stats CTE.
+// `selected_roots` takes the newest @row_limit roots. The final SELECT restores
+// chronological order, so the defensive cap drops the oldest roots without
+// changing the wire order. The recursive `membership` walk only expands those
+// selected threads rather than every thread in the issue, and labels every
+// descendant with its root so the stats stay correct at any reply depth.
func (q *Queries) ListRootCommentsForIssue(ctx context.Context, arg ListRootCommentsForIssueParams) ([]ListRootCommentsForIssueRow, error) {
rows, err := q.db.Query(ctx, listRootCommentsForIssue, arg.IssueID, arg.WorkspaceID, arg.RowLimit)
if err != nil {
@@ -868,6 +1021,8 @@ func (q *Queries) ListRootCommentsForIssue(ctx context.Context, arg ListRootComm
&i.ResolvedAt,
&i.ResolvedByType,
&i.ResolvedByID,
+ &i.SourceTaskID,
+ &i.QuickActionID,
&i.ReplyCount,
&i.LastActivityAt,
); err != nil {
@@ -912,6 +1067,7 @@ thread_stats AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -941,6 +1097,8 @@ type ListRootCommentsSinceForIssueRow struct {
ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
ResolvedByType pgtype.Text `json:"resolved_by_type"`
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
ReplyCount int32 `json:"reply_count"`
LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
}
@@ -980,6 +1138,8 @@ func (q *Queries) ListRootCommentsSinceForIssue(ctx context.Context, arg ListRoo
&i.ResolvedAt,
&i.ResolvedByType,
&i.ResolvedByID,
+ &i.SourceTaskID,
+ &i.QuickActionID,
&i.ReplyCount,
&i.LastActivityAt,
); err != nil {
@@ -993,111 +1153,6 @@ func (q *Queries) ListRootCommentsSinceForIssue(ctx context.Context, arg ListRoo
return items, nil
}
-const listThreadCommentsForIssue = `-- name: ListThreadCommentsForIssue :many
-WITH RECURSIVE root_of AS (
- -- Walk up from the anchor until parent_id IS NULL.
- SELECT c.id, c.parent_id
- FROM comment c
- WHERE c.id = $2 AND c.issue_id = $3 AND c.workspace_id = $4
- UNION ALL
- SELECT p.id, p.parent_id
- FROM comment p
- JOIN root_of r ON p.id = r.parent_id
-),
-thread_root AS (
- SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1
-),
-descendants AS (
- -- Start from the root, then keep adding any comment whose parent is
- -- already in the set. Cycle-safe under PK constraint (a comment cannot
- -- be its own ancestor).
- SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
- c.created_at, c.updated_at, c.parent_id, c.workspace_id,
- c.resolved_at, c.resolved_by_type, c.resolved_by_id
- FROM comment c
- JOIN thread_root tr ON c.id = tr.id
- UNION
- SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
- c.created_at, c.updated_at, c.parent_id, c.workspace_id,
- c.resolved_at, c.resolved_by_type, c.resolved_by_id
- FROM comment c
- JOIN descendants d ON c.parent_id = d.id
- WHERE c.issue_id = $3 AND c.workspace_id = $4
-)
-SELECT id, issue_id, author_type, author_id, content, type,
- created_at, updated_at, parent_id, workspace_id,
- resolved_at, resolved_by_type, resolved_by_id
-FROM descendants
-ORDER BY created_at ASC, id ASC
-LIMIT $1
-`
-
-type ListThreadCommentsForIssueParams struct {
- RowLimit int32 `json:"row_limit"`
- AnchorID pgtype.UUID `json:"anchor_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
-}
-
-type ListThreadCommentsForIssueRow struct {
- ID pgtype.UUID `json:"id"`
- IssueID pgtype.UUID `json:"issue_id"`
- AuthorType string `json:"author_type"`
- AuthorID pgtype.UUID `json:"author_id"`
- Content string `json:"content"`
- Type string `json:"type"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- ParentID pgtype.UUID `json:"parent_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
- ResolvedByType pgtype.Text `json:"resolved_by_type"`
- ResolvedByID pgtype.UUID `json:"resolved_by_id"`
-}
-
-// Returns the root of the thread containing @anchor_id plus every descendant
-// (recursive — supports real reply-to-reply nesting). @anchor_id may itself be
-// a root or any reply in the thread. Output is chronological so it can be fed
-// straight to the agent.
-func (q *Queries) ListThreadCommentsForIssue(ctx context.Context, arg ListThreadCommentsForIssueParams) ([]ListThreadCommentsForIssueRow, error) {
- rows, err := q.db.Query(ctx, listThreadCommentsForIssue,
- arg.RowLimit,
- arg.AnchorID,
- arg.IssueID,
- arg.WorkspaceID,
- )
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []ListThreadCommentsForIssueRow{}
- for rows.Next() {
- var i ListThreadCommentsForIssueRow
- if err := rows.Scan(
- &i.ID,
- &i.IssueID,
- &i.AuthorType,
- &i.AuthorID,
- &i.Content,
- &i.Type,
- &i.CreatedAt,
- &i.UpdatedAt,
- &i.ParentID,
- &i.WorkspaceID,
- &i.ResolvedAt,
- &i.ResolvedByType,
- &i.ResolvedByID,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
const listThreadCommentsForIssuePaged = `-- name: ListThreadCommentsForIssuePaged :many
WITH RECURSIVE root_of AS (
SELECT c.id, c.parent_id
@@ -1107,6 +1162,7 @@ WITH RECURSIVE root_of AS (
SELECT p.id, p.parent_id
FROM comment p
JOIN root_of r ON p.id = r.parent_id
+ WHERE p.issue_id = $2 AND p.workspace_id = $3
),
thread_root AS (
SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1
@@ -1114,13 +1170,15 @@ thread_root AS (
descendants AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
- c.resolved_at, c.resolved_by_type, c.resolved_by_id
+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id
FROM comment c
JOIN thread_root tr ON c.id = tr.id
UNION
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
- c.resolved_at, c.resolved_by_type, c.resolved_by_id
+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id
FROM comment c
JOIN descendants d ON c.parent_id = d.id
WHERE c.issue_id = $2 AND c.workspace_id = $3
@@ -1128,7 +1186,8 @@ descendants AS (
reply_page AS (
SELECT d.id, d.issue_id, d.author_type, d.author_id, d.content, d.type,
d.created_at, d.updated_at, d.parent_id, d.workspace_id,
- d.resolved_at, d.resolved_by_type, d.resolved_by_id
+ d.resolved_at, d.resolved_by_type, d.resolved_by_id,
+ d.source_task_id, d.quick_action_id
FROM descendants d
WHERE d.id NOT IN (SELECT id FROM thread_root)
AND (
@@ -1140,17 +1199,20 @@ reply_page AS (
)
SELECT id, issue_id, author_type, author_id, content, type,
created_at, updated_at, parent_id, workspace_id,
- resolved_at, resolved_by_type, resolved_by_id
+ resolved_at, resolved_by_type, resolved_by_id,
+ source_task_id, quick_action_id
FROM (
SELECT d.id, d.issue_id, d.author_type, d.author_id, d.content, d.type,
d.created_at, d.updated_at, d.parent_id, d.workspace_id,
- d.resolved_at, d.resolved_by_type, d.resolved_by_id
+ d.resolved_at, d.resolved_by_type, d.resolved_by_id,
+ d.source_task_id, d.quick_action_id
FROM descendants d
JOIN thread_root tr ON d.id = tr.id
UNION ALL
SELECT id, issue_id, author_type, author_id, content, type,
created_at, updated_at, parent_id, workspace_id,
- resolved_at, resolved_by_type, resolved_by_id
+ resolved_at, resolved_by_type, resolved_by_id,
+ source_task_id, quick_action_id
FROM reply_page
) combined
ORDER BY created_at ASC, id ASC
@@ -1180,10 +1242,12 @@ type ListThreadCommentsForIssuePagedRow struct {
ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
ResolvedByType pgtype.Text `json:"resolved_by_type"`
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
}
-// Same root-walk + descendants expansion as ListThreadCommentsForIssue, but
-// returns root + only the @reply_limit most recent replies (per the
+// Resolves @anchor_id to its thread root, recursively expands every descendant,
+// and returns the root + only the @reply_limit most recent replies (per the
// (created_at, id) composite key). When @has_cursor=TRUE only replies with
// (created_at, id) < (@before_at, @before_id) are eligible — that is the
// cursor for scrolling *within* a thread.
@@ -1228,6 +1292,8 @@ func (q *Queries) ListThreadCommentsForIssuePaged(ctx context.Context, arg ListT
&i.ResolvedAt,
&i.ResolvedByType,
&i.ResolvedByID,
+ &i.SourceTaskID,
+ &i.QuickActionID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/activity.sql b/server/pkg/db/queries/activity.sql
index fa796e6b88..0517e74511 100644
--- a/server/pkg/db/queries/activity.sql
+++ b/server/pkg/db/queries/activity.sql
@@ -1,10 +1,26 @@
-- name: ListActivitiesForIssue :many
--- All activities for an issue in chronological order, capped at $2 (DB safety
--- net to bound the response).
-SELECT * FROM activity_log
-WHERE issue_id = $1
-ORDER BY created_at ASC, id ASC
-LIMIT $2;
+-- The NEWEST $2 activities for an issue, returned in chronological order.
+--
+-- The cap has to bite at the OLD end, not the new one. The inner query takes
+-- the window with the keyset ordering (created_at DESC, id DESC), which
+-- idx_activity_log_issue_keyset (migration 068) satisfies without a sort step —
+-- it is not an index-only scan, since the index does not cover the columns
+-- SELECT * needs, so the heap is still read for the rows in the window. The
+-- outer query re-sorts ascending so every caller keeps the chronological
+-- contract it already had.
+--
+-- Capping with ORDER BY created_at ASC instead discards the newest rows, which
+-- made a busy issue's timeline appear to stop at some point in the past with no
+-- indication anything was missing. Activity is machine-paced (description
+-- autosave, every agent run, status/assignee changes), so this was reachable in
+-- normal use, not only on pathological issues (MUL-5492).
+SELECT * FROM (
+ SELECT * FROM activity_log
+ WHERE issue_id = $1
+ ORDER BY created_at DESC, id DESC
+ LIMIT $2
+) AS recent
+ORDER BY created_at ASC, id ASC;
-- name: GetActivity :one
SELECT * FROM activity_log
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index 8dfceb67cf..058864bdfa 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -1,11 +1,62 @@
-- name: ListCommentsForIssue :many
--- All comments for an issue in chronological order, capped at $3 (DB safety
--- net). Issue p99 is ~30 comments, max ever observed in prod is ~1.1k, so
--- the handler-side cap of 2000 is purely defensive.
+-- The NEWEST $3 comments for an issue, returned in chronological order.
+--
+-- Same shape and same reason as ListActivitiesForIssue: the inner query takes
+-- the window with the keyset ordering so the cap discards the OLDEST rows, and
+-- the outer query restores the ascending contract callers rely on. The ordering
+-- of the inner window is satisfied by idx_comment_issue_keyset (migration 068);
+-- the outer query sorts that bounded window back into chronological order.
+--
+-- A newest-N window is a suffix of the timeline, and unlike a prefix it is NOT
+-- closed under "parent of": a reply is always newer than its parent, so an old
+-- thread root can fall outside the window while a fresh reply to it stays
+-- inside. Callers that render threads must close the parent chains afterwards —
+-- see completeCommentThreads (MUL-5492).
+--
+-- The cap is still purely defensive here — issue p99 is ~30 comments and the max
+-- ever observed in prod is ~1.1k — but "defensive" is not a reason to drop the
+-- newest rows when it does fire (MUL-5492).
+SELECT * FROM (
+ SELECT * FROM comment
+ WHERE issue_id = $1 AND workspace_id = $2
+ ORDER BY created_at DESC, id DESC
+ LIMIT $3
+) AS recent
+ORDER BY created_at ASC, id ASC;
+
+-- name: ListCommentsByIDsForIssue :many
+-- The subset of @ids that exists within this issue and workspace.
+--
+-- Used to walk parent chains one level at a time (see completeCommentThreads).
+-- Deliberately NOT a recursive CTE: an earlier revision walked parent_id upward
+-- in SQL, which had no depth bound — a deep chain could pull tens of thousands of
+-- ancestors back and defeat the whole point of the row cap — and its recursive
+-- branch matched on parent_id alone, so a stray cross-workspace parent reference
+-- would have dragged another tenant's comments into the response. Both tenant
+-- columns are required here on every level, and the caller owns the budget.
SELECT * FROM comment
-WHERE issue_id = $1 AND workspace_id = $2
-ORDER BY created_at ASC, id ASC
-LIMIT $3;
+WHERE id = ANY(@ids::uuid[])
+ AND issue_id = @issue_id
+ AND workspace_id = @workspace_id
+ORDER BY created_at ASC, id ASC;
+
+-- name: ListChildCommentsForParents :many
+-- Fetch one descendant level for a bounded set of parent comments. Each parent
+-- maps back to its thread root in the Go breadth-first walk, avoiding one query
+-- per root.
+--
+-- Both tenant predicates apply at every level. row_limit is always a probe
+-- limit owned by completeCommentThreads; it prevents a wide level from defeating
+-- the response budget. through_at/through_id pin the walk to the newest row in
+-- the original window, so replies created concurrently are left to realtime
+-- delivery instead of making the multi-query snapshot internally inconsistent.
+SELECT * FROM comment
+WHERE parent_id = ANY(@parent_ids::uuid[])
+ AND issue_id = @issue_id
+ AND workspace_id = @workspace_id
+ AND (created_at, id) <= (@through_at::timestamptz, @through_id::uuid)
+ORDER BY parent_id ASC, created_at ASC, id ASC
+LIMIT @row_limit;
-- name: ListCommentsSinceForIssue :many
-- Comments created strictly after $3 in chronological order, capped at $4.
@@ -23,20 +74,18 @@ LIMIT $4;
-- discussion but also triage which thread to drill into (biggest / most
-- recently active) before fetching any specific reply thread.
--
--- `selected_roots` picks the roots we will actually return first (the chrono
--- page of size @row_limit), so the recursive `membership` walk only expands
--- those threads' subtrees instead of every thread in the issue. membership
--- labels each comment with its thread root by walking down from the selected
--- roots, so the counts stay correct even if the schema ever allows
--- reply-of-reply (the write path collapses to root today, but does not enforce
--- it). Mirrors ListRecentThreadCommentsForIssue's stats CTE.
+-- `selected_roots` takes the newest @row_limit roots. The final SELECT restores
+-- chronological order, so the defensive cap drops the oldest roots without
+-- changing the wire order. The recursive `membership` walk only expands those
+-- selected threads rather than every thread in the issue, and labels every
+-- descendant with its root so the stats stay correct at any reply depth.
WITH RECURSIVE selected_roots AS (
SELECT c.id, c.created_at
FROM comment c
WHERE c.issue_id = @issue_id
AND c.workspace_id = @workspace_id
AND c.parent_id IS NULL
- ORDER BY c.created_at ASC, c.id ASC
+ ORDER BY c.created_at DESC, c.id DESC
LIMIT @row_limit
),
membership(id, root_id, comment_created_at) AS (
@@ -59,6 +108,7 @@ thread_stats AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -104,6 +154,7 @@ thread_stats AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -111,51 +162,9 @@ JOIN comment c ON c.id = sr.id
JOIN thread_stats ts ON ts.root_id = sr.id
ORDER BY c.created_at ASC, c.id ASC;
--- name: ListThreadCommentsForIssue :many
--- Returns the root of the thread containing @anchor_id plus every descendant
--- (recursive — supports real reply-to-reply nesting). @anchor_id may itself be
--- a root or any reply in the thread. Output is chronological so it can be fed
--- straight to the agent.
-WITH RECURSIVE root_of AS (
- -- Walk up from the anchor until parent_id IS NULL.
- SELECT c.id, c.parent_id
- FROM comment c
- WHERE c.id = @anchor_id AND c.issue_id = @issue_id AND c.workspace_id = @workspace_id
- UNION ALL
- SELECT p.id, p.parent_id
- FROM comment p
- JOIN root_of r ON p.id = r.parent_id
-),
-thread_root AS (
- SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1
-),
-descendants AS (
- -- Start from the root, then keep adding any comment whose parent is
- -- already in the set. Cycle-safe under PK constraint (a comment cannot
- -- be its own ancestor).
- SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
- c.created_at, c.updated_at, c.parent_id, c.workspace_id,
- c.resolved_at, c.resolved_by_type, c.resolved_by_id
- FROM comment c
- JOIN thread_root tr ON c.id = tr.id
- UNION
- SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
- c.created_at, c.updated_at, c.parent_id, c.workspace_id,
- c.resolved_at, c.resolved_by_type, c.resolved_by_id
- FROM comment c
- JOIN descendants d ON c.parent_id = d.id
- WHERE c.issue_id = @issue_id AND c.workspace_id = @workspace_id
-)
-SELECT id, issue_id, author_type, author_id, content, type,
- created_at, updated_at, parent_id, workspace_id,
- resolved_at, resolved_by_type, resolved_by_id
-FROM descendants
-ORDER BY created_at ASC, id ASC
-LIMIT @row_limit;
-
-- name: ListThreadCommentsForIssuePaged :many
--- Same root-walk + descendants expansion as ListThreadCommentsForIssue, but
--- returns root + only the @reply_limit most recent replies (per the
+-- Resolves @anchor_id to its thread root, recursively expands every descendant,
+-- and returns the root + only the @reply_limit most recent replies (per the
-- (created_at, id) composite key). When @has_cursor=TRUE only replies with
-- (created_at, id) < (@before_at, @before_id) are eligible — that is the
-- cursor for scrolling *within* a thread.
@@ -177,6 +186,7 @@ WITH RECURSIVE root_of AS (
SELECT p.id, p.parent_id
FROM comment p
JOIN root_of r ON p.id = r.parent_id
+ WHERE p.issue_id = @issue_id AND p.workspace_id = @workspace_id
),
thread_root AS (
SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1
@@ -184,13 +194,15 @@ thread_root AS (
descendants AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
- c.resolved_at, c.resolved_by_type, c.resolved_by_id
+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id
FROM comment c
JOIN thread_root tr ON c.id = tr.id
UNION
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
- c.resolved_at, c.resolved_by_type, c.resolved_by_id
+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id
FROM comment c
JOIN descendants d ON c.parent_id = d.id
WHERE c.issue_id = @issue_id AND c.workspace_id = @workspace_id
@@ -198,7 +210,8 @@ descendants AS (
reply_page AS (
SELECT d.id, d.issue_id, d.author_type, d.author_id, d.content, d.type,
d.created_at, d.updated_at, d.parent_id, d.workspace_id,
- d.resolved_at, d.resolved_by_type, d.resolved_by_id
+ d.resolved_at, d.resolved_by_type, d.resolved_by_id,
+ d.source_task_id, d.quick_action_id
FROM descendants d
WHERE d.id NOT IN (SELECT id FROM thread_root)
AND (
@@ -210,17 +223,20 @@ reply_page AS (
)
SELECT id, issue_id, author_type, author_id, content, type,
created_at, updated_at, parent_id, workspace_id,
- resolved_at, resolved_by_type, resolved_by_id
+ resolved_at, resolved_by_type, resolved_by_id,
+ source_task_id, quick_action_id
FROM (
SELECT d.id, d.issue_id, d.author_type, d.author_id, d.content, d.type,
d.created_at, d.updated_at, d.parent_id, d.workspace_id,
- d.resolved_at, d.resolved_by_type, d.resolved_by_id
+ d.resolved_at, d.resolved_by_type, d.resolved_by_id,
+ d.source_task_id, d.quick_action_id
FROM descendants d
JOIN thread_root tr ON d.id = tr.id
UNION ALL
SELECT id, issue_id, author_type, author_id, content, type,
created_at, updated_at, parent_id, workspace_id,
- resolved_at, resolved_by_type, resolved_by_id
+ resolved_at, resolved_by_type, resolved_by_id,
+ source_task_id, quick_action_id
FROM reply_page
) combined
ORDER BY created_at ASC, id ASC;
@@ -285,6 +301,7 @@ picked AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
+ c.source_task_id, c.quick_action_id,
p.root_id AS thread_root_id,
p.last_activity_at AS thread_last_activity_at
FROM picked p