Skip to content

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

Go

MUL-6343: Add semantic issue activity timestamps (#7193)

Multica Eve5d5fe646723d
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 301e655201..8c4286138d 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -88,6 +88,20 @@ const baseIssue = {
};
describe("IssueSchema (via ListIssuesResponseSchema)", () => {
+ it("accepts null activity during backfill and rejects malformed activity", () => {
+ const parsed = ListIssuesResponseSchema.parse({
+ issues: [{ ...baseIssue, last_activity_at: null }],
+ total: 1,
+ });
+ expect(parsed.issues[0]?.last_activity_at).toBeNull();
+ expect(() =>
+ ListIssuesResponseSchema.parse({
+ issues: [{ ...baseIssue, last_activity_at: 42 }],
+ total: 1,
+ }),
+ ).toThrow();
+ });
+
it("accepts a primitive metadata KV map", () => {
const payload = {
issues: [
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 8464bd4c34..8ad4aeb220 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -968,6 +968,9 @@ export const IssueSchema = z.object({
created_at: z.string(),
updated_at: z.string(),
revision: z.number().int().positive().optional(),
+ // Optional for compatibility with older self-hosted backends; a current
+ // backend emits null until its historical backfill reaches the issue.
+ last_activity_at: z.string().nullable().optional(),
}).loose();
export const ListIssuesResponseSchema = z.object({
diff --git a/packages/core/issues/cache-coordinator.test.ts b/packages/core/issues/cache-coordinator.test.ts
index 1adff02398..9bda267a31 100644
--- a/packages/core/issues/cache-coordinator.test.ts
+++ b/packages/core/issues/cache-coordinator.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { QueryClient, hashKey } from "@tanstack/react-query";
import {
applyIssueChange,
+ invalidateLastActivitySortedIssueLists,
invalidateUpdatedAtSortedIssueLists,
rollbackIssueChange,
type IssueFlatCache,
@@ -90,6 +91,32 @@ const flatUpdatedSortKey = issueKeys.flat(
{},
updatedSort,
);
+const lastActivitySort: IssueSortParam = {
+ sort_by: "last_activity",
+ sort_direction: "desc",
+};
+const wsLastActivityKey = issueKeys.listSorted(WS_ID, lastActivitySort);
+const flatLastActivityKey = issueKeys.flat(
+ WS_ID,
+ "workspace:all",
+ {},
+ lastActivitySort,
+);
+const assigneeGroupsLastActivityKey = issueKeys.assigneeGroups(WS_ID, {
+ ...lastActivitySort,
+});
+const tableLastActivityKey = issueKeys.tableRows(
+ WS_ID,
+ {
+ scope: { kind: "workspace" },
+ filters: {},
+ sort: { field: "last_activity", direction: "desc" },
+ },
+ { kind: "none" },
+ null,
+ false,
+ null,
+);
// Assignee-grouped boards fold the sort into their filter bag
// (issueAssigneeGroupsOptions does `{ ...filter, ...sort }`).
const assigneeGroupsUpdatedKey = issueKeys.assigneeGroups(WS_ID, {
@@ -307,6 +334,36 @@ describe("applyIssueChange", () => {
expect(stale).not.toContain(hashKey(wsKey));
});
+ it("re-sorts last_activity windows for semantic edits but not position-only moves", () => {
+ qc.setQueryData<ListIssuesCache>(wsLastActivityKey, bucketed([issue()]));
+ qc.setQueryData<IssueFlatCache>(flatLastActivityKey, {
+ pages: [{ issues: [issue()], total: 1 }],
+ pageParams: [0],
+ });
+
+ const titlePatch = { title: "semantic edit" };
+ const semantic = applyIssueChange(qc, WS_ID, "issue-1", titlePatch, {
+ changed: issueChangedDims(titlePatch, issue()),
+ baseIssue: issue(),
+ });
+ expect(semantic.staleKeys.map(hashKey)).toEqual([
+ hashKey(wsLastActivityKey),
+ hashKey(flatLastActivityKey),
+ ]);
+
+ const positionPatch = { position: 99 };
+ const layout = applyIssueChange(qc, WS_ID, "issue-1", positionPatch, {
+ changed: issueChangedDims(positionPatch, issue()),
+ baseIssue: issue(),
+ });
+ expect(layout.staleKeys.map(hashKey)).not.toContain(
+ hashKey(wsLastActivityKey),
+ );
+ expect(layout.staleKeys.map(hashKey)).not.toContain(
+ hashKey(flatLastActivityKey),
+ );
+ });
+
it("marks an updated_at-sorted board stale even when the edited card is beyond its window", () => {
// Card not in the loaded window (empty bucket, non-zero total): an edit
// that bumps updated_at can still surface it, so the key must refetch.
@@ -632,3 +689,32 @@ describe("invalidateUpdatedAtSortedIssueLists", () => {
expect(qc.getQueryState(wsKey)?.isInvalidated).toBe(false);
});
});
+
+describe("invalidateLastActivitySortedIssueLists", () => {
+ it("invalidates bucketed, flat, grouped, and server Table activity sorts only", () => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc.setQueryData<ListIssuesCache>(wsLastActivityKey, bucketed([makeIssue(1)]));
+ qc.setQueryData<IssueFlatCache>(flatLastActivityKey, {
+ pages: [{ issues: [makeIssue(1)], total: 1 }],
+ pageParams: [0],
+ });
+ qc.setQueryData(assigneeGroupsLastActivityKey, { groups: [] });
+ qc.setQueryData(tableLastActivityKey, { rows: [] });
+ qc.setQueryData<ListIssuesCache>(wsUpdatedKey, bucketed([makeIssue(1)]));
+ qc.setQueryData<ListIssuesCache>(wsKey, bucketed([makeIssue(1)]));
+
+ invalidateLastActivitySortedIssueLists(qc, WS_ID);
+
+ for (const key of [
+ wsLastActivityKey,
+ flatLastActivityKey,
+ assigneeGroupsLastActivityKey,
+ tableLastActivityKey,
+ ]) {
+ expect(qc.getQueryState(key)?.isInvalidated).toBe(true);
+ }
+ expect(qc.getQueryState(wsUpdatedKey)?.isInvalidated).toBe(false);
+ expect(qc.getQueryState(wsKey)?.isInvalidated).toBe(false);
+ qc.clear();
+ });
+});
diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.ts
index 3ae1a4f1bf..bf7f6f5158 100644
--- a/packages/core/issues/cache-coordinator.ts
+++ b/packages/core/issues/cache-coordinator.ts
@@ -194,6 +194,37 @@ function patchChangesAnyIssueField(
);
}
+// Fields whose direct mutation is part of the issue's semantic activity
+// contract. Position-only moves deliberately stay out: they are layout edits,
+// not user-visible activity. Full server snapshots carry last_activity_at, so
+// prefer that authoritative clock when present; the field list is the
+// mixed-version/optimistic fallback for patches that do not carry it yet.
+const issueActivityFields = [
+ "title",
+ "description",
+ "status",
+ "priority",
+ "assignee_type",
+ "assignee_id",
+ "start_date",
+ "due_date",
+ "parent_issue_id",
+ "project_id",
+ "stage",
+] as const satisfies readonly (keyof Issue)[];
+
+function patchChangesIssueActivity(
+ patch: Partial<Issue>,
+ base: Issue | undefined,
+): boolean {
+ if (Object.prototype.hasOwnProperty.call(patch, "last_activity_at")) {
+ return patchFieldChanged(patch, base, "last_activity_at");
+ }
+ return issueActivityFields.some((field) =>
+ patchFieldChanged(patch, base, field),
+ );
+}
+
/** Whether a patch can change a flat window's membership or ordering. A
* loaded row is always patched optimistically; only windows whose server
* contract depends on the changed field need the follow-up refetch. */
@@ -248,6 +279,8 @@ function flatWindowNeedsReconcile(
// Every persisted issue edit advances updated_at even though the
// optimistic request payload does not carry the server timestamp.
return anyIssueFieldChanged;
+ case "last_activity":
+ return patchChangesIssueActivity(patch, base);
case "start_date":
return patchFieldChanged(patch, base, "start_date");
case "due_date":
@@ -309,6 +342,12 @@ export function applyIssueChange(
) {
staleKeys.push(key);
}
+ if (
+ sort.sort_by === "last_activity" &&
+ patchChangesIssueActivity(patch, loc?.issue ?? baseIssue)
+ ) {
+ staleKeys.push(key);
+ }
if (loc) {
if (!prevIssue) prevIssue = loc.issue;
@@ -536,18 +575,23 @@ export function invalidateIssueDerivatives(
}
}
-/** True when any object part of a query key encodes an "Updated date" ordering
- * (`sort_by: "updated_at"`). Bucketed status boards and flat tables keep the
- * sort in a standalone bag; assignee-grouped boards merge it into their filter
- * bag (see `issueAssigneeGroupsOptions`). Scanning every object part matches
- * all of those surfaces — workspace and My Issues — with one rule. */
-function queryKeyHasUpdatedAtSort(key: QueryKey): boolean {
+/** True when any object part of a query key encodes the requested ordering.
+ * Bucketed, flat and grouped surfaces use `sort_by`; server Table queries use
+ * the nested `sort.field` contract. */
+function queryKeyHasSort(key: QueryKey, field: string): boolean {
return key.some(
- (part) =>
- !!part &&
- typeof part === "object" &&
- !Array.isArray(part) &&
- (part as Record<string, unknown>).sort_by === "updated_at",
+ (part) => {
+ if (!part || typeof part !== "object" || Array.isArray(part)) return false;
+ const record = part as Record<string, unknown>;
+ if (record.sort_by === field) return true;
+ const sort = record.sort;
+ return (
+ !!sort &&
+ typeof sort === "object" &&
+ !Array.isArray(sort) &&
+ (sort as Record<string, unknown>).field === field
+ );
+ },
);
}
@@ -568,7 +612,20 @@ export function invalidateUpdatedAtSortedIssueLists(
): void {
qc.invalidateQueries({
queryKey: issueKeys.all(wsId),
- predicate: (query) => queryKeyHasUpdatedAtSort(query.queryKey),
+ predicate: (query) => queryKeyHasSort(query.queryKey, "updated_at"),
+ });
+}
+
+/** Refetch only issue surfaces ordered by semantic activity. Auxiliary
+ * mutations carry no full Issue snapshot or sortable timestamp, so an
+ * authoritative refetch is the only safe way to restore their order. */
+export function invalidateLastActivitySortedIssueLists(
+ qc: QueryClient,
+ wsId: string,
+): void {
+ qc.invalidateQueries({
+ queryKey: issueKeys.all(wsId),
+ predicate: (query) => queryKeyHasSort(query.queryKey, "last_activity"),
});
}
diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsx
index d7ddf9a87a..c36aa05247 100644
--- a/packages/core/issues/mutations.test.tsx
+++ b/packages/core/issues/mutations.test.tsx
@@ -10,7 +10,9 @@ import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
import {
useBatchUpdateIssues,
+ useDeleteComment,
useResolveComment,
+ useUpdateComment,
useUpdateIssue,
} from "./mutations";
import {
@@ -750,6 +752,92 @@ describe("useBatchUpdateIssues — optimistic patch covers filtered boards too",
});
});
+describe("comment mutations — owner revision and last activity", () => {
+ const issueId = "issue-1";
+ const detailKey = issueKeys.detail(WS_ID, issueId);
+ const lastActivityKey = issueKeys.listSorted(WS_ID, {
+ sort_by: "last_activity",
+ sort_direction: "desc",
+ });
+ const positionKey = issueKeys.listSorted(WS_ID, { sort_by: "position" });
+
+ function seed(qc: QueryClient) {
+ const issue = makeIssue(1, { revision: 1 });
+ const board: ListIssuesCache = {
+ byStatus: { todo: { issues: [issue], total: 1 } },
+ };
+ qc.setQueryData<Issue>(detailKey, issue);
+ qc.setQueryData<ListIssuesCache>(lastActivityKey, board);
+ qc.setQueryData<ListIssuesCache>(positionKey, board);
+ qc.setQueryData<TimelineEntry[]>(issueKeys.timeline(issueId), [
+ {
+ type: "comment",
+ id: "comment-1",
+ actor_type: "member",
+ actor_id: "user-1",
+ content: "before",
+ parent_id: null,
+ comment_type: "comment",
+ reactions: [],
+ attachments: [],
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ },
+ ]);
+ }
+
+ it("consumes an update response's issue revision and re-sorts activity", async () => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ seed(qc);
+ setApiInstance({
+ updateComment: vi.fn().mockResolvedValue({
+ id: "comment-1",
+ issue_id: issueId,
+ content: "after",
+ issue_revision: 2,
+ }),
+ } as unknown as ApiClient);
+ const { result } = renderHook(() => useUpdateComment(issueId), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({
+ commentId: "comment-1",
+ content: "after",
+ attachmentIds: [],
+ });
+ });
+
+ expect(qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(lastActivityKey)?.isInvalidated).toBe(true);
+ // The owner revision also invalidates any loaded projection containing
+ // this issue, independent of sort.
+ expect(qc.getQueryState(positionKey)?.isInvalidated).toBe(true);
+ qc.clear();
+ });
+
+ it("invalidates the owner projection after a successful 204 delete", async () => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ seed(qc);
+ setApiInstance({
+ deleteComment: vi.fn().mockResolvedValue(undefined),
+ } as unknown as ApiClient);
+ const { result } = renderHook(() => useDeleteComment(issueId), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync("comment-1");
+ });
+
+ expect(qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(lastActivityKey)?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(positionKey)?.isInvalidated).toBe(true);
+ qc.clear();
+ });
+});
+
describe("useResolveComment", () => {
const ISSUE_ID = "issue-1";
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 8e3c583bf0..1057014d87 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -7,6 +7,7 @@ import { inboxKeys } from "../inbox/queries";
import {
applyIssueChange,
invalidateIssueDerivatives,
+ invalidateLastActivitySortedIssueLists,
invalidateStaleListKeys,
rollbackIssueChange,
type IssueFlatCache,
@@ -37,6 +38,7 @@ import type { TimelineEntry, IssueSubscriber, Reaction } from "../types";
import { sortTimelineEntriesAsc } from "./timeline-sort";
import {
onIssueAuxiliaryRevision,
+ invalidateIssueOwnerProjections,
reconcileIssueFullSnapshotRevision,
} from "./ws-updaters";
@@ -731,7 +733,12 @@ export function useCreateComment(issueId: string) {
suppressAgentIds?: string[];
}) => api.createComment(issueId, content, type, parentId, attachmentIds, suppressAgentIds),
onSuccess: (comment) => {
- onIssueAuxiliaryRevision(qc, wsId, issueId, comment.issue_revision);
+ if (comment.issue_revision) {
+ onIssueAuxiliaryRevision(qc, wsId, issueId, comment.issue_revision);
+ } else {
+ invalidateIssueOwnerProjections(qc, wsId, issueId);
+ }
+ invalidateLastActivitySortedIssueLists(qc, wsId);
const entry: TimelineEntry = {
type: "comment",
id: comment.id,
@@ -770,6 +777,7 @@ export function useCreateComment(issueId: string) {
export function useUpdateComment(issueId: string) {
const qc = useQueryClient();
+ const wsId = useWorkspaceId();
return useMutation({
mutationFn: ({
commentId,
@@ -804,6 +812,16 @@ export function useUpdateComment(issueId: string) {
qc.setQueryData(issueKeys.timeline(issueId), ctx.prev);
}
},
+ onSuccess: (comment) => {
+ if (comment.issue_revision) {
+ onIssueAuxiliaryRevision(qc, wsId, issueId, comment.issue_revision);
+ } else {
+ // Mixed-version fallback: an older backend may have committed the
+ // aggregate revision without returning it.
+ invalidateIssueOwnerProjections(qc, wsId, issueId);
+ }
+ invalidateLastActivitySortedIssueLists(qc, wsId);
+ },
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });
},
@@ -812,6 +830,7 @@ export function useUpdateComment(issueId: string) {
export function useDeleteComment(issueId: string) {
const qc = useQueryClient();
+ const wsId = useWorkspaceId();
return useMutation({
mutationFn: (commentId: string) => api.deleteComment(commentId),
onMutate: async (commentId) => {
@@ -847,6 +866,13 @@ export function useDeleteComment(issueId: string) {
qc.setQueryData(issueKeys.timeline(issueId), ctx.prev);
}
},
+ onSuccess: () => {
+ // The endpoint remains 204 for compatibility, so the local caller has
+ // no body carrying issue_revision. The realtime event will narrow this
+ // with its revision when connected; this is the no-WS safety net.
+ invalidateIssueOwnerProjections(qc, wsId, issueId);
+ invalidateLastActivitySortedIssueLists(qc, wsId);
+ },
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });
},
diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.ts
index 1cdcac10e4..1f8cbda0b5 100644
--- a/packages/core/issues/ws-updaters.test.ts
+++ b/packages/core/issues/ws-updaters.test.ts
@@ -470,6 +470,29 @@ describe("issue property snapshots", () => {
});
});
+describe("auxiliary issue activity ordering", () => {
+ it.each([
+ ["labels", (qc: QueryClient) => onIssueLabelsChanged(qc, WS_ID, ISSUE_ID, [labelB])],
+ ["metadata", (qc: QueryClient) => onIssueMetadataChanged(qc, WS_ID, ISSUE_ID, { state: "changed" })],
+ ["properties", (qc: QueryClient) => onIssuePropertiesChanged(qc, WS_ID, ISSUE_ID, { estimate: 5 })],
+ ])("re-sorts last_activity after committed %s changes", (_kind, apply) => {
+ const qc = new QueryClient();
+ const activityKey = issueKeys.listSorted(WS_ID, {
+ sort_by: "last_activity",
+ sort_direction: "desc",
+ });
+ const positionKey = issueKeys.listSorted(WS_ID, { sort_by: "position" });
+ qc.setQueryData<ListIssuesCache>(activityKey, makeListCache(baseIssue));
+ qc.setQueryData<ListIssuesCache>(positionKey, makeListCache(baseIssue));
+
+ apply(qc);
+
+ expectInvalidated(qc, activityKey);
+ expect(qc.getQueryState(positionKey)?.isInvalidated).toBe(false);
+ qc.clear();
+ });
+});
+
describe("project progress invalidation", () => {
let qc: QueryClient;
diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.ts
index 0b2706d059..3b3107ac76 100644
--- a/packages/core/issues/ws-updaters.ts
+++ b/packages/core/issues/ws-updaters.ts
@@ -6,6 +6,7 @@ import { projectKeys } from "../projects/queries";
import {
applyIssueChange,
invalidateIssueDerivatives,
+ invalidateLastActivitySortedIssueLists,
invalidateStaleListKeys,
invalidateUpdatedAtSortedIssueLists,
type IssueFlatCache,
@@ -293,25 +294,22 @@ function refetchForUnversionedIssueEvent(
return true;
}
-function invalidateStaleIssueOwnerProjections(
+function invalidateIssueOwnerProjectionsWhere(
qc: QueryClient,
wsId: string,
issueId: string,
- revision: number,
+ shouldInvalidate: (issue: Issue | undefined) => boolean,
) {
- const isStale = (issue: Issue | undefined) =>
- issue !== undefined &&
- (issue.revision === undefined || issue.revision < revision);
const invalidateExact = (queryKey: readonly unknown[]) => {
qc.invalidateQueries({ queryKey, exact: true });
};
const detailKey = issueKeys.detail(wsId, issueId);
- if (isStale(qc.getQueryData<Issue>(detailKey))) invalidateExact(detailKey);
+ if (shouldInvalidate(qc.getQueryData<Issue>(detailKey))) invalidateExact(detailKey);
for (const prefix of [issueKeys.list(wsId), issueKeys.myAll(wsId)]) {
for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: prefix })) {
- if (isStale(data ? findIssueLocation(data, issueId)?.issue : undefined)) {
+ if (shouldInvalidate(data ? findIssueLocation(data, issueId)?.issue : undefined)) {
invalidateExact(key);
}
}
@@ -319,26 +317,58 @@ function invalidateStaleIssueOwnerProjections(
for (const [key, data] of qc.getQueriesData<IssueFlatCache>({
queryKey: issueKeys.flatAll(wsId),
})) {
- if (data?.pages.some((page) => isStale(page.issues.find((issue) => issue.id === issueId)))) {
+ if (data?.pages.some((page) => shouldInvalidate(page.issues.find((issue) => issue.id === issueId)))) {
invalidateExact(key);
}
}
for (const [key, data] of qc.getQueriesData<IssueTableRowsResponse>({
queryKey: issueKeys.tableAll(wsId),
})) {
- if (data?.rows.some((row) => row.issue.id === issueId && isStale(row.issue))) {
+ if (data?.rows.some((row) => row.issue.id === issueId && shouldInvalidate(row.issue))) {
invalidateExact(key);
}
}
for (const prefix of [issueKeys.childrenAll(wsId), issueKeys.projectGanttAll(wsId)]) {
for (const [key, data] of qc.getQueriesData<Issue[]>({ queryKey: prefix })) {
- if (data?.some((issue) => issue.id === issueId && isStale(issue))) {
+ if (data?.some((issue) => issue.id === issueId && shouldInvalidate(issue))) {
invalidateExact(key);
}
}
}
}
+function invalidateStaleIssueOwnerProjections(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number,
+) {
+ invalidateIssueOwnerProjectionsWhere(
+ qc,
+ wsId,
+ issueId,
+ (issue) =>
+ issue !== undefined &&
+ (issue.revision === undefined || issue.revision < revision),
+ );
+}
+
+/** Fallback for successful auxiliary mutations whose HTTP response cannot
+ * carry an owner revision (notably 204 comment deletion). Only loaded
+ * projections containing the owner are invalidated. */
+export function invalidateIssueOwnerProjections(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+) {
+ invalidateIssueOwnerProjectionsWhere(
+ qc,
+ wsId,
+ issueId,
+ (issue) => issue !== undefined,
+ );
+}
+
/**
* An auxiliary event proves that a newer aggregate owner revision exists, but
* it does not carry the full Issue snapshot for that revision. Advancing the
@@ -557,6 +587,7 @@ export function onIssueLabelsChanged(
}
patchIssueLabels(qc, wsId, issueId, labels, revision);
invalidateIssueLabelDerivatives(qc, wsId);
+ invalidateLastActivitySortedIssueLists(qc, wsId);
}
/** Deterministic label snapshot patch used by optimistic mutation legs. */
@@ -650,6 +681,7 @@ export function onIssueMetadataChanged(
}
patchIssueSnapshot(qc, wsId, issueId, { metadata }, revision);
onIssueAuxiliaryRevision(qc, wsId, issueId, revision, "metadata");
+ invalidateLastActivitySortedIssueLists(qc, wsId);
qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
// A metadata write bumps issue.updated_at server-side (SetIssueMetadataKey /
// DeleteIssueMetadataKey), but the patches above keep each card's slot, so a
@@ -676,6 +708,7 @@ export function onIssuePropertiesChanged(
) {
if (refetchForUnversionedIssueEvent(qc, wsId, issueId, revision)) return;
patchIssueProperties(qc, wsId, issueId, properties, revision);
+ invalidateLastActivitySortedIssueLists(qc, wsId);
// Per-parent rows are patched for immediate UI feedback, then all children
// projections are marked stale so older fetches cannot win after commit.
qc.invalidateQueries({ queryKey: issueKeys.childrenAll(wsId) });
diff --git a/packages/core/realtime/use-realtime-sync-comment.test.tsx b/packages/core/realtime/use-realtime-sync-comment.test.tsx
index 85fb26c453..8b40db0ae4 100644
--- a/packages/core/realtime/use-realtime-sync-comment.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-comment.test.tsx
@@ -7,7 +7,7 @@ import type { ReactNode } from "react";
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import type { WSClient } from "../api/ws-client";
import { issueKeys, type IssueSortParam } from "../issues/queries";
-import type { ListIssuesCache } from "../types";
+import type { Issue, ListIssuesCache } from "../types";
import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";
vi.mock("../platform/workspace-storage", () => ({
@@ -65,12 +65,16 @@ const updatedSort: IssueSortParam = {
const positionSort: IssueSortParam = { sort_by: "position" };
const updatedBoardKey = issueKeys.listSorted("ws-1", updatedSort);
const positionBoardKey = issueKeys.listSorted("ws-1", positionSort);
+const lastActivityBoardKey = issueKeys.listSorted("ws-1", {
+ sort_by: "last_activity",
+ sort_direction: "desc",
+});
function bucketed(): ListIssuesCache {
return { byStatus: { todo: { issues: [], total: 1 } } };
}
-describe("useRealtimeSync — comment:created re-sorts Updated date lists", () => {
+describe("useRealtimeSync — comment activity cache coherence", () => {
let qc: QueryClient;
beforeEach(() => {
@@ -85,6 +89,7 @@ describe("useRealtimeSync — comment:created re-sorts Updated date lists", () =
it("invalidates the updated_at-sorted board but leaves the position board", () => {
qc.setQueryData<ListIssuesCache>(updatedBoardKey, bucketed());
qc.setQueryData<ListIssuesCache>(positionBoardKey, bucketed());
+ qc.setQueryData<ListIssuesCache>(lastActivityBoardKey, bucketed());
qc.setQueryData(issueKeys.timeline("issue-1"), []);
const { ws, handlers } = createRecordingWs();
@@ -97,6 +102,7 @@ describe("useRealtimeSync — comment:created re-sorts Updated date lists", () =
});
expect(qc.getQueryState(updatedBoardKey)?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(lastActivityBoardKey)?.isInvalidated).toBe(true);
expect(qc.getQueryState(positionBoardKey)?.isInvalidated).toBe(false);
// The per-issue timeline is still invalidated as before.
expect(
@@ -104,6 +110,50 @@ describe("useRealtimeSync — comment:created re-sorts Updated date lists", () =
).toBe(true);
});
+ it("uses update/delete owner revisions and re-sorts only last_activity", () => {
+ const detailKey = issueKeys.detail("ws-1", "issue-1");
+ qc.setQueryData<Issue>(detailKey, {
+ id: "issue-1",
+ workspace_id: "ws-1",
+ revision: 1,
+ } as Issue);
+ qc.setQueryData<ListIssuesCache>(updatedBoardKey, bucketed());
+ qc.setQueryData<ListIssuesCache>(positionBoardKey, bucketed());
+ qc.setQueryData<ListIssuesCache>(lastActivityBoardKey, bucketed());
+ qc.setQueryData(issueKeys.timeline("issue-1"), []);
+
+ const { ws, handlers } = createRecordingWs();
+ renderHook(() => useRealtimeSync(ws, createStores()), {
+ wrapper: createWrapper(qc),
+ });
+
+ handlers["comment:updated"]?.({
+ comment: { id: "c1", issue_id: "issue-1" },
+ issue_revision: 2,
+ });
+
+ expect(qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(lastActivityBoardKey)?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(updatedBoardKey)?.isInvalidated).toBe(false);
+ expect(qc.getQueryState(positionBoardKey)?.isInvalidated).toBe(false);
+
+ qc.setQueryData<Issue>(detailKey, {
+ id: "issue-1",
+ workspace_id: "ws-1",
+ revision: 2,
+ } as Issue);
+ qc.setQueryData<ListIssuesCache>(lastActivityBoardKey, bucketed());
+
+ handlers["comment:deleted"]?.({
+ comment_id: "c1",
+ issue_id: "issue-1",
+ issue_revision: 3,
+ });
+
+ expect(qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(lastActivityBoardKey)?.isInvalidated).toBe(true);
+ });
+
it("ignores a comment event with no issue_id", () => {
qc.setQueryData<ListIssuesCache>(updatedBoardKey, bucketed());
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index b61f18ca60..5189e93324 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -36,8 +36,12 @@ import {
onIssuePropertiesChanged,
onIssueMetadataChanged,
onIssueAuxiliaryRevision,
+ invalidateIssueOwnerProjections,
} from "../issues/ws-updaters";
-import { invalidateUpdatedAtSortedIssueLists } from "../issues/cache-coordinator";
+import {
+ invalidateLastActivitySortedIssueLists,
+ invalidateUpdatedAtSortedIssueLists,
+} from "../issues/cache-coordinator";
import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";
import { inboxKeys } from "../inbox/queries";
import {
@@ -1076,21 +1080,46 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) {
invalidateUpdatedAtSortedIssueLists(qc, wsId);
+ invalidateLastActivitySortedIssueLists(qc, wsId);
// A comment carries only the aggregate owner revision, not a full
// Issue snapshot. Mark stale projections for an authoritative fetch
// without making a later full snapshot look older than the cache.
- onIssueAuxiliaryRevision(qc, wsId, comment.issue_id, issueRevision);
+ if (issueRevision) {
+ onIssueAuxiliaryRevision(qc, wsId, comment.issue_id, issueRevision);
+ } else {
+ invalidateIssueOwnerProjections(qc, wsId, comment.issue_id);
+ }
}
});
const unsubCommentUpdated = ws.on("comment:updated", (p) => {
- const { comment } = p as CommentUpdatedPayload;
- if (comment?.issue_id) invalidateTimeline(comment.issue_id);
+ const { comment, issue_revision } = p as CommentUpdatedPayload;
+ if (!comment?.issue_id) return;
+ invalidateTimeline(comment.issue_id);
+ const wsId = getCurrentWsId();
+ if (wsId) {
+ invalidateLastActivitySortedIssueLists(qc, wsId);
+ if (issue_revision) {
+ onIssueAuxiliaryRevision(qc, wsId, comment.issue_id, issue_revision);
+ } else {
+ invalidateIssueOwnerProjections(qc, wsId, comment.issue_id);
+ }
+ }
});
const unsubCommentDeleted = ws.on("comment:deleted", (p) => {
- const { issue_id } = p as CommentDeletedPayload;
- if (issue_id) invalidateTimeline(issue_id);
+ const { issue_id, issue_revision } = p as CommentDeletedPayload;
+ if (!issue_id) return;
+ invalidateTimeline(issue_id);
+ const wsId = getCurrentWsId();
+ if (wsId) {
+ invalidateLastActivitySortedIssueLists(qc, wsId);
+ if (issue_revision) {
+ onIssueAuxiliaryRevision(qc, wsId, issue_id, issue_revision);
+ } else {
+ invalidateIssueOwnerProjections(qc, wsId, issue_id);
+ }
+ }
});
const unsubCommentResolved = ws.on("comment:resolved", (p) => {
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 8694b32a48..693015ac6e 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -181,6 +181,7 @@ export interface ListIssuesParams {
| "title"
| "created_at"
| "updated_at"
+ | "last_activity"
| "start_date"
| "due_date"
| `property:${string}`;
@@ -229,6 +230,7 @@ export interface ListGroupedIssuesParams {
| "title"
| "created_at"
| "updated_at"
+ | "last_activity"
| "start_date"
| "due_date"
| `property:${string}`;
@@ -293,6 +295,7 @@ export type IssueTableSortField =
| "title"
| "created_at"
| "updated_at"
+ | "last_activity"
| "start_date"
| "due_date"
| `property:${string}`;
diff --git a/packages/core/types/comment.ts b/packages/core/types/comment.ts
index 5ec762dfd2..0c80d6623c 100644
--- a/packages/core/types/comment.ts
+++ b/packages/core/types/comment.ts
@@ -29,7 +29,7 @@ export interface Comment {
updated_at: string;
/** Monotonic server revision; absent when connected to an older backend. */
revision?: number;
- /** Parent issue revision after this comment creation; create responses only. */
+ /** Parent issue revision after this semantic comment mutation. */
issue_revision?: number;
resolved_at: string | null;
resolved_by_type: CommentAuthorType | null;
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 571130bd05..4da693022d 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -207,11 +207,13 @@ export interface CommentCreatedPayload {
export interface CommentUpdatedPayload {
comment: Comment;
+ issue_revision?: number;
}
export interface CommentDeletedPayload {
comment_id: string;
issue_id: string;
+ issue_revision?: number;
}
export interface CommentResolvedPayload {
diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.ts
index 2f15c0a543..c77801c702 100644
--- a/packages/core/types/issue.ts
+++ b/packages/core/types/issue.ts
@@ -96,4 +96,10 @@ export interface Issue {
updated_at: string;
/** Monotonic server revision; absent when connected to an older backend. */
revision?: number;
+ /**
+ * Null until the server's historical activity backfill reaches this row.
+ * This RFC3339 timestamp may include sub-second precision while legacy
+ * created_at/updated_at values are second-precision; parse before comparing.
+ */
+ last_activity_at?: string | null;
}
diff --git a/server/cmd/backfill_issue_last_activity/README.md b/server/cmd/backfill_issue_last_activity/README.md
new file mode 100644
index 0000000000..1f674eef9b
--- /dev/null
+++ b/server/cmd/backfill_issue_last_activity/README.md
@@ -0,0 +1,36 @@
+# Issue last-activity backfill runbook
+
+Use this command only after migrations 360 and 361 are applied and every
+issue-writing backend has been upgraded to maintain `issue.last_activity_at`.
+Running it while an older writer is still live can make that writer's later
+changes invisible to the activity clock.
+
+From `server/`:
+
+```bash
+go run ./cmd/backfill_issue_last_activity
+```
+
+The command uses bounded transactions, an id keyset watermark, `SKIP LOCKED`,
+a delay between batches, and a session advisory lock. It is safe to interrupt
+and restart. Use `--batch-size`, `--sleep-between-batches`, and `--max-batches`
+to reduce load or run a bounded canary. If consecutive passes make no progress
+while rows remain, the command fails after 10 passes instead of repeatedly
+counting the table forever. Release the long-held row locks and rerun, or adjust
+`--max-stalled-passes`; setting it to 0 explicitly disables this guard.
+Completion is explicit: do not depend on complete historical activity ordering
+until the command logs `remaining=0`.
+
+Migration 361 builds the serving index before this operator-run backfill so
+new application versions can sort safely throughout a rolling deployment. The
+tradeoff is index maintenance and possible bloat while historical rows are
+updated. After a large backfill, rebuild it online during a normal maintenance
+window:
+
+```sql
+REINDEX INDEX CONCURRENTLY idx_issue_workspace_last_activity;
+```
+
+Do not roll application writers back to a version that predates
+`last_activity_at` after the backfill. The nullable column keeps old readers
+compatible, but old writers do not maintain the new clock.
diff --git a/server/cmd/backfill_issue_last_activity/main.go b/server/cmd/backfill_issue_last_activity/main.go
new file mode 100644
index 0000000000..a9e4b9a516
--- /dev/null
+++ b/server/cmd/backfill_issue_last_activity/main.go
@@ -0,0 +1,174 @@
+// backfill_issue_last_activity reconstructs issue.last_activity_at from the
+// existing updated_at value. Run it after every issue-writing backend in a
+// rolling deployment has been upgraded; older writers do not maintain the new
+// column. The command is deliberately separate from migrations and startup so
+// a large issue table never blocks a deploy.
+//
+// Each batch commits independently. SIGINT/SIGTERM, a database error, or
+// --max-batches can stop the walk, and a later invocation resumes from rows
+// whose last_activity_at is still NULL. Each pass advances by an id keyset
+// watermark instead of rescanning its completed prefix. A session advisory lock
+// serializes operators while SKIP LOCKED avoids waiting behind unrelated hot
+// rows; later passes wrap around to recover rows skipped while locked.
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/issueactivitybackfill"
+ "github.com/multica-ai/multica/server/internal/logger"
+)
+
+const (
+ advisoryLockName = "issue_last_activity_backfill"
+ defaultMaxStalledPasses = 10
+)
+
+type stalledPassGuard struct {
+ max int
+ consecutive int
+}
+
+func (g *stalledPassGuard) observe(passRows, remaining int64) error {
+ if passRows > 0 {
+ g.consecutive = 0
+ return nil
+ }
+ g.consecutive++
+ if g.max > 0 && g.consecutive >= g.max {
+ return fmt.Errorf(
+ "issue last-activity backfill stalled: %d consecutive passes made no progress with %d rows remaining; release long-held row locks and rerun, or increase --max-stalled-passes",
+ g.consecutive,
+ remaining,
+ )
+ }
+ return nil
+}
+
+func main() {
+ logger.Init()
+ if err := run(); err != nil {
+ slog.Error("issue last-activity backfill failed", "error", err)
+ os.Exit(1)
+ }
+}
+
+func run() error {
+ batchSize := flag.Int("batch-size", issueactivitybackfill.DefaultBatchSize, "maximum issue rows updated per transaction")
+ delay := flag.Duration("sleep-between-batches", 100*time.Millisecond, "delay between committed batches")
+ maxBatches := flag.Int("max-batches", 0, "stop after N batches (0 = finish all remaining rows)")
+ maxStalledPasses := flag.Int("max-stalled-passes", defaultMaxStalledPasses, "fail after N consecutive no-progress passes (0 = disable the guard)")
+ flag.Parse()
+ if *batchSize < 1 {
+ return fmt.Errorf("--batch-size must be at least 1")
+ }
+ if *delay < 0 {
+ return fmt.Errorf("--sleep-between-batches must not be negative")
+ }
+ if *maxBatches < 0 {
+ return fmt.Errorf("--max-batches must not be negative")
+ }
+ if *maxStalledPasses < 0 {
+ return fmt.Errorf("--max-stalled-passes must not be negative")
+ }
+
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ return fmt.Errorf("connect to database: %w", err)
+ }
+ defer pool.Close()
+ if err := pool.Ping(ctx); err != nil {
+ return fmt.Errorf("ping database: %w", err)
+ }
+
+ lockConn, err := pool.Acquire(ctx)
+ if err != nil {
+ return fmt.Errorf("acquire advisory-lock connection: %w", err)
+ }
+ defer lockConn.Release()
+ if _, err := lockConn.Exec(ctx, `SELECT pg_advisory_lock(hashtextextended($1, 0))`, advisoryLockName); err != nil {
+ return fmt.Errorf("acquire advisory lock: %w", err)
+ }
+ defer func() {
+ _, _ = lockConn.Exec(context.Background(), `SELECT pg_advisory_unlock(hashtextextended($1, 0))`, advisoryLockName)
+ }()
+
+ remaining, err := issueactivitybackfill.CountRemaining(ctx, pool, "")
+ if err != nil {
+ return err
+ }
+ slog.Info("issue last-activity backfill started", "remaining", remaining, "batch_size", *batchSize, "delay", delay.String())
+
+ var total int64
+ var passRows int64
+ var afterID *string
+ pass := 1
+ stallGuard := stalledPassGuard{max: *maxStalledPasses}
+ for batch := 1; *maxBatches == 0 || batch <= *maxBatches; batch++ {
+ result, err := issueactivitybackfill.Batch(ctx, pool, issueactivitybackfill.Options{
+ BatchSize: *batchSize,
+ AfterID: afterID,
+ })
+ if err != nil {
+ return err
+ }
+ if result.Rows > 0 && result.LastID == "" {
+ return fmt.Errorf("issue last-activity backfill batch returned %d rows without a keyset watermark", result.Rows)
+ }
+ total += result.Rows
+ passRows += result.Rows
+ if result.Rows > 0 {
+ slog.Info("issue last-activity batch committed", "batch", batch, "pass", pass, "rows", result.Rows, "total", total, "last_id", result.LastID)
+ next := result.LastID
+ afterID = &next
+ }
+ // A short/empty keyset batch marks the end of this pass, not necessarily
+ // completion: SKIP LOCKED may have left hot rows below the watermark.
+ // Count once per pass, then wrap to the start until those rows unlock.
+ if result.Rows < int64(*batchSize) {
+ remaining, err = issueactivitybackfill.CountRemaining(ctx, pool, "")
+ if err != nil {
+ return err
+ }
+ if remaining == 0 {
+ slog.Info("issue last-activity backfill complete", "rows_backfilled", total, "remaining", 0)
+ return nil
+ }
+ if err := stallGuard.observe(passRows, remaining); err != nil {
+ return err
+ }
+ pass++
+ afterID = nil
+ slog.Info("issue last-activity pass complete; rows remain locked or pending", "pass", pass-1, "rows", passRows, "remaining", remaining, "stalled_passes", stallGuard.consecutive)
+ passRows = 0
+ }
+ if *delay > 0 {
+ select {
+ case <-time.After(*delay):
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ }
+
+ remaining, err = issueactivitybackfill.CountRemaining(ctx, pool, "")
+ if err != nil {
+ return err
+ }
+ slog.Info("issue last-activity backfill stopped at max batches", "rows_backfilled", total, "remaining", remaining)
+ return nil
+}
diff --git a/server/cmd/backfill_issue_last_activity/main_test.go b/server/cmd/backfill_issue_last_activity/main_test.go
new file mode 100644
index 0000000000..81a84498f1
--- /dev/null
+++ b/server/cmd/backfill_issue_last_activity/main_test.go
@@ -0,0 +1,36 @@
+package main
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestStalledPassGuardFailsAfterConsecutiveNoProgressPasses(t *testing.T) {
+ guard := stalledPassGuard{max: 2}
+
+ if err := guard.observe(0, 7); err != nil {
+ t.Fatalf("first stalled pass: %v", err)
+ }
+ if err := guard.observe(3, 4); err != nil {
+ t.Fatalf("progressing pass: %v", err)
+ }
+ if guard.consecutive != 0 {
+ t.Fatalf("progress did not reset stalled passes: got %d", guard.consecutive)
+ }
+ if err := guard.observe(0, 4); err != nil {
+ t.Fatalf("first stalled pass after progress: %v", err)
+ }
+ err := guard.observe(0, 4)
+ if err == nil || !strings.Contains(err.Error(), "2 consecutive passes") || !strings.Contains(err.Error(), "4 rows remaining") {
+ t.Fatalf("second stalled pass error = %v, want count and remaining backlog", err)
+ }
+}
+
+func TestStalledPassGuardCanBeExplicitlyDisabled(t *testing.T) {
+ guard := stalledPassGuard{max: 0}
+ for range 100 {
+ if err := guard.observe(0, 1); err != nil {
+ t.Fatalf("disabled guard: %v", err)
+ }
+ }
+}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index e39f0dde38..c6a5f7f6c1 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -206,6 +206,7 @@ var concurrentIndexCleanups = map[string]string{
"356_autopilot_run_quota_reservation_index": "uq_autopilot_run_quota_reservation",
"357_webhook_delivery_replay_idempotency_index": "uq_webhook_delivery_replay_idempotency",
"358_autopilot_quota_reservation_state_index": "idx_autopilot_quota_reservation_state",
+ "361_issue_last_activity_index": "idx_issue_workspace_last_activity",
}
// concurrentDownIndexCleanups covers every migration whose down direction
diff --git a/server/cmd/server/workspace_scope_guard_test.go b/server/cmd/server/workspace_scope_guard_test.go
index 1560f1ee49..7a1ff14e4b 100644
--- a/server/cmd/server/workspace_scope_guard_test.go
+++ b/server/cmd/server/workspace_scope_guard_test.go
@@ -49,8 +49,9 @@ func TestWorkspaceScopeGuard(t *testing.T) {
id := seedComment(t, ctx, issueID)
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, util.UUIDToString(id)) })
- if err := queries.DeleteComment(ctx, db.DeleteCommentParams{ID: id, WorkspaceID: wsB}); err != nil {
- t.Fatalf("cross-workspace DeleteComment: expected nil error (no-op), got %v", err)
+ deleted, err := queries.DeleteComment(ctx, db.DeleteCommentParams{ID: id, WorkspaceID: wsB})
+ if err != nil || deleted.Changed {
+ t.Fatalf("cross-workspace DeleteComment = (%+v, %v), want unchanged result", deleted, err)
}
assertRowExists(t, ctx, "comment", id)
})
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 76ade30f9d..f20093a473 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -3339,6 +3339,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
updateParams.ExpectedRevision = pgtype.Int8{Int64: *req.ExpectedRevision, Valid: true}
}
var comment db.Comment
+ var issueRevision int64
transactionalEdit := replaceAttachments || (oldContent != req.Content && strictContentEdit)
if transactionalEdit {
// Strict body edits, attachment-set edits, and cancellation of tasks built
@@ -3353,7 +3354,12 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
- comment, err = qtx.UpdateComment(r.Context(), updateParams)
+ var updated db.UpdateCommentRow
+ updated, err = qtx.UpdateComment(r.Context(), updateParams)
+ if err == nil {
+ comment = updated.Comment()
+ issueRevision = updated.IssueRevision
+ }
if err == nil && oldContent != req.Content && strictContentEdit {
cancelled, err = qtx.CancelAgentTasksByTriggerComment(r.Context(), existing.ID)
}
@@ -3378,7 +3384,12 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
h.TaskService.BroadcastCancelledTasks(r.Context(), uuidToString(existing.WorkspaceID), cancelled)
}
} else {
- comment, err = h.Queries.UpdateComment(r.Context(), updateParams)
+ var updated db.UpdateCommentRow
+ updated, err = h.Queries.UpdateComment(r.Context(), updateParams)
+ if err == nil {
+ comment = updated.Comment()
+ issueRevision = updated.IssueRevision
+ }
}
if err != nil {
slog.Warn("update comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
@@ -3431,8 +3442,13 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
groupedAtt := h.groupAttachments(r, []pgtype.UUID{comment.ID})
cid := uuidToString(comment.ID)
resp := commentToResponse(comment, grouped[cid], groupedAtt[cid])
+ resp.IssueRevision = issueRevision
slog.Info("comment updated", append(logger.RequestAttrs(r), "comment_id", commentId)...)
- h.publish(protocol.EventCommentUpdated, workspaceID, actorType, actorID, map[string]any{"comment": resp})
+ eventPayload := map[string]any{"comment": resp}
+ if issueRevision > 0 {
+ eventPayload["issue_revision"] = issueRevision
+ }
+ h.publish(protocol.EventCommentUpdated, workspaceID, actorType, actorID, eventPayload)
// The broadcast above intentionally omits trigger_outcomes — it is the
// editor's private feedback, not shared timeline state (MUL-4525 §2).
@@ -3482,11 +3498,18 @@ func (h *Handler) DeleteComment(w http.ResponseWriter, r *http.Request) {
return
}
issue, err := h.Queries.GetIssue(r.Context(), comment.IssueID)
- if err != nil {
+ hasIssue := err == nil
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
slog.Warn("load issue for delete post-processing failed", "issue_id", uuidToString(comment.IssueID), "error", err)
writeError(w, http.StatusInternalServerError, "failed to load issue")
return
}
+ if errors.Is(err, pgx.ErrNoRows) {
+ // The issue delete may have won the race after GetCommentInWorkspace.
+ // Continue so DeleteComment can report whether the comment itself still
+ // existed; touching issue activity is intentionally best effort.
+ slog.Info("comment parent issue no longer exists", "issue_id", uuidToString(comment.IssueID), "comment_id", commentId)
+ }
// Collect attachment URLs before CASCADE delete removes them.
attachmentURLs, _ := h.Queries.ListAttachmentURLsByCommentID(r.Context(), comment.ID)
@@ -3500,26 +3523,39 @@ func (h *Handler) DeleteComment(w http.ResponseWriter, r *http.Request) {
slog.Warn("cancel tasks for deleted trigger comment failed", append(logger.RequestAttrs(r), "error", cancelErr, "comment_id", commentId)...)
}
- if err := h.Queries.DeleteComment(r.Context(), db.DeleteCommentParams{
+ deleted, err := h.Queries.DeleteComment(r.Context(), db.DeleteCommentParams{
ID: comment.ID,
WorkspaceID: comment.WorkspaceID,
- }); err != nil {
- slog.Warn("delete comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
- // Cancellation already committed but deletion did not. The comment is
- // still valid, so rebuild the complete cancelled batch (including this
- // trigger) before returning the storage error.
- h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, pgtype.UUID{})
- writeError(w, http.StatusInternalServerError, "failed to delete comment")
+ })
+ if err != nil || !deleted.Changed {
+ slog.Warn("delete comment failed", append(logger.RequestAttrs(r), "error", err, "changed", deleted.Changed, "comment_id", commentId)...)
+ // Cancellation already committed but deletion did not. If the parent
+ // issue still exists, rebuild the complete cancelled batch (including
+ // this trigger) before reporting the storage error or concurrent no-op.
+ if hasIssue {
+ h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, pgtype.UUID{})
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete comment")
+ } else {
+ writeError(w, http.StatusNotFound, "comment not found")
+ }
return
}
h.deleteS3Objects(r.Context(), attachmentURLs)
slog.Info("comment deleted", append(logger.RequestAttrs(r), "comment_id", commentId, "issue_id", uuidToString(comment.IssueID))...)
- h.publish(protocol.EventCommentDeleted, workspaceID, actorType, actorID, map[string]any{
+ eventPayload := map[string]any{
"comment_id": uuidToString(comment.ID),
"issue_id": uuidToString(comment.IssueID),
- })
- h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, comment.ID)
+ }
+ if deleted.IssueRevision > 0 {
+ eventPayload["issue_revision"] = deleted.IssueRevision
+ }
+ h.publish(protocol.EventCommentDeleted, workspaceID, actorType, actorID, eventPayload)
+ if hasIssue {
+ h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, comment.ID)
+ }
w.WriteHeader(http.StatusNoContent)
}
diff --git a/server/internal/handler/comment_touch_issue_test.go b/server/internal/handler/comment_touch_issue_test.go
index 8b645a3469..14f561ca8b 100644
--- a/server/internal/handler/comment_touch_issue_test.go
+++ b/server/internal/handler/comment_touch_issue_test.go
@@ -2,6 +2,7 @@ package handler
import (
"context"
+ "encoding/json"
"errors"
"net/http"
"net/http/httptest"
@@ -9,15 +10,18 @@ import (
"time"
"github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
-// TestCreateComment_BumpsIssueUpdatedAt pins MUL-5009: a new comment counts as
-// activity on the issue, so updated_at advances. This is what lets the
-// "Updated date" Kanban/list sort surface recently-discussed cards, not only
-// cards whose status changed.
-func TestCreateComment_BumpsIssueUpdatedAt(t *testing.T) {
+// TestCreateComment_BumpsIssueActivity pins MUL-5009 and MUL-6343: a new
+// comment advances both the legacy updated_at clock and the semantic activity
+// clock in the same statement.
+func TestCreateComment_BumpsIssueActivity(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
@@ -25,9 +29,9 @@ func TestCreateComment_BumpsIssueUpdatedAt(t *testing.T) {
issueID := createCommentTriggerPreviewIssue(t, "comment bumps updated_at", "", "")
- var before time.Time
- if err := testPool.QueryRow(ctx, `SELECT updated_at FROM issue WHERE id = $1`, issueID).Scan(&before); err != nil {
- t.Fatalf("read updated_at before: %v", err)
+ var before, activityBefore time.Time
+ if err := testPool.QueryRow(ctx, `SELECT updated_at, last_activity_at FROM issue WHERE id = $1`, issueID).Scan(&before, &activityBefore); err != nil {
+ t.Fatalf("read issue clocks before: %v", err)
}
// Guarantee a measurable wall-clock gap so the bump is unambiguous; now() is
@@ -44,14 +48,17 @@ func TestCreateComment_BumpsIssueUpdatedAt(t *testing.T) {
t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
}
- var after time.Time
- if err := testPool.QueryRow(ctx, `SELECT updated_at FROM issue WHERE id = $1`, issueID).Scan(&after); err != nil {
- t.Fatalf("read updated_at after: %v", err)
+ var after, activityAfter time.Time
+ if err := testPool.QueryRow(ctx, `SELECT updated_at, last_activity_at FROM issue WHERE id = $1`, issueID).Scan(&after, &activityAfter); err != nil {
+ t.Fatalf("read issue clocks after: %v", err)
}
if !after.After(before) {
t.Fatalf("issue updated_at was not bumped by a new comment: before=%s after=%s", before, after)
}
+ if !activityAfter.After(activityBefore) {
+ t.Fatalf("issue last_activity_at was not bumped by a new comment: before=%s after=%s", activityBefore, activityAfter)
+ }
}
// TestCreateComment_WorkspaceMismatchPersistsNothing pins the tenant-integrity
@@ -69,9 +76,9 @@ func TestCreateComment_WorkspaceMismatchPersistsNothing(t *testing.T) {
issueID := createCommentTriggerPreviewIssue(t, "comment workspace guard", "", "")
- var before time.Time
- if err := testPool.QueryRow(ctx, `SELECT updated_at FROM issue WHERE id = $1`, issueID).Scan(&before); err != nil {
- t.Fatalf("read updated_at before: %v", err)
+ var before, activityBefore time.Time
+ if err := testPool.QueryRow(ctx, `SELECT updated_at, last_activity_at FROM issue WHERE id = $1`, issueID).Scan(&before, &activityBefore); err != nil {
+ t.Fatalf("read issue clocks before: %v", err)
}
// A workspace that is NOT the issue's workspace: the issue exists, but the
@@ -97,11 +104,386 @@ func TestCreateComment_WorkspaceMismatchPersistsNothing(t *testing.T) {
t.Fatalf("workspace mismatch must persist no comment, found %d", commentCount)
}
- var after time.Time
- if err := testPool.QueryRow(ctx, `SELECT updated_at FROM issue WHERE id = $1`, issueID).Scan(&after); err != nil {
- t.Fatalf("read updated_at after: %v", err)
+ var after, activityAfter time.Time
+ if err := testPool.QueryRow(ctx, `SELECT updated_at, last_activity_at FROM issue WHERE id = $1`, issueID).Scan(&after, &activityAfter); err != nil {
+ t.Fatalf("read issue clocks after: %v", err)
}
if !after.Equal(before) {
t.Fatalf("workspace mismatch must not bump updated_at: before=%s after=%s", before, after)
}
+ if !activityAfter.Equal(activityBefore) {
+ t.Fatalf("workspace mismatch must not bump last_activity_at: before=%s after=%s", activityBefore, activityAfter)
+ }
+}
+
+func TestUpdateAndDeleteCommentBumpIssueActivity(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := createCommentTriggerPreviewIssue(t, "comment mutations bump activity", "", "")
+ comment, err := testHandler.Queries.CreateComment(ctx, db.CreateCommentParams{
+ IssueID: parseUUID(issueID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ AuthorType: "member",
+ AuthorID: parseUUID(testUserID),
+ Content: "before",
+ Type: "comment",
+ })
+ if err != nil {
+ t.Fatalf("CreateComment: %v", err)
+ }
+
+ base := time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)
+ setBase := func() {
+ t.Helper()
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET last_activity_at = $2 WHERE id = $1`, issueID, base); err != nil {
+ t.Fatalf("reset last_activity_at: %v", err)
+ }
+ }
+ readActivity := func() time.Time {
+ t.Helper()
+ var got time.Time
+ if err := testPool.QueryRow(ctx, `SELECT last_activity_at FROM issue WHERE id = $1`, issueID).Scan(&got); err != nil {
+ t.Fatalf("read last_activity_at: %v", err)
+ }
+ return got
+ }
+
+ setBase()
+ updated, err := testHandler.Queries.UpdateComment(ctx, db.UpdateCommentParams{
+ ID: comment.ID,
+ Content: "after",
+ })
+ if err != nil {
+ t.Fatalf("UpdateComment: %v", err)
+ }
+ if updated.IssueRevision == 0 {
+ t.Fatal("comment edit omitted the advanced issue revision")
+ }
+ if got := readActivity(); !got.After(base) {
+ t.Fatalf("comment edit did not advance activity: base=%s got=%s", base, got)
+ }
+
+ setBase()
+ noOp, err := testHandler.Queries.UpdateComment(ctx, db.UpdateCommentParams{
+ ID: comment.ID,
+ Content: "after",
+ })
+ if err != nil {
+ t.Fatalf("no-op UpdateComment: %v", err)
+ }
+ if noOp.IssueRevision != 0 {
+ t.Fatalf("no-op comment edit issue revision = %d, want 0", noOp.IssueRevision)
+ }
+ if got := readActivity(); !got.Equal(base) {
+ t.Fatalf("no-op comment edit changed activity: base=%s got=%s", base, got)
+ }
+
+ setBase()
+ deleted, err := testHandler.Queries.DeleteComment(ctx, db.DeleteCommentParams{
+ ID: comment.ID,
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil || !deleted.Changed {
+ t.Fatalf("DeleteComment = (%+v, %v), want changed result", deleted, err)
+ }
+ if deleted.IssueRevision == 0 {
+ t.Fatal("comment delete omitted the advanced issue revision")
+ }
+ if got := readActivity(); !got.After(base) {
+ t.Fatalf("comment delete did not advance activity: base=%s got=%s", base, got)
+ }
+}
+
+func TestCommentMutationEventsCarryIssueRevision(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "comment mutation event revision")
+ commentID := dbfx.Comment(t, issueID, "before")
+
+ h := *testHandler
+ h.Bus = events.New()
+ var updatedEvent, deletedEvent events.Event
+ h.Bus.Subscribe(protocol.EventCommentUpdated, func(event events.Event) {
+ updatedEvent = event
+ })
+ h.Bus.Subscribe(protocol.EventCommentDeleted, func(event events.Event) {
+ deletedEvent = event
+ })
+
+ update := httptest.NewRecorder()
+ h.UpdateComment(update, withURLParam(newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{
+ "content": "after",
+ }), "commentId", commentID))
+ if update.Code != http.StatusOK {
+ t.Fatalf("UpdateComment = %d: %s", update.Code, update.Body.String())
+ }
+ var response CommentResponse
+ if err := json.NewDecoder(update.Body).Decode(&response); err != nil {
+ t.Fatalf("decode update response: %v", err)
+ }
+ if response.IssueRevision != 2 {
+ t.Fatalf("update response issue_revision = %d, want 2", response.IssueRevision)
+ }
+ updatedPayload, ok := updatedEvent.Payload.(map[string]any)
+ if !ok || updatedPayload["issue_revision"] != int64(2) {
+ t.Fatalf("update event issue_revision = %#v, want 2", updatedEvent.Payload)
+ }
+
+ deleted := httptest.NewRecorder()
+ h.DeleteComment(deleted, withURLParam(newRequest(http.MethodDelete, "/api/comments/"+commentID, nil), "commentId", commentID))
+ if deleted.Code != http.StatusNoContent {
+ t.Fatalf("DeleteComment = %d: %s", deleted.Code, deleted.Body.String())
+ }
+ deletedPayload, ok := deletedEvent.Payload.(map[string]any)
+ if !ok || deletedPayload["issue_revision"] != int64(3) {
+ t.Fatalf("delete event issue_revision = %#v, want 3", deletedEvent.Payload)
+ }
+}
+
+// A conditional update that loses after waiting for the comment row must not
+// advance the parent issue. The old sibling CTEs could run the issue UPDATE
+// from a stale target snapshot even when the comment UPDATE later matched no
+// rows, producing phantom activity and a phantom owner revision.
+func TestUpdateCommentLosingRaceDoesNotTouchIssue(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := dbfx.Issue(t, "losing comment update", testutil.Cols{
+ "revision": 7,
+ "last_activity_at": testutil.Raw("'2020-01-01T00:00:00Z'::timestamptz"),
+ })
+ commentID := dbfx.Comment(t, issueID, "base")
+
+ holder, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder: %v", err)
+ }
+ defer holder.Rollback(ctx)
+ if _, err := holder.Exec(ctx, `SELECT id FROM comment WHERE id = $1 FOR UPDATE`, commentID); err != nil {
+ t.Fatalf("lock comment: %v", err)
+ }
+
+ done := make(chan error, 1)
+ go func() {
+ _, updateErr := testHandler.Queries.UpdateComment(context.Background(), db.UpdateCommentParams{
+ ID: parseUUID(commentID),
+ Content: "loser",
+ ExpectedRevision: pgtype.Int8{Int64: 1, Valid: true},
+ ContentBase: pgtype.Text{String: "base", Valid: true},
+ })
+ done <- updateErr
+ }()
+ waitForCommentMutationLock(t, "UpdateComment", done)
+
+ if _, err := holder.Exec(ctx, `UPDATE comment SET content = 'winner', revision = revision + 1 WHERE id = $1`, commentID); err != nil {
+ t.Fatalf("commit winning edit: %v", err)
+ }
+ if err := holder.Commit(ctx); err != nil {
+ t.Fatalf("commit holder: %v", err)
+ }
+ if err := <-done; !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("losing update error = %v, want pgx.ErrNoRows", err)
+ }
+
+ assertIssueActivityState(t, issueID, 7, time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC))
+}
+
+// A delete that loses after waiting for the same comment row likewise must not
+// mutate the issue. The issue touch now depends on DELETE ... RETURNING, so an
+// empty delete result is an empty activity source.
+func TestDeleteCommentLosingRaceDoesNotTouchIssue(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := dbfx.Issue(t, "losing comment delete", testutil.Cols{
+ "revision": 11,
+ "last_activity_at": testutil.Raw("'2020-01-02T00:00:00Z'::timestamptz"),
+ })
+ commentID := dbfx.Comment(t, issueID, "delete me")
+
+ holder, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder: %v", err)
+ }
+ defer holder.Rollback(ctx)
+ if _, err := holder.Exec(ctx, `SELECT id FROM comment WHERE id = $1 FOR UPDATE`, commentID); err != nil {
+ t.Fatalf("lock comment: %v", err)
+ }
+
+ type deleteResult struct {
+ row db.DeleteCommentRow
+ err error
+ }
+ done := make(chan deleteResult, 1)
+ go func() {
+ row, deleteErr := testHandler.Queries.DeleteComment(context.Background(), db.DeleteCommentParams{
+ ID: parseUUID(commentID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ done <- deleteResult{row: row, err: deleteErr}
+ }()
+ lockDone := make(chan error, 1)
+ go func() {
+ result := <-done
+ if result.err == nil && result.row.Changed {
+ lockDone <- errors.New("losing delete unexpectedly changed a row")
+ return
+ }
+ lockDone <- result.err
+ }()
+ waitForCommentMutationLock(t, "DeleteComment", lockDone)
+
+ if _, err := holder.Exec(ctx, `DELETE FROM comment WHERE id = $1`, commentID); err != nil {
+ t.Fatalf("commit winning delete: %v", err)
+ }
+ if err := holder.Commit(ctx); err != nil {
+ t.Fatalf("commit holder: %v", err)
+ }
+ if err := <-lockDone; err != nil {
+ t.Fatalf("losing delete: %v", err)
+ }
+
+ assertIssueActivityState(t, issueID, 11, time.Date(2020, time.January, 2, 0, 0, 0, 0, time.UTC))
+}
+
+// Issue teardown locks the owner and then cascades into comments. A comment
+// mutation must wait for that owner lock before taking the child lock; taking
+// them in the opposite order would deadlock when teardown reaches the cascade.
+func TestCommentMutationsFollowIssueTeardownLockOrder(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ tests := []struct {
+ name string
+ queryName string
+ mutate func(context.Context, string) error
+ }{
+ {
+ name: "update",
+ queryName: "UpdateComment",
+ mutate: func(ctx context.Context, commentID string) error {
+ _, err := testHandler.Queries.UpdateComment(ctx, db.UpdateCommentParams{
+ ID: parseUUID(commentID),
+ Content: "concurrent edit",
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ return errors.New("comment update succeeded after its issue was deleted")
+ },
+ },
+ {
+ name: "delete",
+ queryName: "DeleteComment",
+ mutate: func(ctx context.Context, commentID string) error {
+ result, err := testHandler.Queries.DeleteComment(ctx, db.DeleteCommentParams{
+ ID: parseUUID(commentID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ return err
+ }
+ if result.Changed {
+ return errors.New("comment delete changed a row after its issue was deleted")
+ }
+ return nil
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ issueID := dbfx.Issue(t, "comment mutation vs issue teardown "+tt.name)
+ commentID := dbfx.Comment(t, issueID, "before")
+
+ teardown, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin issue teardown: %v", err)
+ }
+ defer teardown.Rollback(context.Background())
+ qtx := testHandler.Queries.WithTx(teardown)
+ if _, err := qtx.LockIssueForDelete(ctx, db.LockIssueForDeleteParams{
+ ID: parseUUID(issueID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ }); err != nil {
+ t.Fatalf("lock issue for teardown: %v", err)
+ }
+
+ mutationDone := make(chan error, 1)
+ go func() {
+ mutationDone <- tt.mutate(ctx, commentID)
+ }()
+ waitForCommentMutationLock(t, tt.queryName, mutationDone)
+
+ // This is the delete phase of deleteIssueAndCollectAttachmentURLs.
+ // If the mutation took the comment before waiting for the issue, the
+ // ON DELETE CASCADE below closes a real issue/comment deadlock cycle.
+ deleteErr := qtx.DeleteIssue(ctx, db.DeleteIssueParams{
+ ID: parseUUID(issueID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if deleteErr == nil {
+ deleteErr = teardown.Commit(ctx)
+ } else {
+ _ = teardown.Rollback(context.Background())
+ }
+ mutationErr := <-mutationDone
+ if deleteErr != nil {
+ t.Fatalf("issue teardown deadlocked or failed: %v", deleteErr)
+ }
+ if mutationErr != nil {
+ t.Fatalf("comment mutation deadlocked or returned an unexpected result: %v", mutationErr)
+ }
+ })
+ }
+}
+
+func waitForCommentMutationLock(t *testing.T, queryName string, done <-chan error) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ select {
+ case err := <-done:
+ t.Fatalf("%s completed before the competing row lock was released: %v", queryName, err)
+ default:
+ }
+ var waiting bool
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT EXISTS (
+ SELECT 1 FROM pg_stat_activity
+ WHERE datname = current_database()
+ AND wait_event_type = 'Lock'
+ AND query LIKE '%' || $1 || '%'
+ )
+ `, "-- name: "+queryName+" :one").Scan(&waiting); err != nil {
+ t.Fatalf("observe blocked %s: %v", queryName, err)
+ }
+ if waiting {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatalf("%s did not block on the competing comment lock", queryName)
+}
+
+func assertIssueActivityState(t *testing.T, issueID string, wantRevision int64, wantActivity time.Time) {
+ t.Helper()
+ var revision int64
+ var activity time.Time
+ dbfx.QueryRow(t, `SELECT revision, last_activity_at FROM issue WHERE id = $1`, issueID).Scan(&revision, &activity)
+ if revision != wantRevision || !activity.Equal(wantActivity) {
+ t.Fatalf("issue activity = (revision %d, %s), want (%d, %s)", revision, activity, wantRevision, wantActivity)
+ }
}
diff --git a/server/internal/handler/comment_trigger_preview_test.go b/server/internal/handler/comment_trigger_preview_test.go
index b0ea00bd1e..b007088873 100644
--- a/server/internal/handler/comment_trigger_preview_test.go
+++ b/server/internal/handler/comment_trigger_preview_test.go
@@ -36,8 +36,8 @@ func createCommentTriggerPreviewIssue(t *testing.T, title string, assigneeType,
var issueID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO issue (workspace_id, creator_type, creator_id, title, assignee_type, assignee_id, number)
- VALUES ($1, 'member', $2, $3, $4, $5, $6)
+ INSERT INTO issue (workspace_id, creator_type, creator_id, title, assignee_type, assignee_id, number, last_activity_at)
+ VALUES ($1, 'member', $2, $3, $4, $5, $6, now())
RETURNING id
`, testWorkspaceID, testUserID, title, assigneeTypeArg, assigneeIDArg, number).Scan(&issueID); err != nil {
t.Fatalf("create issue: %v", err)
diff --git a/server/internal/handler/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
index bb73a08bdb..c2e537a2ba 100644
--- a/server/internal/handler/daemon_comment_delivery_test.go
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -115,6 +115,24 @@ type failDeleteCommentDB struct {
delegate db.DBTX
}
+type zeroDeleteCommentDB struct {
+ delegate db.DBTX
+}
+
+type deleteCommentResultRow struct {
+ changed bool
+ err error
+}
+
+func (r deleteCommentResultRow) Scan(dest ...interface{}) error {
+ if r.err != nil {
+ return r.err
+ }
+ *(dest[0].(*bool)) = r.changed
+ *(dest[1].(*int64)) = 0
+ return nil
+}
+
func (f *failDeleteCommentDB) Exec(ctx context.Context, query string, args ...interface{}) (pgconn.CommandTag, error) {
if strings.Contains(query, "-- name: DeleteComment") {
return pgconn.CommandTag{}, errors.New("injected comment deletion failure")
@@ -127,9 +145,30 @@ func (f *failDeleteCommentDB) Query(ctx context.Context, query string, args ...i
}
func (f *failDeleteCommentDB) QueryRow(ctx context.Context, query string, args ...interface{}) pgx.Row {
+ if strings.Contains(query, "-- name: DeleteComment") {
+ return deleteCommentResultRow{err: errors.New("injected comment deletion failure")}
+ }
return f.delegate.QueryRow(ctx, query, args...)
}
+func (z *zeroDeleteCommentDB) Exec(ctx context.Context, query string, args ...interface{}) (pgconn.CommandTag, error) {
+ if strings.Contains(query, "-- name: DeleteComment") {
+ return pgconn.NewCommandTag("DELETE 0"), nil
+ }
+ return z.delegate.Exec(ctx, query, args...)
+}
+
+func (z *zeroDeleteCommentDB) Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) {
+ return z.delegate.Query(ctx, query, args...)
+}
+
+func (z *zeroDeleteCommentDB) QueryRow(ctx context.Context, query string, args ...interface{}) pgx.Row {
+ if strings.Contains(query, "-- name: DeleteComment") {
+ return deleteCommentResultRow{changed: false}
+ }
+ return z.delegate.QueryRow(ctx, query, args...)
+}
+
func (f *failNthBegin) Begin(ctx context.Context) (pgx.Tx, error) {
f.calls++
if f.calls == f.failAt {
@@ -462,6 +501,28 @@ func TestDeleteComment_FailureRestoresCancelledCompleteBatch(t *testing.T) {
assertRepairedCommentBatch(t, fixture, fixture.commentID[2], fixture.commentID[:2])
}
+func TestDeleteComment_ConcurrentNoOpIsReportedAndRestoresCancelledBatch(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Concurrent deletion batch repair")
+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign concurrent-delete issue: %v", err)
+ }
+
+ zeroHandler := *testHandler
+ zeroHandler.Queries = db.New(&zeroDeleteCommentDB{delegate: testPool})
+ w := httptest.NewRecorder()
+ req := newRequest(http.MethodDelete, "/api/comments/"+fixture.commentID[2], nil)
+ req = withURLParam(req, "commentId", fixture.commentID[2])
+ zeroHandler.DeleteComment(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("DeleteComment no-op: got %d: %s", w.Code, w.Body.String())
+ }
+
+ assertRepairedCommentBatch(t, fixture, fixture.commentID[2], fixture.commentID[:2])
+}
+
func assertRepairedCommentBatch(t *testing.T, fixture commentDeliveryFixture, wantTrigger string, wantCoalesced []string) {
t.Helper()
var originalStatus string
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 9b20c057ce..d53b63deab 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -547,8 +547,11 @@ func ptrToText(s *string) pgtype.Text { return util.PtrToText(s) }
func strToText(s string) pgtype.Text { return util.StrToText(s) }
func timestampToString(t pgtype.Timestamptz) string { return util.TimestampToString(t) }
func timestampToPtr(t pgtype.Timestamptz) *string { return util.TimestampToPtr(t) }
-func dateToPtr(d pgtype.Date) *string { return util.DateToPtr(d) }
-func uuidToPtr(u pgtype.UUID) *string { return util.UUIDToPtr(u) }
+func timestampToNanoPtr(t pgtype.Timestamptz) *string {
+ return util.TimestampToNanoPtr(t)
+}
+func dateToPtr(d pgtype.Date) *string { return util.DateToPtr(d) }
+func uuidToPtr(u pgtype.UUID) *string { return util.UUIDToPtr(u) }
// uuidsToStrings maps a UUID array column to string ids, skipping NULL/invalid
// entries. Returns nil (not an empty slice) when there is nothing to emit so
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 3ffa030228..06ad2253a1 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -63,6 +63,9 @@ type IssueResponse struct {
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Revision int64 `json:"revision"`
+ // LastActivityAt is the latest semantic issue activity. It stays nullable
+ // while the operator-run historical backfill is incomplete.
+ LastActivityAt *string `json:"last_activity_at"`
// Metadata is the per-issue KV map (see issue_metadata.go). Always emitted
// (empty object when unset) so frontend code can `issue.metadata[key]`
// without nil-guarding the parent field.
@@ -295,6 +298,7 @@ func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {
CreatedAt: timestampToString(i.CreatedAt),
UpdatedAt: timestampToString(i.UpdatedAt),
Revision: i.Revision,
+ LastActivityAt: timestampToNanoPtr(i.LastActivityAt),
Metadata: parseIssueMetadata(i.Metadata),
Properties: parseIssueProperties(i.Properties),
}
@@ -331,6 +335,7 @@ func issueListRowToResponse(i db.ListIssuesRow, issuePrefix string) IssueRespons
CreatedAt: timestampToString(i.CreatedAt),
UpdatedAt: timestampToString(i.UpdatedAt),
Revision: i.Revision,
+ LastActivityAt: timestampToNanoPtr(i.LastActivityAt),
Metadata: parseIssueMetadata(i.Metadata),
Properties: parseIssueProperties(i.Properties),
}
@@ -399,6 +404,7 @@ func openIssueRowToResponse(i db.ListOpenIssuesRow, issuePrefix string) IssueRes
CreatedAt: timestampToString(i.CreatedAt),
UpdatedAt: timestampToString(i.UpdatedAt),
Revision: i.Revision,
+ LastActivityAt: timestampToNanoPtr(i.LastActivityAt),
Metadata: parseIssueMetadata(i.Metadata),
Properties: parseIssueProperties(i.Properties),
}
@@ -825,7 +831,7 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,
query := fmt.Sprintf(`SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position,
- i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id,
+ i.start_date, i.due_date, i.created_at, i.updated_at, i.last_activity_at, i.number, i.project_id,
i.revision,
COUNT(*) OVER() AS total_count,
%s AS match_source,
@@ -912,6 +918,7 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {
&sr.issue.DueDate,
&sr.issue.CreatedAt,
&sr.issue.UpdatedAt,
+ &sr.issue.LastActivityAt,
&sr.issue.Number,
&sr.issue.ProjectID,
&sr.issue.Revision,
@@ -1201,6 +1208,8 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
switch s {
case "position", "title", "created_at", "updated_at", "start_date", "due_date":
sortCol = s
+ case "last_activity":
+ sortCol = "last_activity_at"
case "status":
sortCol = "CASE i.status WHEN 'backlog' THEN 0 WHEN 'todo' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'in_review' THEN 3 WHEN 'done' THEN 4 WHEN 'blocked' THEN 5 WHEN 'cancelled' THEN 6 ELSE 7 END"
sortIsExpr = true
@@ -1233,6 +1242,9 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
}
}
sortDir := "ASC"
+ if sortCol == "last_activity_at" {
+ sortDir = "DESC"
+ }
if sortCol != "position" {
if d := r.URL.Query().Get("direction"); d != "" {
switch strings.ToLower(d) {
@@ -1426,7 +1438,7 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
orderBy = "i." + sortCol
}
orderBy += " " + sortDir
- if sortCol == "start_date" || sortCol == "due_date" || sortIsProperty {
+ if sortCol == "start_date" || sortCol == "due_date" || sortCol == "last_activity_at" || sortIsProperty {
// Property values are sparse: issues without one sort last in both
// directions (mirrors the client comparator).
orderBy += " NULLS LAST"
@@ -1434,14 +1446,18 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
// created_at alone is not unique (bulk imports share timestamps); without
// a unique final key the database may reorder ties between two
// LIMIT/OFFSET requests, duplicating or dropping rows at page boundaries.
- orderBy += ", i.created_at DESC, i.id DESC"
+ if sortCol == "last_activity_at" {
+ orderBy += ", i.id DESC"
+ } else {
+ orderBy += ", i.created_at DESC, i.id DESC"
+ }
offsetRef := addArg(int64(offset))
limitRef := addArg(int64(limit))
query := fmt.Sprintf(`SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
i.revision
FROM issue i
WHERE %s
@@ -1476,6 +1492,7 @@ LIMIT %s OFFSET %s`, whereSql, orderBy, limitRef, offsetRef)
&row.DueDate,
&row.CreatedAt,
&row.UpdatedAt,
+ &row.LastActivityAt,
&row.Number,
&row.ProjectID,
&row.Metadata,
@@ -1957,6 +1974,8 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {
switch s {
case "position", "title", "created_at", "updated_at", "start_date", "due_date":
sortCol = s
+ case "last_activity":
+ sortCol = "last_activity_at"
case "status":
sortCol = "CASE i.status WHEN 'backlog' THEN 0 WHEN 'todo' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'in_review' THEN 3 WHEN 'done' THEN 4 WHEN 'blocked' THEN 5 WHEN 'cancelled' THEN 6 ELSE 7 END"
sortIsExpr = true
@@ -1989,6 +2008,9 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {
}
}
sortDir := "ASC"
+ if sortCol == "last_activity_at" {
+ sortDir = "DESC"
+ }
if sortCol != "position" {
if d := r.URL.Query().Get("direction"); d != "" {
switch strings.ToLower(d) {
@@ -2008,12 +2030,16 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {
intraGroupOrder = "i." + sortCol
}
intraGroupOrder += " " + sortDir
- if sortCol == "start_date" || sortCol == "due_date" || sortIsProperty {
+ if sortCol == "start_date" || sortCol == "due_date" || sortCol == "last_activity_at" || sortIsProperty {
intraGroupOrder += " NULLS LAST"
}
// Unique final key — see ListIssues: created_at ties would otherwise make
// ROW_NUMBER() unstable across per-group offset pages.
- intraGroupOrder += ", i.created_at DESC, i.id DESC"
+ if sortCol == "last_activity_at" {
+ intraGroupOrder += ", i.id DESC"
+ } else {
+ intraGroupOrder += ", i.created_at DESC, i.id DESC"
+ }
offsetRef := addArg(int64(offset))
limitRef := addArg(int64(limit))
@@ -2022,8 +2048,8 @@ WITH ranked AS (
SELECT
i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at,
- i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.last_activity_at,
+ i.number, i.project_id, i.metadata, i.stage, i.properties, i.revision,
COUNT(*) OVER (PARTITION BY i.assignee_type, i.assignee_id) AS group_total,
ROW_NUMBER() OVER (
PARTITION BY i.assignee_type, i.assignee_id
@@ -2035,8 +2061,8 @@ WITH ranked AS (
SELECT
id, workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
- parent_issue_id, position, start_date, due_date, created_at, updated_at,
- number, project_id, metadata, stage, properties, group_total
+ parent_issue_id, position, start_date, due_date, created_at, updated_at, last_activity_at,
+ number, project_id, metadata, stage, properties, revision, group_total
FROM ranked
WHERE rn > %s AND rn <= %s + %s
ORDER BY
@@ -2078,11 +2104,13 @@ ORDER BY
&row.DueDate,
&row.CreatedAt,
&row.UpdatedAt,
+ &row.LastActivityAt,
&row.Number,
&row.ProjectID,
&row.Metadata,
&row.Stage,
&row.Properties,
+ &row.Revision,
&row.GroupTotal,
); err != nil {
slog.Warn("ListGroupedIssues scan failed", "error", err)
diff --git a/server/internal/handler/issue_last_activity_test.go b/server/internal/handler/issue_last_activity_test.go
new file mode 100644
index 0000000000..b6157481c5
--- /dev/null
+++ b/server/internal/handler/issue_last_activity_test.go
@@ -0,0 +1,174 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestUpdateIssueActivityExcludesPositionOnlyWrites(t *testing.T) {
+ created := createIssueForTest(t, map[string]any{
+ "title": "activity contract",
+ })
+ if created.LastActivityAt == nil {
+ t.Fatal("CreateIssue response omitted last_activity_at")
+ }
+ var initial time.Time
+ if err := testPool.QueryRow(context.Background(), `SELECT last_activity_at FROM issue WHERE id = $1`, created.ID).Scan(&initial); err != nil {
+ t.Fatalf("read initial last_activity_at: %v", err)
+ }
+
+ update := func(body map[string]any) IssueResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ r := withURLParam(newRequest(http.MethodPut, "/api/issues/"+created.ID, body), "id", created.ID)
+ testHandler.UpdateIssue(w, r)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var response IssueResponse
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode UpdateIssue: %v", err)
+ }
+ return response
+ }
+
+ positionOnly := update(map[string]any{"position": created.Position + 1})
+ if positionOnly.LastActivityAt == nil {
+ t.Fatal("position update response omitted last_activity_at")
+ }
+ var positionActivity time.Time
+ if err := testPool.QueryRow(context.Background(), `SELECT last_activity_at FROM issue WHERE id = $1`, created.ID).Scan(&positionActivity); err != nil {
+ t.Fatalf("read position last_activity_at: %v", err)
+ }
+ if !positionActivity.Equal(initial) {
+ t.Fatalf("position-only update changed activity: before=%s after=%s", initial, positionActivity)
+ }
+
+ time.Sleep(10 * time.Millisecond)
+ titleUpdate := update(map[string]any{"title": "activity contract changed"})
+ if titleUpdate.LastActivityAt == nil {
+ t.Fatal("title update response omitted last_activity_at")
+ }
+ var titleActivity time.Time
+ if err := testPool.QueryRow(context.Background(), `SELECT last_activity_at FROM issue WHERE id = $1`, created.ID).Scan(&titleActivity); err != nil {
+ t.Fatalf("read title last_activity_at: %v", err)
+ }
+ if !titleActivity.After(positionActivity) {
+ t.Fatalf("semantic update did not advance activity: before=%s after=%s", positionActivity, titleActivity)
+ }
+}
+
+func TestIssueActivityTimestampIsMonotonic(t *testing.T) {
+ created := createIssueForTest(t, map[string]any{"title": "monotonic activity"})
+ future := time.Now().UTC().Add(24 * time.Hour).Truncate(time.Microsecond)
+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET last_activity_at = $2 WHERE id = $1`, created.ID, future); err != nil {
+ t.Fatalf("seed future last_activity_at: %v", err)
+ }
+ updated, err := testHandler.Queries.SetIssueMetadataKey(context.Background(), db.SetIssueMetadataKeyParams{
+ Key: "activity_test",
+ Value: []byte(`"changed"`),
+ ID: parseUUID(created.ID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("SetIssueMetadataKey: %v", err)
+ }
+ if !updated.LastActivityAt.Valid || !updated.LastActivityAt.Time.Equal(future) {
+ t.Fatalf("activity timestamp regressed: got=%v want=%s", updated.LastActivityAt, future)
+ }
+}
+
+func TestIssueDecorationActivityOnlyAdvancesOnChange(t *testing.T) {
+ ctx := context.Background()
+ created := createIssueForTest(t, map[string]any{"title": "decoration activity"})
+ issueID := parseUUID(created.ID)
+ workspaceID := parseUUID(testWorkspaceID)
+ labelID := parseUUID(createTestIssueLabel(t, "activity-label-"+created.ID[:8]))
+ base := time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)
+
+ reset := func() {
+ t.Helper()
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET last_activity_at = $2 WHERE id = $1`, issueID, base); err != nil {
+ t.Fatalf("reset last_activity_at: %v", err)
+ }
+ }
+ read := func() time.Time {
+ t.Helper()
+ var got time.Time
+ if err := testPool.QueryRow(ctx, `SELECT last_activity_at FROM issue WHERE id = $1`, issueID).Scan(&got); err != nil {
+ t.Fatalf("read last_activity_at: %v", err)
+ }
+ return got
+ }
+
+ reset()
+ if _, err := testHandler.Queries.AttachLabelToIssue(ctx, db.AttachLabelToIssueParams{
+ IssueID: issueID, LabelID: labelID, WorkspaceID: workspaceID,
+ }); err != nil {
+ t.Fatalf("AttachLabelToIssue: %v", err)
+ }
+ if got := read(); !got.After(base) {
+ t.Fatalf("label attach did not advance activity: base=%s got=%s", base, got)
+ }
+ reset()
+ if _, err := testHandler.Queries.AttachLabelToIssue(ctx, db.AttachLabelToIssueParams{
+ IssueID: issueID, LabelID: labelID, WorkspaceID: workspaceID,
+ }); err != nil {
+ t.Fatalf("duplicate AttachLabelToIssue: %v", err)
+ }
+ if got := read(); !got.Equal(base) {
+ t.Fatalf("duplicate label attach changed activity: base=%s got=%s", base, got)
+ }
+
+ reset()
+ if _, err := testHandler.Queries.SetIssuePropertyValue(ctx, db.SetIssuePropertyValueParams{
+ Key: "00000000-0000-0000-0000-000000000001",
+ Value: []byte(`"selected"`),
+ ID: issueID,
+ WorkspaceID: workspaceID,
+ }); err != nil {
+ t.Fatalf("SetIssuePropertyValue: %v", err)
+ }
+ if got := read(); !got.After(base) {
+ t.Fatalf("property change did not advance activity: base=%s got=%s", base, got)
+ }
+ reset()
+ if _, err := testHandler.Queries.SetIssuePropertyValue(ctx, db.SetIssuePropertyValueParams{
+ Key: "00000000-0000-0000-0000-000000000001",
+ Value: []byte(`"selected"`),
+ ID: issueID,
+ WorkspaceID: workspaceID,
+ }); err != nil {
+ t.Fatalf("duplicate SetIssuePropertyValue: %v", err)
+ }
+ if got := read(); !got.Equal(base) {
+ t.Fatalf("duplicate property write changed activity: base=%s got=%s", base, got)
+ }
+}
+
+func TestMarkIssueFirstExecutedDoesNotChangeActivity(t *testing.T) {
+ created := createIssueForTest(t, map[string]any{"title": "execution is not activity"})
+ if created.LastActivityAt == nil {
+ t.Fatal("CreateIssue response omitted last_activity_at")
+ }
+ var before time.Time
+ if err := testPool.QueryRow(context.Background(), `SELECT last_activity_at FROM issue WHERE id = $1`, created.ID).Scan(&before); err != nil {
+ t.Fatalf("read last_activity_at before: %v", err)
+ }
+ if _, err := testHandler.Queries.MarkIssueFirstExecuted(context.Background(), parseUUID(created.ID)); err != nil {
+ t.Fatalf("MarkIssueFirstExecuted: %v", err)
+ }
+ var after time.Time
+ if err := testPool.QueryRow(context.Background(), `SELECT last_activity_at FROM issue WHERE id = $1`, created.ID).Scan(&after); err != nil {
+ t.Fatalf("read last_activity_at: %v", err)
+ }
+ if !after.Equal(before) {
+ t.Fatalf("execution lifecycle changed activity: before=%s after=%s", before, after)
+ }
+}
diff --git a/server/internal/handler/issue_payload_shape_test.go b/server/internal/handler/issue_payload_shape_test.go
index c33d1d9083..1fd8645636 100644
--- a/server/internal/handler/issue_payload_shape_test.go
+++ b/server/internal/handler/issue_payload_shape_test.go
@@ -126,27 +126,28 @@ func fullyPopulatedIssue(t *testing.T) db.Issue {
return time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
}
return db.Issue{
- ID: parseUUID("11111111-1111-1111-1111-111111111111"),
- WorkspaceID: parseUUID("22222222-2222-2222-2222-222222222222"),
- Number: 42,
- Title: "Fix login",
- Description: pgtype.Text{String: "details", Valid: true},
- Status: "todo",
- Priority: "high",
- AssigneeType: pgtype.Text{String: "agent", Valid: true},
- AssigneeID: parseUUID("33333333-3333-3333-3333-333333333333"),
- CreatorType: "member",
- CreatorID: parseUUID("44444444-4444-4444-4444-444444444444"),
- ParentIssueID: parseUUID("55555555-5555-5555-5555-555555555555"),
- ProjectID: parseUUID("66666666-6666-6666-6666-666666666666"),
- Position: 1024.5,
- Stage: pgtype.Int4{Int32: 2, Valid: true},
- StartDate: pgtype.Date{Time: utcDate(2026, time.January, 1), Valid: true},
- DueDate: pgtype.Date{Time: utcDate(2026, time.February, 1), Valid: true},
- CreatedAt: pgtype.Timestamptz{Time: utcDate(2026, time.January, 1), Valid: true},
- UpdatedAt: pgtype.Timestamptz{Time: utcDate(2026, time.January, 2), Valid: true},
- Metadata: []byte(`{"pr_url":"https://example.test/pr/1"}`),
- Properties: []byte(`{"77777777-7777-7777-7777-777777777777":"done"}`),
+ ID: parseUUID("11111111-1111-1111-1111-111111111111"),
+ WorkspaceID: parseUUID("22222222-2222-2222-2222-222222222222"),
+ Number: 42,
+ Title: "Fix login",
+ Description: pgtype.Text{String: "details", Valid: true},
+ Status: "todo",
+ Priority: "high",
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ AssigneeID: parseUUID("33333333-3333-3333-3333-333333333333"),
+ CreatorType: "member",
+ CreatorID: parseUUID("44444444-4444-4444-4444-444444444444"),
+ ParentIssueID: parseUUID("55555555-5555-5555-5555-555555555555"),
+ ProjectID: parseUUID("66666666-6666-6666-6666-666666666666"),
+ Position: 1024.5,
+ Stage: pgtype.Int4{Int32: 2, Valid: true},
+ StartDate: pgtype.Date{Time: utcDate(2026, time.January, 1), Valid: true},
+ DueDate: pgtype.Date{Time: utcDate(2026, time.February, 1), Valid: true},
+ CreatedAt: pgtype.Timestamptz{Time: utcDate(2026, time.January, 1), Valid: true},
+ UpdatedAt: pgtype.Timestamptz{Time: utcDate(2026, time.January, 2), Valid: true},
+ LastActivityAt: pgtype.Timestamptz{Time: utcDate(2026, time.January, 3), Valid: true},
+ Metadata: []byte(`{"pr_url":"https://example.test/pr/1"}`),
+ Properties: []byte(`{"77777777-7777-7777-7777-777777777777":"done"}`),
}
}
diff --git a/server/internal/handler/issue_revision_test.go b/server/internal/handler/issue_revision_test.go
index 75224a369b..2edb55dba1 100644
--- a/server/internal/handler/issue_revision_test.go
+++ b/server/internal/handler/issue_revision_test.go
@@ -374,8 +374,10 @@ func TestConcurrentRevisionWritesHaveExactlyOneWinner(t *testing.T) {
if err := testPool.QueryRow(ctx, `SELECT revision FROM comment WHERE id = $1`, commentID).Scan(&commentRevision); err != nil {
t.Fatalf("reload concurrent comment: %v", err)
}
- if issueRevision != 2 || commentRevision != 2 {
- t.Fatalf("concurrent revisions = issue:%d comment:%d, want 2/2", issueRevision, commentRevision)
+ // The winning comment edit is semantic issue activity, so it advances the
+ // parent issue revision once in addition to the winning issue title edit.
+ if issueRevision != 3 || commentRevision != 2 {
+ t.Fatalf("concurrent revisions = issue:%d comment:%d, want 3/2", issueRevision, commentRevision)
}
}
diff --git a/server/internal/handler/issue_sort_test.go b/server/internal/handler/issue_sort_test.go
index c5b4f23d38..8c93c60540 100644
--- a/server/internal/handler/issue_sort_test.go
+++ b/server/internal/handler/issue_sort_test.go
@@ -25,14 +25,15 @@ func TestListIssuesSortsByStatusAndUpdatedAt(t *testing.T) {
})
type fixture struct {
- title string
- status string
- updatedAt time.Time
+ title string
+ status string
+ updatedAt time.Time
+ activityAt time.Time
}
fixtures := []fixture{
- {"sort-done", "done", time.Date(2026, 1, 3, 0, 0, 0, 0, time.UTC)},
- {"sort-backlog", "backlog", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)},
- {"sort-progress", "in_progress", time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC)},
+ {"sort-done", "done", time.Date(2026, 1, 3, 0, 0, 0, 0, time.UTC), time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC)},
+ {"sort-backlog", "backlog", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), time.Date(2026, 2, 3, 0, 0, 0, 0, time.UTC)},
+ {"sort-progress", "in_progress", time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC), time.Date(2026, 2, 2, 0, 0, 0, 0, time.UTC)},
}
for index, item := range fixtures {
var number int
@@ -46,10 +47,10 @@ func TestListIssuesSortsByStatusAndUpdatedAt(t *testing.T) {
if _, err := testPool.Exec(ctx, `
INSERT INTO issue (
workspace_id, title, status, priority, creator_type, creator_id,
- position, number, project_id, created_at, updated_at
+ position, number, project_id, created_at, updated_at, last_activity_at
)
- VALUES ($1, $2, $3, 'none', 'member', $4, $5, $6, $7, $8, $8)
- `, testWorkspaceID, item.title, item.status, testUserID, index, number, projectID, item.updatedAt); err != nil {
+ VALUES ($1, $2, $3, 'none', 'member', $4, $5, $6, $7, $8, $8, $9)
+ `, testWorkspaceID, item.title, item.status, testUserID, index, number, projectID, item.updatedAt, item.activityAt); err != nil {
t.Fatalf("create issue %q: %v", item.title, err)
}
}
@@ -57,12 +58,14 @@ func TestListIssuesSortsByStatusAndUpdatedAt(t *testing.T) {
listTitles := func(sort, direction string) []string {
t.Helper()
path := fmt.Sprintf(
- "/api/issues?workspace_id=%s&project_id=%s&limit=50&sort=%s&direction=%s",
+ "/api/issues?workspace_id=%s&project_id=%s&limit=50&sort=%s",
testWorkspaceID,
projectID,
sort,
- direction,
)
+ if direction != "" {
+ path += "&direction=" + direction
+ }
w := httptest.NewRecorder()
testHandler.ListIssues(w, newRequest("GET", path, nil))
if w.Code != http.StatusOK {
@@ -80,6 +83,35 @@ func TestListIssuesSortsByStatusAndUpdatedAt(t *testing.T) {
}
return titles
}
+ groupedTitles := func(sort, direction string) []string {
+ t.Helper()
+ path := fmt.Sprintf(
+ "/api/issues/grouped?workspace_id=%s&project_id=%s&limit=50&sort=%s",
+ testWorkspaceID,
+ projectID,
+ sort,
+ )
+ if direction != "" {
+ path += "&direction=" + direction
+ }
+ w := httptest.NewRecorder()
+ testHandler.ListGroupedIssues(w, newRequest("GET", path, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListGroupedIssues: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var response GroupedIssuesResponse
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode grouped response: %v", err)
+ }
+ if len(response.Groups) != 1 {
+ t.Fatalf("ListGroupedIssues groups = %d, want 1", len(response.Groups))
+ }
+ titles := make([]string, 0, len(response.Groups[0].Issues))
+ for _, issue := range response.Groups[0].Issues {
+ titles = append(titles, issue.Title)
+ }
+ return titles
+ }
assertTitles := func(got, want []string) {
t.Helper()
@@ -108,4 +140,29 @@ func TestListIssuesSortsByStatusAndUpdatedAt(t *testing.T) {
"sort-progress",
"sort-backlog",
})
+ assertTitles(listTitles("last_activity", "asc"), []string{
+ "sort-done",
+ "sort-progress",
+ "sort-backlog",
+ })
+ assertTitles(listTitles("last_activity", "desc"), []string{
+ "sort-backlog",
+ "sort-progress",
+ "sort-done",
+ })
+ assertTitles(listTitles("last_activity", ""), []string{
+ "sort-backlog",
+ "sort-progress",
+ "sort-done",
+ })
+ assertTitles(groupedTitles("last_activity", "asc"), []string{
+ "sort-done",
+ "sort-progress",
+ "sort-backlog",
+ })
+ assertTitles(groupedTitles("last_activity", ""), []string{
+ "sort-backlog",
+ "sort-progress",
+ "sort-done",
+ })
}
diff --git a/server/internal/handler/issue_table_query_test.go b/server/internal/handler/issue_table_query_test.go
index 3fbc6c2ef1..f9d9b62764 100644
--- a/server/internal/handler/issue_table_query_test.go
+++ b/server/internal/handler/issue_table_query_test.go
@@ -459,6 +459,42 @@ func TestIssueTablePositionCursorIncludesIndexableLowerBound(t *testing.T) {
}
}
+func TestIssueTableLastActivityDefaultsToIndexedOrder(t *testing.T) {
+ w := httptest.NewRecorder()
+ sort, ok := testHandler.issueTableOrderBy(
+ w,
+ newRequest(http.MethodPost, "/api/issues/table/rows", nil),
+ testWorkspaceID,
+ issueTableSortRequest{Field: "last_activity"},
+ )
+ if !ok {
+ t.Fatalf("last_activity sort rejected: status=%d body=%s", w.Code, w.Body.String())
+ }
+ if got, want := sort.orderBy(), "i.last_activity_at DESC NULLS LAST, i.id DESC"; got != want {
+ t.Fatalf("orderBy = %q, want %q", got, want)
+ }
+
+ sortValue := "2026-08-19T05:04:03.123456Z"
+ cursor := issueTableCursor{
+ SortValue: &sortValue,
+ RowID: "00000000-0000-4000-8000-000000000001",
+ }
+ args := make([]any, 0, 2)
+ predicate, ok := sort.cursorPredicate(w, &cursor, func(value any) string {
+ args = append(args, value)
+ return fmt.Sprintf("$%d", len(args))
+ })
+ if !ok {
+ t.Fatalf("valid last_activity cursor rejected: status=%d body=%s", w.Code, w.Body.String())
+ }
+ if strings.Contains(predicate, "created_at") {
+ t.Fatalf("last_activity cursor unexpectedly uses created_at tie-break: %s", predicate)
+ }
+ if !strings.Contains(predicate, "i.id < $1::uuid") {
+ t.Fatalf("last_activity cursor is missing id tie-break: %s", predicate)
+ }
+}
+
func TestIssueTableGroupIdentityBindsIncludeEmpty(t *testing.T) {
withoutEmpty := issueTableGroupIdentity(issueTableGroupSpec{
Kind: "property",
diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.go
index db7b22a0d3..6bda9b8ab9 100644
--- a/server/internal/handler/issue_table_rows.go
+++ b/server/internal/handler/issue_table_rows.go
@@ -35,6 +35,7 @@ type resolvedIssueTableSort struct {
direction string
castType string
nullsLast bool
+ idOnlyTie bool
}
func (sort resolvedIssueTableSort) orderBy() string {
@@ -42,6 +43,9 @@ func (sort resolvedIssueTableSort) orderBy() string {
if sort.nullsLast {
orderBy += " NULLS LAST"
}
+ if sort.idOnlyTie {
+ return orderBy + ", i.id DESC"
+ }
return orderBy + ", i.created_at DESC, i.id DESC"
}
@@ -49,8 +53,7 @@ func (sort resolvedIssueTableSort) cursorPredicate(w http.ResponseWriter, cursor
if cursor == nil {
return "TRUE", true
}
- createdAt, err := time.Parse(time.RFC3339Nano, cursor.RowCreatedAt)
- if err != nil || cursor.RowID == "" {
+ if cursor.RowID == "" {
writeError(w, http.StatusBadRequest, "invalid cursor")
return "", false
}
@@ -59,9 +62,17 @@ func (sort resolvedIssueTableSort) cursorPredicate(w http.ResponseWriter, cursor
writeError(w, http.StatusBadRequest, "invalid cursor")
return "", false
}
- createdRef := addArg(createdAt)
idRef := addArg(rowID)
- tie := fmt.Sprintf("(i.created_at < %s::timestamptz OR (i.created_at = %s::timestamptz AND i.id < %s::uuid))", createdRef, createdRef, idRef)
+ tie := fmt.Sprintf("i.id < %s::uuid", idRef)
+ if !sort.idOnlyTie {
+ createdAt, err := time.Parse(time.RFC3339Nano, cursor.RowCreatedAt)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return "", false
+ }
+ createdRef := addArg(createdAt)
+ tie = fmt.Sprintf("(i.created_at < %s::timestamptz OR (i.created_at = %s::timestamptz AND i.id < %s::uuid))", createdRef, createdRef, idRef)
+ }
if cursor.SortIsNull {
if !sort.nullsLast || cursor.SortValue != nil {
writeError(w, http.StatusBadRequest, "invalid cursor")
@@ -134,6 +145,11 @@ func (h *Handler) issueTableOrderBy(w http.ResponseWriter, r *http.Request, work
case "created_at", "updated_at":
resolved.expression = "i." + sortField
resolved.castType = "timestamptz"
+ case "last_activity":
+ resolved.expression = "i.last_activity_at"
+ resolved.castType = "timestamptz"
+ resolved.nullsLast = true
+ resolved.idOnlyTie = true
case "start_date", "due_date":
resolved.expression = "i." + sortField
resolved.castType = "date"
@@ -172,6 +188,9 @@ func (h *Handler) issueTableOrderBy(w http.ResponseWriter, r *http.Request, work
direction := strings.ToLower(strings.TrimSpace(sortRequest.Direction))
if direction == "" {
direction = "asc"
+ if resolved.idOnlyTie {
+ direction = "desc"
+ }
}
if direction != "asc" && direction != "desc" {
writeError(w, http.StatusBadRequest, "invalid query.sort.direction")
@@ -349,7 +368,7 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at,
- i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.updated_at, i.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
i.revision,
%s AS direct_child_count, i.table_sort_key
FROM page i
@@ -388,6 +407,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
&row.issue.DueDate,
&row.issue.CreatedAt,
&row.issue.UpdatedAt,
+ &row.issue.LastActivityAt,
&row.issue.Number,
&row.issue.ProjectID,
&row.issue.Metadata,
diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.go
index 52ecfa6332..680555baf9 100644
--- a/server/internal/integrations/channel/engine/session_db_test.go
+++ b/server/internal/integrations/channel/engine/session_db_test.go
@@ -461,6 +461,10 @@ func TestMaterializeIssueChannelMediaMarkdownPreservesEditedDescription(t *testi
`, fixture.workspaceID, fixture.userID).Scan(&issueID); err != nil {
t.Fatalf("create issue: %v", err)
}
+ activityAt := time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)
+ if _, err := pool.Exec(ctx, `UPDATE issue SET last_activity_at = $2 WHERE id = $1`, issueID, activityAt); err != nil {
+ t.Fatalf("seed issue activity: %v", err)
+ }
const markdown = "![](/api/attachments/22222222-2222-4222-8222-222222222222/download)"
issue, err := db.New(pool).MaterializeIssueChannelMediaMarkdown(ctx, db.MaterializeIssueChannelMediaMarkdownParams{
@@ -477,6 +481,9 @@ func TestMaterializeIssueChannelMediaMarkdownPreservesEditedDescription(t *testi
if !issue.Description.Valid || issue.Description.String != want {
t.Fatalf("issue description = %#v, want %q", issue.Description, want)
}
+ if !issue.LastActivityAt.Valid || !issue.LastActivityAt.Time.Equal(activityAt) {
+ t.Fatalf("system media materialization changed activity: got=%v want=%s", issue.LastActivityAt, activityAt)
+ }
}
func TestMaterializeIssueChannelMediaMarkdownReplacesUnchangedBase(t *testing.T) {
diff --git a/server/internal/issueactivitybackfill/backfill.go b/server/internal/issueactivitybackfill/backfill.go
new file mode 100644
index 0000000000..71a81ebc1b
--- /dev/null
+++ b/server/internal/issueactivitybackfill/backfill.go
@@ -0,0 +1,84 @@
+// Package issueactivitybackfill provides bounded, resumable batches for
+// seeding issue.last_activity_at from the pre-existing updated_at history.
+package issueactivitybackfill
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+// DefaultBatchSize bounds each transaction and the number of issue rows it
+// locks. Operators can add a delay between calls from the command wrapper.
+const DefaultBatchSize = 1000
+
+// Options controls one backfill batch. Zero values are production defaults.
+type Options struct {
+ BatchSize int
+ // AfterID is the exclusive keyset watermark for the current pass.
+ AfterID *string
+ // Table is a trusted identifier override used only by tests.
+ Table string
+}
+
+// BatchResult advances a caller's keyset walk without rescanning completed
+// prefixes. LastID is empty only when the batch updated no rows.
+type BatchResult struct {
+ Rows int64
+ LastID string
+}
+
+// Batch copies updated_at into last_activity_at for at most BatchSize rows.
+// Rows already touched by a current writer no longer match the outer predicate,
+// so a concurrent semantic update always wins over historical reconstruction.
+func Batch(ctx context.Context, pool *pgxpool.Pool, opts Options) (BatchResult, error) {
+ batchSize := opts.BatchSize
+ if batchSize <= 0 {
+ batchSize = DefaultBatchSize
+ }
+ table := opts.Table
+ if table == "" {
+ table = "issue"
+ }
+
+ query := fmt.Sprintf(`
+WITH batch AS (
+ SELECT id
+ FROM %s
+ WHERE last_activity_at IS NULL
+ AND ($2::uuid IS NULL OR id > $2::uuid)
+ ORDER BY id
+ LIMIT $1
+ FOR UPDATE SKIP LOCKED
+), updated AS (
+UPDATE %s i
+SET last_activity_at = i.updated_at
+FROM batch
+WHERE i.id = batch.id
+ AND i.last_activity_at IS NULL
+ RETURNING i.id
+)
+SELECT COUNT(*)::bigint,
+ COALESCE((SELECT id::text FROM updated ORDER BY id DESC LIMIT 1), '')
+FROM updated`, table, table)
+ var result BatchResult
+ if err := pool.QueryRow(ctx, query, batchSize, opts.AfterID).Scan(&result.Rows, &result.LastID); err != nil {
+ return BatchResult{}, fmt.Errorf("backfill issue last_activity_at batch: %w", err)
+ }
+ return result, nil
+}
+
+// CountRemaining reports rows not yet reconstructed.
+func CountRemaining(ctx context.Context, pool *pgxpool.Pool, table string) (int64, error) {
+ if table == "" {
+ table = "issue"
+ }
+ var count int64
+ if err := pool.QueryRow(ctx, fmt.Sprintf(
+ "SELECT count(*) FROM %s WHERE last_activity_at IS NULL", table,
+ )).Scan(&count); err != nil {
+ return 0, fmt.Errorf("count issue last_activity_at backlog: %w", err)
+ }
+ return count, nil
+}
diff --git a/server/internal/issueactivitybackfill/backfill_test.go b/server/internal/issueactivitybackfill/backfill_test.go
new file mode 100644
index 0000000000..fcd2c95f01
--- /dev/null
+++ b/server/internal/issueactivitybackfill/backfill_test.go
@@ -0,0 +1,136 @@
+package issueactivitybackfill
+
+import (
+ "context"
+ "fmt"
+ "math/rand/v2"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func testPool(t *testing.T) *pgxpool.Pool {
+ t.Helper()
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+ pool, err := pgxpool.New(context.Background(), dbURL)
+ if err != nil {
+ t.Skipf("connect to database: %v", err)
+ }
+ if err := pool.Ping(context.Background()); err != nil {
+ pool.Close()
+ t.Skipf("database not reachable: %v", err)
+ }
+ return pool
+}
+
+func fixture(t *testing.T, pool *pgxpool.Pool) string {
+ t.Helper()
+ schema := fmt.Sprintf("issue_activity_backfill_%d_%d", time.Now().UnixNano(), rand.IntN(1_000_000))
+ if _, err := pool.Exec(context.Background(), fmt.Sprintf(`CREATE SCHEMA %q`, schema)); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), fmt.Sprintf(`DROP SCHEMA %q CASCADE`, schema))
+ })
+ table := fmt.Sprintf("%q.issue", schema)
+ if _, err := pool.Exec(context.Background(), fmt.Sprintf(`
+CREATE TABLE %s (
+ id UUID PRIMARY KEY,
+ updated_at TIMESTAMPTZ NOT NULL,
+ last_activity_at TIMESTAMPTZ
+)`, table)); err != nil {
+ t.Fatalf("create fixture: %v", err)
+ }
+ return table
+}
+
+func TestBatchIsBoundedAndResumable(t *testing.T) {
+ pool := testPool(t)
+ defer pool.Close()
+ ctx := context.Background()
+ table := fixture(t, pool)
+ if _, err := pool.Exec(ctx, fmt.Sprintf(`
+INSERT INTO %s (id, updated_at, last_activity_at) VALUES
+('00000000-0000-0000-0000-000000000001', '2026-01-01T00:00:00Z', NULL),
+('00000000-0000-0000-0000-000000000002', '2026-01-02T00:00:00Z', NULL),
+('00000000-0000-0000-0000-000000000003', '2026-01-03T00:00:00Z', '2026-02-01T00:00:00Z')`, table)); err != nil {
+ t.Fatalf("seed fixture: %v", err)
+ }
+
+ first, err := Batch(ctx, pool, Options{BatchSize: 1, Table: table})
+ if err != nil || first.Rows != 1 || first.LastID != "00000000-0000-0000-0000-000000000001" {
+ t.Fatalf("first Batch = (%+v, %v), want one row ending at id 1", first, err)
+ }
+ remaining, err := CountRemaining(ctx, pool, table)
+ if err != nil || remaining != 1 {
+ t.Fatalf("CountRemaining = (%d, %v), want (1, nil)", remaining, err)
+ }
+ second, err := Batch(ctx, pool, Options{BatchSize: 10, AfterID: &first.LastID, Table: table})
+ if err != nil || second.Rows != 1 || second.LastID != "00000000-0000-0000-0000-000000000002" {
+ t.Fatalf("second Batch = (%+v, %v), want one row ending at id 2", second, err)
+ }
+ idempotent, err := Batch(ctx, pool, Options{BatchSize: 10, AfterID: &second.LastID, Table: table})
+ if err != nil || idempotent.Rows != 0 || idempotent.LastID != "" {
+ t.Fatalf("idempotent Batch = (%+v, %v), want empty result", idempotent, err)
+ }
+
+ var preserved time.Time
+ if err := pool.QueryRow(ctx, fmt.Sprintf(`
+SELECT last_activity_at FROM %s WHERE id = '00000000-0000-0000-0000-000000000003'`, table)).Scan(&preserved); err != nil {
+ t.Fatalf("read pre-populated row: %v", err)
+ }
+ if want := time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC); !preserved.Equal(want) {
+ t.Fatalf("pre-populated activity changed to %s, want %s", preserved, want)
+ }
+}
+
+func TestBatchWrapsToRecoverRowsSkippedByLock(t *testing.T) {
+ pool := testPool(t)
+ defer pool.Close()
+ ctx := context.Background()
+ table := fixture(t, pool)
+ if _, err := pool.Exec(ctx, fmt.Sprintf(`
+INSERT INTO %s (id, updated_at, last_activity_at) VALUES
+('00000000-0000-0000-0000-000000000001', '2026-01-01T00:00:00Z', NULL),
+('00000000-0000-0000-0000-000000000002', '2026-01-02T00:00:00Z', NULL),
+('00000000-0000-0000-0000-000000000003', '2026-01-03T00:00:00Z', NULL)`, table)); err != nil {
+ t.Fatalf("seed fixture: %v", err)
+ }
+
+ lockTx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin lock transaction: %v", err)
+ }
+ if _, err := lockTx.Exec(ctx, fmt.Sprintf(`
+SELECT id FROM %s WHERE id = '00000000-0000-0000-0000-000000000001' FOR UPDATE`, table)); err != nil {
+ _ = lockTx.Rollback(ctx)
+ t.Fatalf("lock first row: %v", err)
+ }
+
+ first, err := Batch(ctx, pool, Options{BatchSize: 2, Table: table})
+ if err != nil || first.Rows != 2 || first.LastID != "00000000-0000-0000-0000-000000000003" {
+ _ = lockTx.Rollback(ctx)
+ t.Fatalf("locked-row Batch = (%+v, %v), want ids 2-3", first, err)
+ }
+ if err := lockTx.Rollback(ctx); err != nil {
+ t.Fatalf("release first row: %v", err)
+ }
+
+ endOfPass, err := Batch(ctx, pool, Options{BatchSize: 2, AfterID: &first.LastID, Table: table})
+ if err != nil || endOfPass.Rows != 0 {
+ t.Fatalf("end-of-pass Batch = (%+v, %v), want empty result", endOfPass, err)
+ }
+ remaining, err := CountRemaining(ctx, pool, table)
+ if err != nil || remaining != 1 {
+ t.Fatalf("CountRemaining = (%d, %v), want skipped row", remaining, err)
+ }
+ recovered, err := Batch(ctx, pool, Options{BatchSize: 2, Table: table})
+ if err != nil || recovered.Rows != 1 || recovered.LastID != "00000000-0000-0000-0000-000000000001" {
+ t.Fatalf("wrapped Batch = (%+v, %v), want recovered id 1", recovered, err)
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index a58545dbd9..628eb2582e 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -6142,23 +6142,24 @@ func IssueToMap(issue db.Issue, issuePrefix string) map[string]any {
// Mirrors handler.IssueResponse.StatusCategory: a built-in status IS
// its own category, so this resolves with no catalog lookup. Empty for
// a custom status, which consumers resolve via the catalog. (MUL-6243)
- "status_category": builtInStatusCategory(issue.Status),
- "priority": issue.Priority,
- "assignee_type": util.TextToPtr(issue.AssigneeType),
- "assignee_id": util.UUIDToPtr(issue.AssigneeID),
- "creator_type": issue.CreatorType,
- "creator_id": util.UUIDToString(issue.CreatorID),
- "parent_issue_id": util.UUIDToPtr(issue.ParentIssueID),
- "project_id": util.UUIDToPtr(issue.ProjectID),
- "position": issue.Position,
- "stage": util.Int4ToPtr(issue.Stage),
- "start_date": util.DateToPtr(issue.StartDate),
- "due_date": util.DateToPtr(issue.DueDate),
- "created_at": util.TimestampToString(issue.CreatedAt),
- "updated_at": util.TimestampToString(issue.UpdatedAt),
- "revision": issue.Revision,
- "metadata": util.JSONObjectOrEmpty(issue.Metadata),
- "properties": util.JSONObjectOrEmpty(issue.Properties),
+ "status_category": builtInStatusCategory(issue.Status),
+ "priority": issue.Priority,
+ "assignee_type": util.TextToPtr(issue.AssigneeType),
+ "assignee_id": util.UUIDToPtr(issue.AssigneeID),
+ "creator_type": issue.CreatorType,
+ "creator_id": util.UUIDToString(issue.CreatorID),
+ "parent_issue_id": util.UUIDToPtr(issue.ParentIssueID),
+ "project_id": util.UUIDToPtr(issue.ProjectID),
+ "position": issue.Position,
+ "stage": util.Int4ToPtr(issue.Stage),
+ "start_date": util.DateToPtr(issue.StartDate),
+ "due_date": util.DateToPtr(issue.DueDate),
+ "created_at": util.TimestampToString(issue.CreatedAt),
+ "updated_at": util.TimestampToString(issue.UpdatedAt),
+ "last_activity_at": util.TimestampToNanoPtr(issue.LastActivityAt),
+ "revision": issue.Revision,
+ "metadata": util.JSONObjectOrEmpty(issue.Metadata),
+ "properties": util.JSONObjectOrEmpty(issue.Properties),
}
}
diff --git a/server/internal/util/pgx.go b/server/internal/util/pgx.go
index 5b344067c6..98bc8ca831 100644
--- a/server/internal/util/pgx.go
+++ b/server/internal/util/pgx.go
@@ -92,6 +92,17 @@ func TimestampToPtr(t pgtype.Timestamptz) *string {
return &s
}
+// TimestampToNanoPtr preserves PostgreSQL's sub-second precision. New ordering
+// and cursor fields should use this instead of the legacy second-precision
+// TimestampToPtr so two activities in the same second remain distinguishable.
+func TimestampToNanoPtr(t pgtype.Timestamptz) *string {
+ if !t.Valid {
+ return nil
+ }
+ s := t.Time.Format(time.RFC3339Nano)
+ return &s
+}
+
// DateToPtr formats a pgtype.Date as a date-only "YYYY-MM-DD" string, or nil
// when unset. Issue start_date/due_date are calendar days with no time-of-day
// or timezone, so they must never be rendered through an instant.
diff --git a/server/internal/util/pgx_test.go b/server/internal/util/pgx_test.go
index f89c0d1699..a28d51c0d3 100644
--- a/server/internal/util/pgx_test.go
+++ b/server/internal/util/pgx_test.go
@@ -114,3 +114,17 @@ func TestDateToPtr_StableAcrossTimezone(t *testing.T) {
t.Fatalf("got %v want 2026-03-01", got)
}
}
+
+func TestTimestampToNanoPtrPreservesSubSecondPrecision(t *testing.T) {
+ value := pgtype.Timestamptz{
+ Time: time.Date(2026, time.August, 19, 5, 4, 3, 123456000, time.UTC),
+ Valid: true,
+ }
+ got := TimestampToNanoPtr(value)
+ if got == nil || *got != "2026-08-19T05:04:03.123456Z" {
+ t.Fatalf("TimestampToNanoPtr = %v, want microsecond-precise RFC3339", got)
+ }
+ if got := TimestampToNanoPtr(pgtype.Timestamptz{}); got != nil {
+ t.Fatalf("TimestampToNanoPtr invalid = %v, want nil", got)
+ }
+}
diff --git a/server/migrations/360_issue_last_activity_at.down.sql b/server/migrations/360_issue_last_activity_at.down.sql
new file mode 100644
index 0000000000..efd1338f04
--- /dev/null
+++ b/server/migrations/360_issue_last_activity_at.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE issue
+ DROP COLUMN IF EXISTS last_activity_at;
diff --git a/server/migrations/360_issue_last_activity_at.up.sql b/server/migrations/360_issue_last_activity_at.up.sql
new file mode 100644
index 0000000000..af41c3e027
--- /dev/null
+++ b/server/migrations/360_issue_last_activity_at.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE issue
+ ADD COLUMN IF NOT EXISTS last_activity_at TIMESTAMPTZ;
diff --git a/server/migrations/361_issue_last_activity_index.down.sql b/server/migrations/361_issue_last_activity_index.down.sql
new file mode 100644
index 0000000000..ffc13ef3a1
--- /dev/null
+++ b/server/migrations/361_issue_last_activity_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_workspace_last_activity;
diff --git a/server/migrations/361_issue_last_activity_index.up.sql b/server/migrations/361_issue_last_activity_index.up.sql
new file mode 100644
index 0000000000..995ff4fb03
--- /dev/null
+++ b/server/migrations/361_issue_last_activity_index.up.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_last_activity
+ ON issue (workspace_id, last_activity_at DESC NULLS LAST, id DESC);
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index f41f9f69a2..3dbb1c4e6c 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -199,7 +199,10 @@ func (q *Queries) CountNewCommentsSince(ctx context.Context, arg CountNewComment
const createComment = `-- name: CreateComment :one
WITH touched_issue AS (
- UPDATE issue SET updated_at = now(), revision = revision + 1
+ UPDATE issue SET
+ updated_at = now(),
+ revision = revision + 1,
+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
WHERE issue.id = $1 AND issue.workspace_id = $2
RETURNING issue.id, issue.workspace_id, issue.revision
), inserted_comment AS (
@@ -248,7 +251,7 @@ type CreateCommentRow struct {
}
// A new comment counts as activity on its issue, so the same statement bumps
-// the parent issue's updated_at. The touch is a leading data-modifying CTE and
+// the parent issue's updated_at and last_activity_at. The touch is a leading data-modifying CTE and
// the INSERT selects the issue/workspace back out of it, which makes the two
// inseparable and gives two query-level guarantees:
// - atomicity — the insert and the timestamp bump commit or roll back
@@ -300,8 +303,38 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C
return i, err
}
-const deleteComment = `-- name: DeleteComment :exec
-DELETE FROM comment WHERE id = $1 AND workspace_id = $2
+const deleteComment = `-- name: DeleteComment :one
+WITH locked_issue AS MATERIALIZED (
+ -- Lock the aggregate owner before its child so this cannot deadlock with
+ -- issue teardown (which takes the same issue -> comment order).
+ SELECT issue.id
+ FROM issue
+ JOIN comment ON comment.issue_id = issue.id
+ AND comment.workspace_id = issue.workspace_id
+ WHERE comment.id = $1 AND comment.workspace_id = $2
+ FOR UPDATE OF issue
+), issue_fence AS MATERIALIZED (
+ -- The consumed locked_count below is the ordering fence: the issue lock is
+ -- acquired before DELETE can lock the comment. MATERIALIZED only prevents
+ -- folding/re-evaluation and is not, by itself, a lock-order guarantee.
+ SELECT count(*) AS locked_count FROM locked_issue
+), deleted_comment AS (
+ DELETE FROM comment
+ USING issue_fence
+ WHERE comment.id = $1 AND comment.workspace_id = $2
+ AND issue_fence.locked_count >= 0
+ RETURNING issue_id, workspace_id
+), touched_issue AS (
+ UPDATE issue
+ SET revision = issue.revision + 1,
+ last_activity_at = GREATEST(COALESCE(issue.last_activity_at, issue.updated_at), now())
+ FROM deleted_comment
+ WHERE issue.id = deleted_comment.issue_id
+ AND issue.workspace_id = deleted_comment.workspace_id
+ RETURNING issue.id, issue.revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted_comment) AS changed,
+ COALESCE((SELECT revision FROM touched_issue), 0)::bigint AS issue_revision
`
type DeleteCommentParams struct {
@@ -309,10 +342,17 @@ type DeleteCommentParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
}
+type DeleteCommentRow struct {
+ Changed bool `json:"changed"`
+ IssueRevision int64 `json:"issue_revision"`
+}
+
// Defense-in-depth: workspace_id is a SQL-layer tenant guard. See DeleteIssue.
-func (q *Queries) DeleteComment(ctx context.Context, arg DeleteCommentParams) error {
- _, err := q.db.Exec(ctx, deleteComment, arg.ID, arg.WorkspaceID)
- return err
+func (q *Queries) DeleteComment(ctx context.Context, arg DeleteCommentParams) (DeleteCommentRow, error) {
+ row := q.db.QueryRow(ctx, deleteComment, arg.ID, arg.WorkspaceID)
+ var i DeleteCommentRow
+ err := row.Scan(&i.Changed, &i.IssueRevision)
+ return i, err
}
const getComment = `-- name: GetComment :one
@@ -1589,19 +1629,70 @@ func (q *Queries) UnresolveComment(ctx context.Context, id pgtype.UUID) (Comment
}
const updateComment = `-- name: UpdateComment :one
-UPDATE comment SET
- content = $2,
- source_task_id = $3,
- revision = revision + CASE WHEN ROW(content, source_task_id) IS DISTINCT FROM ROW($2, $3) THEN 1 ELSE 0 END,
- updated_at = CASE WHEN ROW(content, source_task_id) IS DISTINCT FROM ROW($2, $3) THEN now() ELSE updated_at END
-WHERE id = $1
- AND ($4::bigint IS NULL OR revision = $4::bigint)
- AND (
- $5::text IS NULL
- OR content IS NOT DISTINCT FROM $5::text
- OR content IS NOT DISTINCT FROM $2
- )
-RETURNING 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, via_plugin_id, revision
+WITH locked_issue AS MATERIALIZED (
+ -- Keep the global issue -> child lock order used by issue teardown. The
+ -- aggregate below still yields one row when the parent was concurrently
+ -- deleted, preserving best-effort edits of an orphaned comment.
+ SELECT issue.id
+ FROM issue
+ JOIN comment ON comment.issue_id = issue.id
+ AND comment.workspace_id = issue.workspace_id
+ WHERE comment.id = $1
+ FOR UPDATE OF issue
+), issue_fence AS MATERIALIZED (
+ -- The aggregate always emits one row. Consuming locked_count in target's
+ -- tautological predicate creates a real data dependency: locked_issue must
+ -- acquire the owner lock before target can lock the comment. MATERIALIZED
+ -- prevents folding/re-evaluation; it does not itself establish lock order.
+ SELECT count(*) AS locked_count FROM locked_issue
+), target AS MATERIALIZED (
+ SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision,
+ ROW(comment.content, comment.source_task_id) IS DISTINCT FROM
+ ROW($2, $3::uuid) AS did_change
+ FROM comment
+ CROSS JOIN issue_fence
+ WHERE comment.id = $1
+ AND issue_fence.locked_count >= 0
+ AND ($4::bigint IS NULL OR revision = $4::bigint)
+ AND (
+ $5::text IS NULL
+ OR content IS NOT DISTINCT FROM $5::text
+ OR content IS NOT DISTINCT FROM $2
+ )
+ FOR UPDATE OF comment
+), updated_comment AS (
+ UPDATE comment SET
+ content = $2,
+ source_task_id = $3::uuid,
+ revision = comment.revision + CASE WHEN target.did_change THEN 1 ELSE 0 END,
+ updated_at = CASE WHEN target.did_change THEN now() ELSE comment.updated_at END
+ FROM target
+ WHERE comment.id = target.id
+ RETURNING comment.id, comment.issue_id, comment.author_type, comment.author_id,
+ comment.content, comment.type, comment.created_at, comment.updated_at,
+ comment.parent_id, comment.workspace_id, comment.resolved_at,
+ comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id,
+ comment.quick_action_id, comment.via_plugin_id, comment.revision,
+ target.did_change
+), touched_issue AS (
+ UPDATE issue
+ SET revision = issue.revision + 1,
+ last_activity_at = GREATEST(COALESCE(issue.last_activity_at, issue.updated_at), now())
+ FROM updated_comment
+ WHERE updated_comment.did_change
+ AND issue.id = updated_comment.issue_id
+ AND issue.workspace_id = updated_comment.workspace_id
+ RETURNING issue.id, issue.revision
+)
+SELECT updated_comment.id, updated_comment.issue_id, updated_comment.author_type,
+ updated_comment.author_id, updated_comment.content, updated_comment.type,
+ updated_comment.created_at, updated_comment.updated_at, updated_comment.parent_id,
+ updated_comment.workspace_id, updated_comment.resolved_at,
+ updated_comment.resolved_by_type, updated_comment.resolved_by_id,
+ updated_comment.source_task_id, updated_comment.quick_action_id,
+ updated_comment.via_plugin_id, updated_comment.revision,
+ COALESCE((SELECT revision FROM touched_issue), 0)::bigint AS issue_revision
+FROM updated_comment
`
type UpdateCommentParams struct {
@@ -1612,7 +1703,28 @@ type UpdateCommentParams struct {
ContentBase pgtype.Text `json:"content_base"`
}
-func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (Comment, error) {
+type UpdateCommentRow 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"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`
+ Revision int64 `json:"revision"`
+ IssueRevision int64 `json:"issue_revision"`
+}
+
+func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (UpdateCommentRow, error) {
row := q.db.QueryRow(ctx, updateComment,
arg.ID,
arg.Content,
@@ -1620,7 +1732,7 @@ func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (C
arg.ExpectedRevision,
arg.ContentBase,
)
- var i Comment
+ var i UpdateCommentRow
err := row.Scan(
&i.ID,
&i.IssueID,
@@ -1639,6 +1751,7 @@ func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (C
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.IssueRevision,
)
return i, err
}
diff --git a/server/pkg/db/generated/comment_row.go b/server/pkg/db/generated/comment_row.go
index f8d0adc125..d534143643 100644
--- a/server/pkg/db/generated/comment_row.go
+++ b/server/pkg/db/generated/comment_row.go
@@ -24,3 +24,28 @@ func (r CreateCommentRow) Comment() Comment {
Revision: r.Revision,
}
}
+
+// Comment converts the sqlc row returned by the CTE-backed update query into
+// the canonical model. IssueRevision is aggregate-owner metadata and remains
+// available on the row for response/event cache reconciliation.
+func (r UpdateCommentRow) Comment() Comment {
+ return Comment{
+ ID: r.ID,
+ IssueID: r.IssueID,
+ AuthorType: r.AuthorType,
+ AuthorID: r.AuthorID,
+ 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,
+ ViaPluginID: r.ViaPluginID,
+ Revision: r.Revision,
+ }
+}
diff --git a/server/pkg/db/generated/comment_row_test.go b/server/pkg/db/generated/comment_row_test.go
index c54e15a640..890eee7d57 100644
--- a/server/pkg/db/generated/comment_row_test.go
+++ b/server/pkg/db/generated/comment_row_test.go
@@ -26,3 +26,21 @@ func TestCreateCommentRowCommentPreservesCanonicalFields(t *testing.T) {
t.Fatalf("via_plugin_id = %#v, want %#v", comment.ViaPluginID, viaPluginID)
}
}
+
+func TestUpdateCommentRowCommentPreservesCanonicalFields(t *testing.T) {
+ viaPluginID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}
+ row := UpdateCommentRow{
+ Content: "updated comment",
+ Revision: 8,
+ ViaPluginID: viaPluginID,
+ IssueRevision: 12,
+ }
+
+ comment := row.Comment()
+ if comment.Content != row.Content || comment.Revision != row.Revision {
+ t.Fatalf("comment = (%q, %d), want (%q, %d)", comment.Content, comment.Revision, row.Content, row.Revision)
+ }
+ if comment.ViaPluginID != viaPluginID {
+ t.Fatalf("via_plugin_id = %#v, want %#v", comment.ViaPluginID, viaPluginID)
+ }
+}
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 9bd9685542..f7fbcc9cb7 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -175,11 +175,11 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- stage
+ stage, last_activity_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- $16
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
+ $16, now()
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
type CreateIssueParams struct {
@@ -249,6 +249,7 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
@@ -258,11 +259,11 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- origin_type, origin_id, stage
+ origin_type, origin_id, stage, last_activity_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- $16, $17, $18
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
+ $16, $17, $18, now()
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
type CreateIssueWithOriginParams struct {
@@ -336,6 +337,7 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
@@ -380,9 +382,14 @@ const deleteIssueMetadataKey = `-- name: DeleteIssueMetadataKey :one
UPDATE issue SET
metadata = metadata - $1::text,
revision = revision + CASE WHEN metadata ? $1::text THEN 1 ELSE 0 END,
+ last_activity_at = CASE
+ WHEN metadata ? $1::text
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = now()
WHERE id = $2 AND workspace_id = $3
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
type DeleteIssueMetadataKeyParams struct {
@@ -424,12 +431,13 @@ func (q *Queries) DeleteIssueMetadataKey(ctx context.Context, arg DeleteIssueMet
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
const findActiveDuplicateIssue = `-- name: FindActiveDuplicateIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue
WHERE workspace_id = $1
AND issue_effective_status(workspace_id, status) NOT IN ('done', 'cancelled')
AND project_id IS NOT DISTINCT FROM $2::uuid
@@ -482,12 +490,13 @@ func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDu
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
const findRecentAutopilotDuplicateIssue = `-- name: FindRecentAutopilotDuplicateIssue :one
-SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision FROM issue i
+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at FROM issue i
WHERE i.workspace_id = $1
AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')
AND i.origin_type = 'autopilot'
@@ -551,12 +560,13 @@ func (q *Queries) FindRecentAutopilotDuplicateIssue(ctx context.Context, arg Fin
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
const getIssue = `-- name: GetIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue
WHERE id = $1
`
@@ -591,12 +601,13 @@ func (q *Queries) GetIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
const getIssueByNumber = `-- name: GetIssueByNumber :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue
WHERE workspace_id = $1 AND number = $2
`
@@ -636,12 +647,13 @@ func (q *Queries) GetIssueByNumber(ctx context.Context, arg GetIssueByNumberPara
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
const getIssueByOrigin = `-- name: GetIssueByOrigin :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue
WHERE workspace_id = $1
AND origin_type = $2
AND origin_id = $3
@@ -690,6 +702,7 @@ func (q *Queries) GetIssueByOrigin(ctx context.Context, arg GetIssueByOriginPara
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
@@ -714,7 +727,7 @@ func (q *Queries) GetIssueGCStatus(ctx context.Context, id pgtype.UUID) (GetIssu
}
const getIssueInWorkspace = `-- name: GetIssueInWorkspace :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue
WHERE id = $1 AND workspace_id = $2
`
@@ -754,12 +767,13 @@ func (q *Queries) GetIssueInWorkspace(ctx context.Context, arg GetIssueInWorkspa
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
const listChildIssues = `-- name: ListChildIssues :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue
WHERE parent_issue_id = $1
ORDER BY number ASC
`
@@ -807,6 +821,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
); err != nil {
return nil, err
}
@@ -819,7 +834,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID
}
const listChildrenByParents = `-- name: ListChildrenByParents :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue
WHERE workspace_id = $1
AND parent_issue_id = ANY($2::uuid[])
ORDER BY parent_issue_id, number ASC
@@ -874,6 +889,7 @@ func (q *Queries) ListChildrenByParents(ctx context.Context, arg ListChildrenByP
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
); err != nil {
return nil, err
}
@@ -926,7 +942,7 @@ func (q *Queries) ListIssueGCStatuses(ctx context.Context, arg ListIssueGCStatus
const listIssues = `-- name: ListIssues :many
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
i.revision
FROM issue i
WHERE i.workspace_id = $1
@@ -998,28 +1014,29 @@ type ListIssuesParams struct {
}
type ListIssuesRow struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Title string `json:"title"`
- Description pgtype.Text `json:"description"`
- Status string `json:"status"`
- Priority string `json:"priority"`
- AssigneeType pgtype.Text `json:"assignee_type"`
- AssigneeID pgtype.UUID `json:"assignee_id"`
- CreatorType string `json:"creator_type"`
- CreatorID pgtype.UUID `json:"creator_id"`
- ParentIssueID pgtype.UUID `json:"parent_issue_id"`
- Position float64 `json:"position"`
- StartDate pgtype.Date `json:"start_date"`
- DueDate pgtype.Date `json:"due_date"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- Number int32 `json:"number"`
- ProjectID pgtype.UUID `json:"project_id"`
- Metadata []byte `json:"metadata"`
- Stage pgtype.Int4 `json:"stage"`
- Properties []byte `json:"properties"`
- Revision int64 `json:"revision"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Title string `json:"title"`
+ Description pgtype.Text `json:"description"`
+ Status string `json:"status"`
+ Priority string `json:"priority"`
+ AssigneeType pgtype.Text `json:"assignee_type"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ CreatorType string `json:"creator_type"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`
+ Position float64 `json:"position"`
+ StartDate pgtype.Date `json:"start_date"`
+ DueDate pgtype.Date `json:"due_date"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
+ Number int32 `json:"number"`
+ ProjectID pgtype.UUID `json:"project_id"`
+ Metadata []byte `json:"metadata"`
+ Stage pgtype.Int4 `json:"stage"`
+ Properties []byte `json:"properties"`
+ Revision int64 `json:"revision"`
}
// involves_user_id widens the assignee filter to surface issues where the user
@@ -1067,6 +1084,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListI
&i.DueDate,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.LastActivityAt,
&i.Number,
&i.ProjectID,
&i.Metadata,
@@ -1087,7 +1105,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListI
const listOpenIssues = `-- name: ListOpenIssues :many
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
i.revision
FROM issue i
WHERE i.workspace_id = $1
@@ -1163,28 +1181,29 @@ type ListOpenIssuesParams struct {
}
type ListOpenIssuesRow struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Title string `json:"title"`
- Description pgtype.Text `json:"description"`
- Status string `json:"status"`
- Priority string `json:"priority"`
- AssigneeType pgtype.Text `json:"assignee_type"`
- AssigneeID pgtype.UUID `json:"assignee_id"`
- CreatorType string `json:"creator_type"`
- CreatorID pgtype.UUID `json:"creator_id"`
- ParentIssueID pgtype.UUID `json:"parent_issue_id"`
- Position float64 `json:"position"`
- StartDate pgtype.Date `json:"start_date"`
- DueDate pgtype.Date `json:"due_date"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- Number int32 `json:"number"`
- ProjectID pgtype.UUID `json:"project_id"`
- Metadata []byte `json:"metadata"`
- Stage pgtype.Int4 `json:"stage"`
- Properties []byte `json:"properties"`
- Revision int64 `json:"revision"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Title string `json:"title"`
+ Description pgtype.Text `json:"description"`
+ Status string `json:"status"`
+ Priority string `json:"priority"`
+ AssigneeType pgtype.Text `json:"assignee_type"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ CreatorType string `json:"creator_type"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`
+ Position float64 `json:"position"`
+ StartDate pgtype.Date `json:"start_date"`
+ DueDate pgtype.Date `json:"due_date"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
+ Number int32 `json:"number"`
+ ProjectID pgtype.UUID `json:"project_id"`
+ Metadata []byte `json:"metadata"`
+ Stage pgtype.Int4 `json:"stage"`
+ Properties []byte `json:"properties"`
+ Revision int64 `json:"revision"`
}
// See ListIssues for the semantics of involves_user_id (mirrors the 4-branch
@@ -1225,6 +1244,7 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)
&i.DueDate,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.LastActivityAt,
&i.Number,
&i.ProjectID,
&i.Metadata,
@@ -1295,7 +1315,7 @@ func (q *Queries) LockIssueForDelete(ctx context.Context, arg LockIssueForDelete
}
const lockIssueForDescriptionUpdate = `-- name: LockIssueForDescriptionUpdate :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue
WHERE id = $1 AND workspace_id = $2
FOR UPDATE
`
@@ -1340,6 +1360,7 @@ func (q *Queries) LockIssueForDescriptionUpdate(ctx context.Context, arg LockIss
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
@@ -1389,7 +1410,7 @@ SET description = CASE
updated_at = now()
WHERE id = $4
AND workspace_id = $5
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
type MaterializeIssueChannelMediaMarkdownParams struct {
@@ -1405,6 +1426,8 @@ type MaterializeIssueChannelMediaMarkdownParams struct {
// with the fully composed Markdown so rich-text ordering survives. If a user
// edited concurrently (or the adapter has no inline layout), append instead;
// preserving user-authored bytes takes precedence over layout fidelity.
+// This is asynchronous system materialization, not a new user action, so it
+// intentionally preserves last_activity_at while still advancing revision.
func (q *Queries) MaterializeIssueChannelMediaMarkdown(ctx context.Context, arg MaterializeIssueChannelMediaMarkdownParams) (Issue, error) {
row := q.db.QueryRow(ctx, materializeIssueChannelMediaMarkdown,
arg.BaseDescription,
@@ -1442,6 +1465,7 @@ func (q *Queries) MaterializeIssueChannelMediaMarkdown(ctx context.Context, arg
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
@@ -1451,9 +1475,14 @@ const setIssueMetadataKey = `-- name: SetIssueMetadataKey :one
UPDATE issue SET
metadata = jsonb_set(metadata, ARRAY[$1::text], $2::jsonb),
revision = revision + CASE WHEN metadata -> $1::text IS DISTINCT FROM $2::jsonb THEN 1 ELSE 0 END,
+ last_activity_at = CASE
+ WHEN metadata -> $1::text IS DISTINCT FROM $2::jsonb
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = now()
WHERE id = $3 AND workspace_id = $4
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
type SetIssueMetadataKeyParams struct {
@@ -1503,6 +1532,7 @@ func (q *Queries) SetIssueMetadataKey(ctx context.Context, arg SetIssueMetadataK
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
@@ -1510,7 +1540,7 @@ func (q *Queries) SetIssueMetadataKey(ctx context.Context, arg SetIssueMetadataK
const updateIssue = `-- name: UpdateIssue :one
WITH candidate AS (
SELECT
- i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision,
+ i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at,
COALESCE($2::text, i.title) AS next_title,
COALESCE($3::text, i.description) AS next_description,
COALESCE($4::text, i.status) AS next_status,
@@ -1528,7 +1558,7 @@ WITH candidate AS (
AND ($14::bigint IS NULL OR i.revision = $14::bigint)
), changed AS (
SELECT
- candidate.id, candidate.workspace_id, candidate.title, candidate.description, candidate.status, candidate.priority, candidate.assignee_type, candidate.assignee_id, candidate.creator_type, candidate.creator_id, candidate.parent_issue_id, candidate.acceptance_criteria, candidate.context_refs, candidate.position, candidate.due_date, candidate.created_at, candidate.updated_at, candidate.number, candidate.project_id, candidate.origin_type, candidate.origin_id, candidate.first_executed_at, candidate.start_date, candidate.metadata, candidate.stage, candidate.properties, candidate.revision, candidate.next_title, candidate.next_description, candidate.next_status, candidate.next_priority, candidate.next_assignee_type, candidate.next_assignee_id, candidate.next_position, candidate.next_start_date, candidate.next_due_date, candidate.next_parent_issue_id, candidate.next_project_id, candidate.next_stage,
+ candidate.id, candidate.workspace_id, candidate.title, candidate.description, candidate.status, candidate.priority, candidate.assignee_type, candidate.assignee_id, candidate.creator_type, candidate.creator_id, candidate.parent_issue_id, candidate.acceptance_criteria, candidate.context_refs, candidate.position, candidate.due_date, candidate.created_at, candidate.updated_at, candidate.number, candidate.project_id, candidate.origin_type, candidate.origin_id, candidate.first_executed_at, candidate.start_date, candidate.metadata, candidate.stage, candidate.properties, candidate.revision, candidate.last_activity_at, candidate.next_title, candidate.next_description, candidate.next_status, candidate.next_priority, candidate.next_assignee_type, candidate.next_assignee_id, candidate.next_position, candidate.next_start_date, candidate.next_due_date, candidate.next_parent_issue_id, candidate.next_project_id, candidate.next_stage,
ROW(
title, description, status, priority, assignee_type, assignee_id,
position, start_date, due_date, parent_issue_id, project_id, stage
@@ -1536,7 +1566,15 @@ WITH candidate AS (
next_title, next_description, next_status, next_priority,
next_assignee_type, next_assignee_id, next_position, next_start_date,
next_due_date, next_parent_issue_id, next_project_id, next_stage
- ) AS did_change
+ ) AS did_change,
+ ROW(
+ title, description, status, priority, assignee_type, assignee_id,
+ start_date, due_date, parent_issue_id, project_id, stage
+ ) IS DISTINCT FROM ROW(
+ next_title, next_description, next_status, next_priority,
+ next_assignee_type, next_assignee_id, next_start_date, next_due_date,
+ next_parent_issue_id, next_project_id, next_stage
+ ) AS did_activity
FROM candidate
)
UPDATE issue AS i SET
@@ -1553,10 +1591,14 @@ UPDATE issue AS i SET
project_id = changed.next_project_id,
stage = changed.next_stage,
revision = i.revision + changed.did_change::integer,
+ last_activity_at = CASE WHEN changed.did_activity
+ THEN GREATEST(COALESCE(i.last_activity_at, i.updated_at), now())
+ ELSE i.last_activity_at
+ END,
updated_at = CASE WHEN changed.did_change THEN now() ELSE i.updated_at END
FROM changed
WHERE i.id = changed.id
-RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision
+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at
`
type UpdateIssueParams struct {
@@ -1622,6 +1664,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
@@ -1630,9 +1673,13 @@ const updateIssueStatus = `-- name: UpdateIssueStatus :one
UPDATE issue SET
status = $2,
revision = revision + CASE WHEN status IS DISTINCT FROM $2 THEN 1 ELSE 0 END,
+ last_activity_at = CASE WHEN status IS DISTINCT FROM $2
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = now()
WHERE id = $1 AND workspace_id = $3
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
type UpdateIssueStatusParams struct {
@@ -1673,6 +1720,7 @@ func (q *Queries) UpdateIssueStatus(ctx context.Context, arg UpdateIssueStatusPa
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/issue_label.sql.go b/server/pkg/db/generated/issue_label.sql.go
index d04d3d640e..dd75801c82 100644
--- a/server/pkg/db/generated/issue_label.sql.go
+++ b/server/pkg/db/generated/issue_label.sql.go
@@ -58,7 +58,8 @@ WITH inserted AS (
RETURNING issue_id
), bumped AS (
UPDATE issue
- SET revision = revision + 1
+ SET revision = revision + 1,
+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
WHERE id IN (SELECT issue_id FROM inserted)
RETURNING revision
)
@@ -85,19 +86,27 @@ func (q *Queries) AttachLabelToIssue(ctx context.Context, arg AttachLabelToIssue
}
const attachLabelToIssueOnCreate = `-- name: AttachLabelToIssueOnCreate :exec
+WITH touched_issue AS (
+ UPDATE issue
+ SET last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
+ WHERE issue.id = $1::uuid
+ AND issue.workspace_id = $3::uuid
+ AND NOT EXISTS (
+ SELECT 1 FROM issue_to_label
+ WHERE issue_to_label.issue_id = $1::uuid
+ AND issue_to_label.label_id = $2::uuid
+ )
+ AND EXISTS (
+ SELECT 1 FROM issue_label
+ WHERE issue_label.id = $2::uuid
+ AND issue_label.workspace_id = $3::uuid
+ AND issue_label.resource_type = 'issue'
+ )
+ RETURNING issue.id
+)
INSERT INTO issue_to_label (issue_id, label_id)
SELECT $1::uuid, $2::uuid
-WHERE EXISTS (
- SELECT 1 FROM issue i
- WHERE i.id = $1::uuid
- AND i.workspace_id = $3::uuid
-)
-AND EXISTS (
- SELECT 1 FROM issue_label l
- WHERE l.id = $2::uuid
- AND l.workspace_id = $3::uuid
- AND l.resource_type = 'issue'
-)
+WHERE EXISTS (SELECT 1 FROM touched_issue)
ON CONFLICT DO NOTHING
`
@@ -303,7 +312,8 @@ WITH deleted AS (
RETURNING issue_id
), bumped AS (
UPDATE issue
- SET revision = revision + 1
+ SET revision = revision + 1,
+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
WHERE id IN (SELECT issue_id FROM deleted)
RETURNING revision
)
diff --git a/server/pkg/db/generated/issue_property.sql.go b/server/pkg/db/generated/issue_property.sql.go
index 7731f99ecf..3a2cc95be8 100644
--- a/server/pkg/db/generated/issue_property.sql.go
+++ b/server/pkg/db/generated/issue_property.sql.go
@@ -119,9 +119,14 @@ const deleteIssuePropertyValue = `-- name: DeleteIssuePropertyValue :one
UPDATE issue
SET properties = properties - $1::text,
revision = revision + CASE WHEN properties ? $1::text THEN 1 ELSE 0 END,
+ last_activity_at = CASE
+ WHEN properties ? $1::text
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = CASE WHEN properties ? $1::text THEN now() ELSE updated_at END
WHERE id = $2::uuid AND workspace_id = $3::uuid
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
type DeleteIssuePropertyValueParams struct {
@@ -161,6 +166,7 @@ func (q *Queries) DeleteIssuePropertyValue(ctx context.Context, arg DeleteIssueP
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
@@ -267,9 +273,14 @@ const setIssuePropertyValue = `-- name: SetIssuePropertyValue :one
UPDATE issue
SET properties = jsonb_set(properties, ARRAY[$1::text], $2::jsonb, true),
revision = revision + CASE WHEN properties -> $1::text IS DISTINCT FROM $2::jsonb THEN 1 ELSE 0 END,
+ last_activity_at = CASE
+ WHEN properties -> $1::text IS DISTINCT FROM $2::jsonb
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = CASE WHEN properties -> $1::text IS DISTINCT FROM $2::jsonb THEN now() ELSE updated_at END
WHERE id = $3::uuid AND workspace_id = $4::uuid
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
type SetIssuePropertyValueParams struct {
@@ -317,6 +328,7 @@ func (q *Queries) SetIssuePropertyValue(ctx context.Context, arg SetIssuePropert
&i.Stage,
&i.Properties,
&i.Revision,
+ &i.LastActivityAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 6ca2ce0eab..a59d77ddcc 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -700,6 +700,7 @@ type Issue struct {
Stage pgtype.Int4 `json:"stage"`
Properties []byte `json:"properties"`
Revision int64 `json:"revision"`
+ LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
}
type IssueDependency struct {
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index efae0624e4..ca015d56fa 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -423,7 +423,7 @@ WHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1);
-- name: CreateComment :one
-- A new comment counts as activity on its issue, so the same statement bumps
--- the parent issue's updated_at. The touch is a leading data-modifying CTE and
+-- the parent issue's updated_at and last_activity_at. The touch is a leading data-modifying CTE and
-- the INSERT selects the issue/workspace back out of it, which makes the two
-- inseparable and gives two query-level guarantees:
-- * atomicity — the insert and the timestamp bump commit or roll back
@@ -438,7 +438,10 @@ WHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1);
-- guarantees regardless of what a caller passes. The "Updated date" sort and
-- the daemon GC TTL both read updated_at, so this consistency is load-bearing.
WITH touched_issue AS (
- UPDATE issue SET updated_at = now(), revision = revision + 1
+ UPDATE issue SET
+ updated_at = now(),
+ revision = revision + 1,
+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
WHERE issue.id = sqlc.arg(issue_id) AND issue.workspace_id = sqlc.arg(workspace_id)
RETURNING issue.id, issue.workspace_id, issue.revision
), inserted_comment AS (
@@ -480,19 +483,70 @@ ORDER BY created_at ASC, id ASC
LIMIT 1;
-- name: UpdateComment :one
-UPDATE comment SET
- content = $2,
- source_task_id = sqlc.narg(source_task_id),
- revision = revision + CASE WHEN ROW(content, source_task_id) IS DISTINCT FROM ROW($2, sqlc.narg(source_task_id)) THEN 1 ELSE 0 END,
- updated_at = CASE WHEN ROW(content, source_task_id) IS DISTINCT FROM ROW($2, sqlc.narg(source_task_id)) THEN now() ELSE updated_at END
-WHERE id = $1
- AND (sqlc.narg('expected_revision')::bigint IS NULL OR revision = sqlc.narg('expected_revision')::bigint)
- AND (
- sqlc.narg('content_base')::text IS NULL
- OR content IS NOT DISTINCT FROM sqlc.narg('content_base')::text
- OR content IS NOT DISTINCT FROM $2
- )
-RETURNING *;
+WITH locked_issue AS MATERIALIZED (
+ -- Keep the global issue -> child lock order used by issue teardown. The
+ -- aggregate below still yields one row when the parent was concurrently
+ -- deleted, preserving best-effort edits of an orphaned comment.
+ SELECT issue.id
+ FROM issue
+ JOIN comment ON comment.issue_id = issue.id
+ AND comment.workspace_id = issue.workspace_id
+ WHERE comment.id = $1
+ FOR UPDATE OF issue
+), issue_fence AS MATERIALIZED (
+ -- The aggregate always emits one row. Consuming locked_count in target's
+ -- tautological predicate creates a real data dependency: locked_issue must
+ -- acquire the owner lock before target can lock the comment. MATERIALIZED
+ -- prevents folding/re-evaluation; it does not itself establish lock order.
+ SELECT count(*) AS locked_count FROM locked_issue
+), target AS MATERIALIZED (
+ SELECT comment.*,
+ ROW(comment.content, comment.source_task_id) IS DISTINCT FROM
+ ROW($2, sqlc.narg(source_task_id)::uuid) AS did_change
+ FROM comment
+ CROSS JOIN issue_fence
+ WHERE comment.id = $1
+ AND issue_fence.locked_count >= 0
+ AND (sqlc.narg('expected_revision')::bigint IS NULL OR revision = sqlc.narg('expected_revision')::bigint)
+ AND (
+ sqlc.narg('content_base')::text IS NULL
+ OR content IS NOT DISTINCT FROM sqlc.narg('content_base')::text
+ OR content IS NOT DISTINCT FROM $2
+ )
+ FOR UPDATE OF comment
+), updated_comment AS (
+ UPDATE comment SET
+ content = $2,
+ source_task_id = sqlc.narg(source_task_id)::uuid,
+ revision = comment.revision + CASE WHEN target.did_change THEN 1 ELSE 0 END,
+ updated_at = CASE WHEN target.did_change THEN now() ELSE comment.updated_at END
+ FROM target
+ WHERE comment.id = target.id
+ RETURNING comment.id, comment.issue_id, comment.author_type, comment.author_id,
+ comment.content, comment.type, comment.created_at, comment.updated_at,
+ comment.parent_id, comment.workspace_id, comment.resolved_at,
+ comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id,
+ comment.quick_action_id, comment.via_plugin_id, comment.revision,
+ target.did_change
+), touched_issue AS (
+ UPDATE issue
+ SET revision = issue.revision + 1,
+ last_activity_at = GREATEST(COALESCE(issue.last_activity_at, issue.updated_at), now())
+ FROM updated_comment
+ WHERE updated_comment.did_change
+ AND issue.id = updated_comment.issue_id
+ AND issue.workspace_id = updated_comment.workspace_id
+ RETURNING issue.id, issue.revision
+)
+SELECT updated_comment.id, updated_comment.issue_id, updated_comment.author_type,
+ updated_comment.author_id, updated_comment.content, updated_comment.type,
+ updated_comment.created_at, updated_comment.updated_at, updated_comment.parent_id,
+ updated_comment.workspace_id, updated_comment.resolved_at,
+ updated_comment.resolved_by_type, updated_comment.resolved_by_id,
+ updated_comment.source_task_id, updated_comment.quick_action_id,
+ updated_comment.via_plugin_id, updated_comment.revision,
+ COALESCE((SELECT revision FROM touched_issue), 0)::bigint AS issue_revision
+FROM updated_comment;
-- name: BumpCommentRevision :one
UPDATE comment
@@ -518,9 +572,39 @@ SELECT EXISTS (
SELECT count(*) > 0 AS has_replied FROM comment
WHERE parent_id = @parent_id AND author_type = 'agent' AND author_id = @agent_id;
--- name: DeleteComment :exec
+-- name: DeleteComment :one
-- Defense-in-depth: workspace_id is a SQL-layer tenant guard. See DeleteIssue.
-DELETE FROM comment WHERE id = $1 AND workspace_id = $2;
+WITH locked_issue AS MATERIALIZED (
+ -- Lock the aggregate owner before its child so this cannot deadlock with
+ -- issue teardown (which takes the same issue -> comment order).
+ SELECT issue.id
+ FROM issue
+ JOIN comment ON comment.issue_id = issue.id
+ AND comment.workspace_id = issue.workspace_id
+ WHERE comment.id = $1 AND comment.workspace_id = $2
+ FOR UPDATE OF issue
+), issue_fence AS MATERIALIZED (
+ -- The consumed locked_count below is the ordering fence: the issue lock is
+ -- acquired before DELETE can lock the comment. MATERIALIZED only prevents
+ -- folding/re-evaluation and is not, by itself, a lock-order guarantee.
+ SELECT count(*) AS locked_count FROM locked_issue
+), deleted_comment AS (
+ DELETE FROM comment
+ USING issue_fence
+ WHERE comment.id = $1 AND comment.workspace_id = $2
+ AND issue_fence.locked_count >= 0
+ RETURNING issue_id, workspace_id
+), touched_issue AS (
+ UPDATE issue
+ SET revision = issue.revision + 1,
+ last_activity_at = GREATEST(COALESCE(issue.last_activity_at, issue.updated_at), now())
+ FROM deleted_comment
+ WHERE issue.id = deleted_comment.issue_id
+ AND issue.workspace_id = deleted_comment.workspace_id
+ RETURNING issue.id, issue.revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted_comment) AS changed,
+ COALESCE((SELECT revision FROM touched_issue), 0)::bigint AS issue_revision;
-- name: ResolveComment :one
-- Idempotent: re-resolving keeps the original resolved_at + resolver. Always
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 52e7a4f6ed..170f205152 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -7,7 +7,7 @@
-- "Assigned to me"), and the two filters must produce disjoint result sets.
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
i.revision
FROM issue i
WHERE i.workspace_id = $1
@@ -104,6 +104,8 @@ FOR UPDATE;
-- with the fully composed Markdown so rich-text ordering survives. If a user
-- edited concurrently (or the adapter has no inline layout), append instead;
-- preserving user-authored bytes takes precedence over layout fidelity.
+-- This is asynchronous system materialization, not a new user action, so it
+-- intentionally preserves last_activity_at while still advancing revision.
UPDATE issue
SET description = CASE
WHEN sqlc.narg('base_description')::text IS NOT NULL
@@ -132,10 +134,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- stage
+ stage, last_activity_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- sqlc.narg('stage')
+ sqlc.narg('stage'), now()
) RETURNING *;
-- name: GetIssueByNumber :one
@@ -171,7 +173,15 @@ WITH candidate AS (
next_title, next_description, next_status, next_priority,
next_assignee_type, next_assignee_id, next_position, next_start_date,
next_due_date, next_parent_issue_id, next_project_id, next_stage
- ) AS did_change
+ ) AS did_change,
+ ROW(
+ title, description, status, priority, assignee_type, assignee_id,
+ start_date, due_date, parent_issue_id, project_id, stage
+ ) IS DISTINCT FROM ROW(
+ next_title, next_description, next_status, next_priority,
+ next_assignee_type, next_assignee_id, next_start_date, next_due_date,
+ next_parent_issue_id, next_project_id, next_stage
+ ) AS did_activity
FROM candidate
)
UPDATE issue AS i SET
@@ -188,6 +198,10 @@ UPDATE issue AS i SET
project_id = changed.next_project_id,
stage = changed.next_stage,
revision = i.revision + changed.did_change::integer,
+ last_activity_at = CASE WHEN changed.did_activity
+ THEN GREATEST(COALESCE(i.last_activity_at, i.updated_at), now())
+ ELSE i.last_activity_at
+ END,
updated_at = CASE WHEN changed.did_change THEN now() ELSE i.updated_at END
FROM changed
WHERE i.id = changed.id
@@ -198,6 +212,10 @@ RETURNING i.*;
UPDATE issue SET
status = $2,
revision = revision + CASE WHEN status IS DISTINCT FROM $2 THEN 1 ELSE 0 END,
+ last_activity_at = CASE WHEN status IS DISTINCT FROM $2
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = now()
WHERE id = $1 AND workspace_id = $3
RETURNING *;
@@ -207,10 +225,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- origin_type, origin_id, stage
+ origin_type, origin_id, stage, last_activity_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- sqlc.narg('origin_type'), sqlc.narg('origin_id'), sqlc.narg('stage')
+ sqlc.narg('origin_type'), sqlc.narg('origin_id'), sqlc.narg('stage'), now()
) RETURNING *;
-- name: LockIssueDuplicateKey :exec
@@ -275,7 +293,7 @@ DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target);
-- filter; member-direct assignment is intentionally excluded).
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
i.revision
FROM issue i
WHERE i.workspace_id = $1
@@ -450,6 +468,11 @@ GROUP BY parent_issue_id;
UPDATE issue SET
metadata = jsonb_set(metadata, ARRAY[sqlc.arg('key')::text], sqlc.arg('value')::jsonb),
revision = revision + CASE WHEN metadata -> sqlc.arg('key')::text IS DISTINCT FROM sqlc.arg('value')::jsonb THEN 1 ELSE 0 END,
+ last_activity_at = CASE
+ WHEN metadata -> sqlc.arg('key')::text IS DISTINCT FROM sqlc.arg('value')::jsonb
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = now()
WHERE id = sqlc.arg('id') AND workspace_id = sqlc.arg('workspace_id')
RETURNING *;
@@ -460,6 +483,11 @@ RETURNING *;
UPDATE issue SET
metadata = metadata - sqlc.arg('key')::text,
revision = revision + CASE WHEN metadata ? sqlc.arg('key')::text THEN 1 ELSE 0 END,
+ last_activity_at = CASE
+ WHEN metadata ? sqlc.arg('key')::text
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = now()
WHERE id = sqlc.arg('id') AND workspace_id = sqlc.arg('workspace_id')
RETURNING *;
diff --git a/server/pkg/db/queries/issue_label.sql b/server/pkg/db/queries/issue_label.sql
index 6017a3ba84..d315a6d22a 100644
--- a/server/pkg/db/queries/issue_label.sql
+++ b/server/pkg/db/queries/issue_label.sql
@@ -73,19 +73,27 @@ WHERE agent_id IN (SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system
-- Workspace-guarded INSERT: the WHERE EXISTS clauses ensure both the issue
-- and the label belong to the given workspace. A future caller that forgets
-- handler-level prechecks still cannot attach labels across workspaces.
+WITH touched_issue AS (
+ UPDATE issue
+ SET last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
+ WHERE issue.id = sqlc.arg('issue_id')::uuid
+ AND issue.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND NOT EXISTS (
+ SELECT 1 FROM issue_to_label
+ WHERE issue_to_label.issue_id = sqlc.arg('issue_id')::uuid
+ AND issue_to_label.label_id = sqlc.arg('label_id')::uuid
+ )
+ AND EXISTS (
+ SELECT 1 FROM issue_label
+ WHERE issue_label.id = sqlc.arg('label_id')::uuid
+ AND issue_label.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND issue_label.resource_type = 'issue'
+ )
+ RETURNING issue.id
+)
INSERT INTO issue_to_label (issue_id, label_id)
SELECT sqlc.arg('issue_id')::uuid, sqlc.arg('label_id')::uuid
-WHERE EXISTS (
- SELECT 1 FROM issue i
- WHERE i.id = sqlc.arg('issue_id')::uuid
- AND i.workspace_id = sqlc.arg('workspace_id')::uuid
-)
-AND EXISTS (
- SELECT 1 FROM issue_label l
- WHERE l.id = sqlc.arg('label_id')::uuid
- AND l.workspace_id = sqlc.arg('workspace_id')::uuid
- AND l.resource_type = 'issue'
-)
+WHERE EXISTS (SELECT 1 FROM touched_issue)
ON CONFLICT DO NOTHING;
-- name: AttachLabelToIssue :one
@@ -107,7 +115,8 @@ WITH inserted AS (
RETURNING issue_id
), bumped AS (
UPDATE issue
- SET revision = revision + 1
+ SET revision = revision + 1,
+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
WHERE id IN (SELECT issue_id FROM inserted)
RETURNING revision
)
@@ -129,7 +138,8 @@ WITH deleted AS (
RETURNING issue_id
), bumped AS (
UPDATE issue
- SET revision = revision + 1
+ SET revision = revision + 1,
+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
WHERE id IN (SELECT issue_id FROM deleted)
RETURNING revision
)
diff --git a/server/pkg/db/queries/issue_property.sql b/server/pkg/db/queries/issue_property.sql
index 1d4bc3d44f..3e69472743 100644
--- a/server/pkg/db/queries/issue_property.sql
+++ b/server/pkg/db/queries/issue_property.sql
@@ -53,6 +53,11 @@ RETURNING *;
UPDATE issue
SET properties = jsonb_set(properties, ARRAY[sqlc.arg('key')::text], sqlc.arg('value')::jsonb, true),
revision = revision + CASE WHEN properties -> sqlc.arg('key')::text IS DISTINCT FROM sqlc.arg('value')::jsonb THEN 1 ELSE 0 END,
+ last_activity_at = CASE
+ WHEN properties -> sqlc.arg('key')::text IS DISTINCT FROM sqlc.arg('value')::jsonb
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = CASE WHEN properties -> sqlc.arg('key')::text IS DISTINCT FROM sqlc.arg('value')::jsonb THEN now() ELSE updated_at END
WHERE id = sqlc.arg('id')::uuid AND workspace_id = sqlc.arg('workspace_id')::uuid
RETURNING *;
@@ -61,6 +66,11 @@ RETURNING *;
UPDATE issue
SET properties = properties - sqlc.arg('key')::text,
revision = revision + CASE WHEN properties ? sqlc.arg('key')::text THEN 1 ELSE 0 END,
+ last_activity_at = CASE
+ WHEN properties ? sqlc.arg('key')::text
+ THEN GREATEST(COALESCE(last_activity_at, updated_at), now())
+ ELSE last_activity_at
+ END,
updated_at = CASE WHEN properties ? sqlc.arg('key')::text THEN now() ELSE updated_at END
WHERE id = sqlc.arg('id')::uuid AND workspace_id = sqlc.arg('workspace_id')::uuid
RETURNING *;