Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(integrations): release resume locks during provider requests

Tin13f53d3dd639
diff --git a/apps/api/src/integration-sync/controllers/apply-resume.ts b/apps/api/src/integration-sync/controllers/apply-resume.ts
new file mode 100644
index 000000000..eacc8246a
--- /dev/null
+++ b/apps/api/src/integration-sync/controllers/apply-resume.ts
@@ -0,0 +1,153 @@
+import { randomUUID } from "node:crypto";
+import { asc, eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import { columnTable, taskTable } from "../../database/schema";
+import { updateExternalLink } from "../../plugins/github/services/link-manager";
+import { parseDeferredIssueEdit } from "../../plugins/github/utils/deferred-issue-edit";
+import {
+ inboundStamp,
+ type SyncStamp,
+} from "../../plugins/github/utils/sync-echo";
+import { formatIssueBody } from "../../plugins/github/utils/format";
+import { resolveTargetStatus as resolveGithubStatus } from "../../plugins/github/utils/resolve-column";
+import { resolveTargetStatus as resolveGiteaStatus } from "../../plugins/gitea/utils/resolve-column";
+import { resolveTargetStatus as resolveGitlabStatus } from "../../plugins/gitlab/utils/resolve-column";
+import {
+ recordTaskMutation,
+ type TaskBefore,
+} from "../../task/controllers/task-mutation-effects";
+import type { reviewSyncResume } from "./review-resume";
+
+export async function applySyncResume(
+ review: Awaited<ReturnType<typeof reviewSyncResume>>,
+ provider: string,
+ source: "kaneo" | "provider",
+ updatedAt: string | null,
+ tx: Parameters<typeof recordTaskMutation>[0],
+) {
+ const { task, link } = review;
+ let adoption:
+ | { before: TaskBefore; after: TaskBefore; integrationId: string }
+ | undefined;
+ if (source === "provider") {
+ let status = { status: task.status, columnId: task.columnId };
+ if (review.local.state !== review.remote.state) {
+ const columns = await tx
+ .select()
+ .from(columnTable)
+ .where(eq(columnTable.projectId, task.projectId))
+ .orderBy(asc(columnTable.position));
+ const fallback = columns.find(
+ (column) => column.isFinal === (review.remote.state === "closed"),
+ );
+ if (!fallback)
+ throw new HTTPException(409, {
+ message: "A matching open or completed column is required",
+ });
+ const resolveStatus =
+ provider === "gitea"
+ ? resolveGiteaStatus
+ : provider === "gitlab"
+ ? resolveGitlabStatus
+ : resolveGithubStatus;
+ const slug = await resolveStatus(
+ task.projectId,
+ review.remote.state === "closed" ? "issue_closed" : "issue_reopened",
+ fallback.slug,
+ tx,
+ );
+ const target = columns.find((column) => column.slug === slug)!;
+ status = { status: target.slug, columnId: target.id };
+ }
+ const [after] = await tx
+ .update(taskTable)
+ .set({
+ title: review.remote.title,
+ description: review.remote.description,
+ ...status,
+ })
+ .where(eq(taskTable.id, task.id))
+ .returning();
+ await recordTaskMutation(tx, task, after!);
+ adoption = {
+ before: task,
+ after: after!,
+ integrationId: review.integration.id,
+ };
+ }
+ const job = parseDeferredIssueEdit(
+ JSON.parse(link.metadata ?? "{}").deferredIssueEdit,
+ );
+ for (const field of ["title", "description", "state"] as const) {
+ await updateExternalLink(
+ link.id,
+ {
+ ...(field === "title"
+ ? { title: review[source === "kaneo" ? "local" : "remote"].title }
+ : {}),
+ ...(source === "kaneo" && provider !== "gitlab"
+ ? {
+ outbound: {
+ field,
+ value: review.local[field],
+ intentId: randomUUID(),
+ updatedAt: updatedAt ?? undefined,
+ pending: false,
+ },
+ }
+ : {}),
+ ...(job ? { completeDeferredEdit: job.id } : {}),
+ metadata: {
+ syncFilterPaused: false,
+ syncResumeUncertain: false,
+ syncResumeLabelBaseline: review.remoteIssueLabels,
+ ...(provider === "gitlab"
+ ? {
+ lastOutboundStateSyncAt: Date.now(),
+ lastSync: {
+ title: {
+ source: source === "kaneo" ? "kaneo" : "gitlab",
+ value:
+ review[source === "kaneo" ? "local" : "remote"].title,
+ timestamp: new Date().toISOString(),
+ },
+ description: {
+ source: source === "kaneo" ? "kaneo" : "gitlab",
+ value:
+ source === "kaneo"
+ ? formatIssueBody(review.local.description, task.id)
+ : review.remote.description,
+ timestamp: new Date().toISOString(),
+ },
+ },
+ }
+ : {}),
+ ...(source === "provider" && provider !== "gitlab"
+ ? {
+ lastSync: {
+ [field]: inboundStamp(
+ (
+ JSON.parse(link.metadata ?? "{}").lastSync as
+ | Record<string, SyncStamp>
+ | undefined
+ )?.[field],
+ review.remote[field],
+ provider,
+ review.remoteIssueUpdatedAt ?? undefined,
+ ),
+ },
+ }
+ : {}),
+ state:
+ provider === "gitlab" &&
+ review[source === "kaneo" ? "local" : "remote"].state === "open"
+ ? "opened"
+ : review[source === "kaneo" ? "local" : "remote"].state,
+ },
+ retireUncertainOutbound: field,
+ },
+ tx,
+ );
+ }
+ return adoption;
+}
diff --git a/apps/api/src/integration-sync/controllers/lock-resume-scope.ts b/apps/api/src/integration-sync/controllers/lock-resume-scope.ts
index b588cb430..382e783be 100644
--- a/apps/api/src/integration-sync/controllers/lock-resume-scope.ts
+++ b/apps/api/src/integration-sync/controllers/lock-resume-scope.ts
@@ -44,7 +44,7 @@ export async function lockResumeScope(
});
if (rule.mode === "labels") {
// Protect both selected roots and assigned copies against rename/deletion
- // until the provider write and local resume have committed.
+ // while validating each local resume phase.
await tx
.select({ id: labelTable.id })
.from(labelTable)
diff --git a/apps/api/src/integration-sync/controllers/resume-provider-snapshot.ts b/apps/api/src/integration-sync/controllers/resume-provider-snapshot.ts
new file mode 100644
index 000000000..9ce9ae01c
--- /dev/null
+++ b/apps/api/src/integration-sync/controllers/resume-provider-snapshot.ts
@@ -0,0 +1,8 @@
+import type { providerIssue } from "../../plugins/sync/provider-issue";
+
+type IssueAccess = Awaited<ReturnType<typeof providerIssue>>;
+
+export type ResumeProviderSnapshot = {
+ access: IssueAccess;
+ remoteIssue: Awaited<ReturnType<IssueAccess["read"]>>;
+};
diff --git a/apps/api/src/integration-sync/controllers/resume-sync.ts b/apps/api/src/integration-sync/controllers/resume-sync.ts
index 5cb7363f0..adb6efe37 100644
--- a/apps/api/src/integration-sync/controllers/resume-sync.ts
+++ b/apps/api/src/integration-sync/controllers/resume-sync.ts
@@ -1,25 +1,14 @@
-import { randomUUID } from "node:crypto";
-import { asc, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
-import { columnTable, taskTable } from "../../database/schema";
import { publishEvent } from "../../events";
import { updateExternalLink } from "../../plugins/github/services/link-manager";
-import { parseDeferredIssueEdit } from "../../plugins/github/utils/deferred-issue-edit";
-import {
- inboundStamp,
- type SyncStamp,
-} from "../../plugins/github/utils/sync-echo";
-import { formatIssueBody } from "../../plugins/github/utils/format";
-import { reviewSyncResume } from "./review-resume";
-import { lockResumeScope } from "./lock-resume-scope";
import { withSyncLease } from "../../plugins/sync/lease";
import { SyncLeaseBusyError } from "../../plugins/sync/lease-busy-error";
-import {
- publishTaskMutation,
- recordTaskMutation,
- type TaskBefore,
-} from "../../task/controllers/task-mutation-effects";
+import { publishTaskMutation } from "../../task/controllers/task-mutation-effects";
+import { applySyncResume } from "./apply-resume";
+import { lockResumeScope } from "./lock-resume-scope";
+import { reviewSyncResume } from "./review-resume";
+import type { ResumeProviderSnapshot } from "./resume-provider-snapshot";
export async function resumeSync(
projectId: string,
@@ -46,155 +35,80 @@ async function resumeWithLease(
token: string,
source: "kaneo" | "provider",
) {
- let providerWritten = false;
- let adoption:
- | { before: TaskBefore; after: TaskBefore; integrationId: string }
+ // Provider latency must not retain a pooled connection or block local edits.
+ const initial = await reviewSyncResume(projectId, provider, linkId);
+ const { snapshot } = initial;
+ let request:
+ | Promise<
+ | {
+ value: Awaited<
+ ReturnType<ResumeProviderSnapshot["access"]["write"]>
+ >;
+ }
+ | { error: unknown }
+ >
| undefined;
- let taskId: string | undefined;
+ let providerWritten = false;
+ let updatedAt: string | null = null;
+ let adoption: Awaited<ReturnType<typeof applySyncResume>>;
+ const validate = async (tx: Parameters<typeof lockResumeScope>[3]) => {
+ await lockResumeScope(projectId, provider, linkId, tx);
+ const review = await reviewSyncResume(
+ projectId,
+ provider,
+ linkId,
+ tx,
+ snapshot,
+ );
+ if (review.token !== token)
+ throw new HTTPException(409, {
+ message: "Task or issue changed; review the comparison again",
+ });
+ return review;
+ };
try {
- await db.transaction(async (tx) => {
- await lockResumeScope(projectId, provider, linkId, tx);
- const review = await reviewSyncResume(projectId, provider, linkId, tx);
- taskId = review.task.id;
- const task = review.task;
- const link = review.link;
- if (review.token !== token)
- throw new HTTPException(409, {
- message: "Task or issue changed; review the comparison again",
- });
- let updatedAt: string | null = null;
- if (source === "kaneo") {
- try {
- updatedAt = (await review.access.write(review.local)).updatedAt;
- providerWritten = true;
- } catch {
- console.error("Sync resume provider write failed", {
- projectId,
- provider,
- linkId,
- });
- throw new HTTPException(502, {
- message: "External issue could not be updated; sync remains paused",
- });
- }
- }
- if (source === "provider") {
- let status = { status: task.status, columnId: task.columnId };
- if (review.local.state !== review.remote.state) {
- const columns = await tx
- .select()
- .from(columnTable)
- .where(eq(columnTable.projectId, projectId))
- .orderBy(asc(columnTable.position));
- const target = columns.find(
- (column) => column.isFinal === (review.remote.state === "closed"),
- );
- if (!target)
- throw new HTTPException(409, {
- message: "A matching open or completed column is required",
- });
- status = { status: target.slug, columnId: target.id };
- }
- const [after] = await tx
- .update(taskTable)
- .set({
- title: review.remote.title,
- description: review.remote.description,
- ...status,
- })
- .where(eq(taskTable.id, task.id))
- .returning();
- await recordTaskMutation(tx, task, after!);
- adoption = {
- before: task,
- after: after!,
- integrationId: review.integration.id,
- };
- }
- const job = parseDeferredIssueEdit(
- JSON.parse(link.metadata ?? "{}").deferredIssueEdit,
- );
- for (const field of ["title", "description", "state"] as const) {
- await updateExternalLink(
- linkId,
- {
- ...(field === "title"
- ? { title: review[source === "kaneo" ? "local" : "remote"].title }
- : {}),
- ...(source === "kaneo" && provider !== "gitlab"
- ? {
- outbound: {
- field,
- value: review.local[field],
- intentId: randomUUID(),
- updatedAt: updatedAt ?? undefined,
- pending: false,
- },
- }
- : {}),
- ...(job ? { completeDeferredEdit: job.id } : {}),
- metadata: {
- syncFilterPaused: false,
- syncResumeUncertain: false,
- syncResumeLabelBaseline: review.remoteIssueLabels,
- ...(provider === "gitlab"
- ? {
- lastOutboundStateSyncAt: Date.now(),
- lastSync: {
- title: {
- source: source === "kaneo" ? "kaneo" : "gitlab",
- value:
- review[source === "kaneo" ? "local" : "remote"].title,
- timestamp: new Date().toISOString(),
- },
- description: {
- source: source === "kaneo" ? "kaneo" : "gitlab",
- value:
- source === "kaneo"
- ? formatIssueBody(review.local.description, task.id)
- : review.remote.description,
- timestamp: new Date().toISOString(),
- },
- },
- }
- : {}),
- ...(source === "provider" && provider !== "gitlab"
- ? {
- lastSync: {
- [field]: inboundStamp(
- (
- JSON.parse(link.metadata ?? "{}").lastSync as
- | Record<string, SyncStamp>
- | undefined
- )?.[field],
- review.remote[field],
- provider,
- review.remoteIssueUpdatedAt ?? undefined,
- ),
- },
- }
- : {}),
- state:
- provider === "gitlab" &&
- review[source === "kaneo" ? "local" : "remote"].state === "open"
- ? "opened"
- : review[source === "kaneo" ? "local" : "remote"].state,
- },
- retireUncertainOutbound: field,
- },
- tx,
+ if (source === "kaneo") {
+ await db.transaction(async (tx) => {
+ const review = await validate(tx);
+ // Dispatch while scope changes are excluded, then release the locks
+ // before awaiting the response. Completion rechecks the local snapshot.
+ request = snapshot.access.write(review.local).then(
+ (value) => ({ value }),
+ (error: unknown) => ({ error }),
);
+ });
+ const result = await request!;
+ if ("error" in result) {
+ console.error("Sync resume provider write failed", {
+ projectId,
+ provider,
+ linkId,
+ });
+ throw new HTTPException(502, {
+ message: "External issue could not be updated; sync remains paused",
+ });
}
+ providerWritten = true;
+ updatedAt = result.value.updatedAt;
+ }
+ await db.transaction(async (tx) => {
+ const review = await validate(tx);
+ adoption = await applySyncResume(review, provider, source, updatedAt, tx);
});
} catch (error) {
+ // Dispatch can outlive a failed scope transaction. Observe its result before
+ // deciding whether the next comparison must show an uncertain provider edit.
+ if (request && !providerWritten)
+ providerWritten = "value" in (await request);
if (providerWritten) {
- // A database failure after a successful provider write must remain visible
- // to the next review. The link stays paused and clients refresh both sides.
await updateExternalLink(linkId, {
metadata: { syncFilterPaused: true, syncResumeUncertain: true },
});
await publishEvent("project.updated", { projectId });
- if (taskId) await publishEvent("task.updated", { projectId, taskId });
+ await publishEvent("task.updated", {
+ projectId,
+ taskId: initial.task.id,
+ });
}
throw error;
}
@@ -203,7 +117,7 @@ async function resumeWithLease(
fields: ["title", "description", "status"],
sourceIntegrationId: adoption.integrationId,
});
- await publishEvent("task.updated", { projectId, taskId });
+ await publishEvent("task.updated", { projectId, taskId: initial.task.id });
await publishEvent("project.updated", { projectId });
return { success: true };
}
diff --git a/apps/api/src/integration-sync/controllers/review-resume.ts b/apps/api/src/integration-sync/controllers/review-resume.ts
index 77df4eca4..0ffce0fcd 100644
--- a/apps/api/src/integration-sync/controllers/review-resume.ts
+++ b/apps/api/src/integration-sync/controllers/review-resume.ts
@@ -9,12 +9,14 @@ import { providerIssue } from "../../plugins/sync/provider-issue";
import { isSyncPaused, readSyncRules } from "../../plugins/sync/rules";
import { getSyncIntegration } from "./get-integration";
import type { IntegrationDatabase } from "../../plugins/github/services/integration-task-scope";
+import type { ResumeProviderSnapshot } from "./resume-provider-snapshot";
export async function reviewSyncResume(
projectId: string,
provider: string,
linkId: string,
database: IntegrationDatabase = db,
+ providerSnapshot?: ResumeProviderSnapshot,
) {
const integration = await getSyncIntegration(projectId, provider, database);
const link = await database.query.externalLinkTable.findFirst({
@@ -55,21 +57,23 @@ export async function reviewSyncResume(
? ("closed" as const)
: ("open" as const),
};
- let access: Awaited<ReturnType<typeof providerIssue>>;
- let remoteIssue: Awaited<ReturnType<typeof access.read>>;
- try {
- access = await providerIssue(integration, link);
- remoteIssue = await access.read();
- } catch {
- console.error("Sync resume provider read failed", {
- projectId,
- provider,
- linkId,
- });
- throw new HTTPException(502, {
- message: "External issue could not be read; sync remains paused",
- });
+ let snapshot = providerSnapshot;
+ if (!snapshot) {
+ try {
+ const access = await providerIssue(integration, link);
+ snapshot = { access, remoteIssue: await access.read() };
+ } catch {
+ console.error("Sync resume provider read failed", {
+ projectId,
+ provider,
+ linkId,
+ });
+ throw new HTTPException(502, {
+ message: "External issue could not be read; sync remains paused",
+ });
+ }
}
+ const { remoteIssue } = snapshot;
const remote = {
title: remoteIssue.title,
description: remoteIssue.description,
@@ -90,7 +94,7 @@ export async function reviewSyncResume(
integration,
link,
task,
- access,
+ snapshot,
local,
remote,
remoteIssueLabels: remoteIssue.labels,
diff --git a/apps/api/src/plugins/sync/dispatch-issue-write.ts b/apps/api/src/plugins/sync/dispatch-issue-write.ts
index 3e3270d1c..2770a32ca 100644
--- a/apps/api/src/plugins/sync/dispatch-issue-write.ts
+++ b/apps/api/src/plugins/sync/dispatch-issue-write.ts
@@ -19,47 +19,59 @@ export async function dispatchIssueWrite<T>(
});
if (!integration) return;
let request: Promise<{ value: T } | { error: unknown }> | undefined;
- await withIntegrationLink(
- link,
- integration,
- async (tx) => {
- const rule = readSyncRules(integration.config)?.outgoing;
- if (rule?.mode === "labels") {
- await tx
- .select({ id: labelTable.id })
- .from(labelTable)
- .where(
- and(
- eq(labelTable.workspaceId, integration.project.workspaceId),
- or(
- and(
- isNull(labelTable.taskId),
- inArray(labelTable.id, rule.labels),
+ try {
+ await withIntegrationLink(
+ link,
+ integration,
+ async (tx) => {
+ const rule = readSyncRules(integration.config)?.outgoing;
+ if (rule?.mode === "labels") {
+ await tx
+ .select({ id: labelTable.id })
+ .from(labelTable)
+ .where(
+ and(
+ eq(labelTable.workspaceId, integration.project.workspaceId),
+ or(
+ and(
+ isNull(labelTable.taskId),
+ inArray(labelTable.id, rule.labels),
+ ),
+ eq(labelTable.taskId, link.taskId),
),
- eq(labelTable.taskId, link.taskId),
),
- ),
- )
- .orderBy(labelTable.id)
- .for("share");
- }
- if (!(await canSyncTask(link.taskId, integration.id, tx, expectedConfig)))
- return;
- // Start the request while pause/rule/label writes are excluded. Settle it
- // after commit so provider latency never holds these row locks.
- request = send().then(
- (value) => ({ value }),
- (error: unknown) => ({ error }),
- );
- },
- {
- type: integration.type,
- validate: (binding) =>
- sameConfig(binding.config, integration.config) &&
- (expectedConfig === undefined ||
- sameConfig(binding.config, expectedConfig)),
- },
- );
+ )
+ .orderBy(labelTable.id)
+ .for("share");
+ }
+ if (
+ !(await canSyncTask(link.taskId, integration.id, tx, expectedConfig))
+ )
+ return;
+ // Start the request while pause/rule/label writes are excluded. Settle it
+ // after commit so provider latency never holds these row locks.
+ request = send().then(
+ (value) => ({ value }),
+ (error: unknown) => ({ error }),
+ );
+ },
+ {
+ type: integration.type,
+ validate: (binding) =>
+ sameConfig(binding.config, integration.config) &&
+ (expectedConfig === undefined ||
+ sameConfig(binding.config, expectedConfig)),
+ },
+ );
+ } catch (error) {
+ if (!request) throw error;
+ // The eligible dispatch path only reads/locks rows. A failed commit cannot
+ // undo its provider request; settle it so the caller records its outcome.
+ console.error("Issue write scope transaction failed after dispatch", {
+ integrationId: integration.id,
+ linkId: link.id,
+ });
+ }
if (!request) return;
const result = await request;
if ("error" in result) throw result.error;
diff --git a/apps/docs/core/integrations/index.mdx b/apps/docs/core/integrations/index.mdx
index 35efffb36..8966bbb84 100644
--- a/apps/docs/core/integrations/index.mdx
+++ b/apps/docs/core/integrations/index.mdx
@@ -32,7 +32,7 @@ When a linked task loses its qualifying labels, synchronization pauses in both d
Resuming leaves priority, detailed status, and custom labels unchanged. Later repository label events apply changes made after the comparison, so an unrelated label event does not restore stale values from the pause. Issue filters do not prevent branch or pull request linking and their configured status transitions.
-Kaneo rereads the issue when you resume and rejects a changed comparison. Gitea's content version, when available, also protects the body write from concurrent edits. Provider APIs do not offer an atomic version check for every issue field, so an edit made after the final read can still conflict with a resume write. Avoid editing the repository issue while resuming it. A rejected provider write leaves synchronization paused for another review.
+Kaneo rereads the issue when you resume and rejects a changed comparison. Local edits remain available while the repository responds; a task, rule, label, or link change during a resume write keeps synchronization paused for another review. When adopting a different open/closed state, resume uses the project's configured issue close or reopen workflow target. Gitea's content version, when available, also protects the body write from concurrent edits. Provider APIs do not offer an atomic version check for every issue field, so an edit made after the final read can still conflict with a resume write. Avoid editing the repository issue while resuming it. A rejected provider write leaves synchronization paused for another review.
An issue creation request already sent to a repository may finish after its task stops matching. Kaneo keeps the returned issue link paused and stops further updates. Local edits remain available while the repository responds.
diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.ts
index 30b23fbf5..233d19e7d 100644
--- a/tests/api-integration/integration-sync-providers.test.ts
+++ b/tests/api-integration/integration-sync-providers.test.ts
@@ -8,7 +8,12 @@ import {
vi,
} from "vite-plus/test";
import * as events from "../../apps/api/src/events";
-import db, { getDatabasePool, schema } from "../../apps/api/src/database";
+import db, {
+ getDatabase,
+ getDatabasePool,
+ schema,
+} from "../../apps/api/src/database";
+import { syncLatestTaskValue } from "../../apps/api/src/plugins/github/services/sync-latest-task-value";
import { giteaPlugin } from "../../apps/api/src/plugins/gitea";
import { handleGiteaIssueLabeled } from "../../apps/api/src/plugins/gitea/webhooks/issue-labeled";
import { handleIssueLabeled } from "../../apps/api/src/plugins/github/webhooks/issue-labeled";
@@ -570,6 +575,108 @@ describe.each(["github", "gitea", "gitlab"] as const)(
}
});
+ it("records a successful outbound edit after its scope transaction fails", async () => {
+ const f = await setup(type);
+ await f.assign();
+ await reconcileTaskSync(f.project.id, f.task.id);
+ const link = (await db.query.externalLinkTable.findMany())[0]!;
+ await db
+ .update(schema.taskTable)
+ .set({ title: "New title" })
+ .where(eq(schema.taskTable.id, f.task.id));
+ const write = vi.fn(async () => "local-time");
+ let injected = false;
+ const transaction = getDatabase().transaction.bind(getDatabase());
+ vi.spyOn(getDatabase(), "transaction").mockImplementation(
+ (apply, config) =>
+ transaction(async (tx) => {
+ const result = await apply(tx);
+ if (!injected && write.mock.calls.length) {
+ injected = true;
+ throw new Error("Injected dispatch transaction failure");
+ }
+ return result;
+ }, config),
+ );
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
+ await syncLatestTaskValue(
+ f.task.id,
+ f.project.id,
+ link,
+ "title",
+ "New title",
+ write,
+ undefined,
+ { type, config: f.integration.config },
+ );
+ expect(injected).toBe(true);
+ expect(write).toHaveBeenCalledOnce();
+ const stored = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, link.id),
+ });
+ expect(JSON.parse(stored!.metadata!).lastSync.title).toMatchObject({
+ source: "kaneo",
+ value: "New title",
+ outbound: [
+ expect.objectContaining({ pending: false, updatedAt: "local-time" }),
+ ],
+ });
+ expect(log).toHaveBeenCalledWith(
+ "Issue write scope transaction failed after dispatch",
+ { integrationId: f.integration.id, linkId: link.id },
+ );
+ });
+
+ it.each(["open", "closed"] as const)(
+ "adopts the configured %s workflow target when resuming",
+ async (state) => {
+ const f = await setup(type);
+ await f.assign();
+ await reconcileTaskSync(f.project.id, f.task.id);
+ const link = (await db.query.externalLinkTable.findMany())[0]!;
+ const [target] = await db
+ .insert(schema.columnTable)
+ .values({
+ projectId: f.project.id,
+ name: "Mapped",
+ slug: "mapped",
+ position: 99,
+ isFinal: state === "closed",
+ })
+ .returning();
+ await db.insert(schema.workflowRuleTable).values({
+ projectId: f.project.id,
+ integrationType: type,
+ eventType: state === "closed" ? "issue_closed" : "issue_reopened",
+ columnId: target.id,
+ });
+ if (state === "open")
+ await db
+ .update(schema.taskTable)
+ .set({ status: f.columns.done.slug, columnId: f.columns.done.id })
+ .where(eq(schema.taskTable.id, f.task.id));
+ await updateExternalLink(link.id, {
+ metadata: { syncFilterPaused: true },
+ });
+ mocks.read.mockResolvedValue({
+ title: "Repository title",
+ description: "Repository body",
+ state,
+ updatedAt: "remote-time",
+ labels: [],
+ });
+ const review = await reviewSyncResume(f.project.id, type, link.id);
+ await resumeSync(f.project.id, type, link.id, review.token, "provider");
+ expect(
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, f.task.id),
+ }),
+ ).toMatchObject({ status: "mapped", columnId: target.id });
+ expect(mocks.write).not.toHaveBeenCalled();
+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(true);
+ },
+ );
+
it.each(["kaneo", "provider"] as const)(
"preserves unreviewed fields after resuming with %s and accepts later label changes",
async (source) => {
diff --git a/tests/api-integration/integration-sync-rules.test.ts b/tests/api-integration/integration-sync-rules.test.ts
index 269d9a5c0..efa8e5e6c 100644
--- a/tests/api-integration/integration-sync-rules.test.ts
+++ b/tests/api-integration/integration-sync-rules.test.ts
@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as events from "../../apps/api/src/events";
import * as assets from "../../apps/api/src/storage/cleanup-assets";
import { handleGitlabIssueReopened } from "../../apps/api/src/plugins/gitlab/webhooks/issue-reopened";
-import db, { schema } from "../../apps/api/src/database";
+import db, { getDatabase, schema } from "../../apps/api/src/database";
import { createApp } from "../../apps/api/src/index";
import { getSyncIntegration } from "../../apps/api/src/integration-sync/controllers/get-integration";
import { previewSyncRules } from "../../apps/api/src/integration-sync/controllers/preview-rules";
@@ -690,59 +690,142 @@ describe("reviewed sync resume", () => {
expect(provider.write).not.toHaveBeenCalled();
});
- it("locks local values, integration, labels and link while writing to the provider", async () => {
+ it.each(["task", "integration", "labels", "link"] as const)(
+ "allows %s edits during a provider write and retains an uncertain paused link",
+ async (change) => {
+ const f = await paused();
+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ provider.write.mockImplementation(async () => {
+ await gate;
+ return { updatedAt: "2026-01-02T00:00:00Z" };
+ });
+ const resume = resumeSync(
+ f.project.id,
+ "gitea",
+ f.link.id,
+ review.token,
+ "kaneo",
+ ).then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+ try {
+ await vi.waitFor(() => expect(provider.write).toHaveBeenCalledOnce());
+ const attempts = {
+ task: (tx: typeof db) =>
+ tx
+ .update(schema.taskTable)
+ .set({ title: "Concurrent edit" })
+ .where(eq(schema.taskTable.id, f.task.id)),
+ integration: (tx: typeof db) =>
+ tx
+ .update(schema.integrationTable)
+ .set({ isActive: false })
+ .where(eq(schema.integrationTable.id, f.integration.id)),
+ labels: (tx: typeof db) =>
+ tx
+ .delete(schema.labelTable)
+ .where(eq(schema.labelTable.taskId, f.task.id)),
+ link: (tx: typeof db) =>
+ tx
+ .update(schema.externalLinkTable)
+ .set({ metadata: "{}" })
+ .where(eq(schema.externalLinkTable.id, f.link.id)),
+ };
+ await db.transaction(async (tx) => {
+ await tx.execute(sql`set local lock_timeout = '1s'`);
+ await attempts[change](tx as typeof db);
+ });
+ const activity = await db.execute<{ count: number }>(sql`
+ select count(*)::int as count from pg_stat_activity
+ where datname = current_database() and state = 'idle in transaction'
+ `);
+ expect(activity.rows[0]!.count).toBe(0);
+ } finally {
+ release();
+ }
+ expect(await resume).toMatchObject({ status: 409 });
+ const stored = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, f.link.id),
+ });
+ expect(JSON.parse(stored!.metadata!)).toMatchObject({
+ syncFilterPaused: true,
+ syncResumeUncertain: true,
+ });
+ if (change === "task")
+ expect(
+ await db.query.taskTable.findFirst({
+ where: eq(schema.taskTable.id, f.task.id),
+ }),
+ ).toMatchObject({ title: "Concurrent edit" });
+ },
+ );
+
+ it("allows task edits during the provider read and rejects the stale comparison before dispatch", async () => {
const f = await paused();
const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
- provider.write.mockImplementation(async () => {
+ provider.read.mockImplementationOnce(async () => {
await gate;
- return { updatedAt: "2026-01-02T00:00:00Z" };
+ return { ...review.remote, updatedAt: review.remoteIssueUpdatedAt };
});
+ provider.read.mockClear();
const resume = resumeSync(
f.project.id,
"gitea",
f.link.id,
review.token,
"kaneo",
+ ).then(
+ () => undefined,
+ (error: unknown) => error,
);
try {
- await vi.waitFor(() => expect(provider.write).toHaveBeenCalledOnce());
- const attempts = [
- (tx: typeof db) =>
- tx
- .update(schema.taskTable)
- .set({ title: "Concurrent edit" })
- .where(eq(schema.taskTable.id, f.task.id)),
- (tx: typeof db) =>
- tx
- .update(schema.integrationTable)
- .set({ isActive: false })
- .where(eq(schema.integrationTable.id, f.integration.id)),
- (tx: typeof db) =>
- tx
- .delete(schema.labelTable)
- .where(eq(schema.labelTable.taskId, f.task.id)),
- (tx: typeof db) =>
- tx
- .update(schema.externalLinkTable)
- .set({ metadata: "{}" })
- .where(eq(schema.externalLinkTable.id, f.link.id)),
- ];
- for (const apply of attempts)
- await expect(
- db.transaction(async (tx) => {
- await tx.execute(sql`set local lock_timeout = '100ms'`);
- await apply(tx as typeof db);
- }),
- ).rejects.toMatchObject({ cause: { code: "55P03" } });
+ await vi.waitFor(() => expect(provider.read).toHaveBeenCalledOnce());
+ await db.transaction(async (tx) => {
+ await tx.execute(sql`set local lock_timeout = '1s'`);
+ await tx
+ .update(schema.taskTable)
+ .set({ title: "Edited during read" })
+ .where(eq(schema.taskTable.id, f.task.id));
+ });
} finally {
release();
- await resume;
}
- expect(await canSyncTask(f.task.id, f.integration.id)).toBe(true);
+ expect(await resume).toMatchObject({ status: 409 });
+ expect(provider.write).not.toHaveBeenCalled();
+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(false);
+ });
+
+ it("records an uncertain provider write when the dispatch transaction fails", async () => {
+ const f = await paused();
+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);
+ const transaction = getDatabase().transaction.bind(getDatabase());
+ vi.spyOn(getDatabase(), "transaction").mockImplementationOnce(
+ (apply, config) =>
+ transaction(async (tx) => {
+ await apply(tx);
+ throw new Error("Injected dispatch transaction failure");
+ }, config),
+ );
+ await expect(
+ resumeSync(f.project.id, "gitea", f.link.id, review.token, "kaneo"),
+ ).rejects.toThrow("Injected dispatch transaction failure");
+ expect(provider.write).toHaveBeenCalledOnce();
+ const stored = await db.query.externalLinkTable.findFirst({
+ where: eq(schema.externalLinkTable.id, f.link.id),
+ });
+ expect(JSON.parse(stored!.metadata!)).toMatchObject({
+ syncFilterPaused: true,
+ syncResumeUncertain: true,
+ });
});
it.each(["planned", "archived"])(