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): settle concurrent uncertainty at correction receipts

Tinb32b357c12d3
diff --git a/apps/api/src/plugins/github/services/deferred-issue-edits.ts b/apps/api/src/plugins/github/services/deferred-issue-edits.ts
index 848b9c31d..30c912b7c 100644
--- a/apps/api/src/plugins/github/services/deferred-issue-edits.ts
+++ b/apps/api/src/plugins/github/services/deferred-issue-edits.ts
@@ -360,6 +360,7 @@ export async function replayDeferredIssueEdits() {
: current[repair.field];
},
integration,
+ true,
);
// A later field can fail; persist this field's successful repair first.
if (repair.intentIds.length)
@@ -385,10 +386,24 @@ export async function replayDeferredIssueEdits() {
await withIntegrationLink(
link,
integration,
- async (tx) => {
+ async (tx, _afterCommit, locked) => {
+ // Writes settled after the receipt need their own later correction.
+ const current = metadataFor(locked);
+ const remaining = fields.filter(
+ (field) =>
+ uncertainOutboundIntents(current.lastSync?.[field]).length,
+ );
await updateExternalLink(
link.id,
- { completeDeferredEdit: job.id },
+ remaining.length
+ ? {
+ deferredEdit: {
+ fields: [],
+ repairFields: remaining,
+ scope: job.scope,
+ },
+ }
+ : { completeDeferredEdit: job.id },
tx,
);
},
diff --git a/apps/api/src/plugins/github/services/link-manager.ts b/apps/api/src/plugins/github/services/link-manager.ts
index 249899064..dd68670b9 100644
--- a/apps/api/src/plugins/github/services/link-manager.ts
+++ b/apps/api/src/plugins/github/services/link-manager.ts
@@ -5,7 +5,11 @@ import {
} from "../utils/deferred-issue-edit";
import { mergeSyncMetadata } from "../utils/merge-sync-metadata";
import { parseLinkMetadata } from "../utils/parse-link-metadata";
-import { outboundStamp, type SyncStamp } from "../utils/sync-echo";
+import {
+ outboundStamp,
+ uncertainOutboundIntents,
+ type SyncStamp,
+} from "../utils/sync-echo";
import { and, eq } from "drizzle-orm";
import db from "../../../database";
import {
@@ -35,6 +39,7 @@ export type UpdateExternalLinkParams = {
scope: string;
};
completeDeferredEdit?: string;
+ retireUncertainOutbound?: IssueField;
retireOutboundIntents?: { field: IssueField; intentIds: string[] };
outbound?: {
field: "title" | "description" | "state";
@@ -151,7 +156,8 @@ export async function updateExternalLink(
params.observedOutbound ||
params.deferredEdit ||
params.completeDeferredEdit ||
- params.retireOutboundIntents
+ params.retireOutboundIntents ||
+ params.retireUncertainOutbound
) {
return database.transaction(async (tx) => {
const link = await lockExternalLink(id, tx);
@@ -217,6 +223,16 @@ export async function updateExternalLink(
: entry,
);
}
+ if (params.retireUncertainOutbound) {
+ const stamp = merged.lastSync?.[params.retireUncertainOutbound];
+ const settled = new Set(uncertainOutboundIntents(stamp));
+ if (stamp)
+ stamp.outbound = stamp.outbound?.map((entry) =>
+ settled.has(entry)
+ ? { ...entry, pending: false, uncertain: false, cancelled: true }
+ : entry,
+ );
+ }
if (params.outbound) {
const { field, value, updatedAt, ...intent } = params.outbound;
merged.lastSync = {
diff --git a/apps/api/src/plugins/github/services/sync-latest-task-value.ts b/apps/api/src/plugins/github/services/sync-latest-task-value.ts
index b66020fbe..e7db76ba8 100644
--- a/apps/api/src/plugins/github/services/sync-latest-task-value.ts
+++ b/apps/api/src/plugins/github/services/sync-latest-task-value.ts
@@ -1,6 +1,10 @@
import { deferTaskSync } from "./defer-issue-edit";
import { randomUUID } from "node:crypto";
import db from "../../../database";
+import {
+ issueEditScope,
+ parseDeferredIssueEdit,
+} from "../utils/deferred-issue-edit";
import { parseLinkMetadata } from "../utils/parse-link-metadata";
import { hasNewerObservedEdit, type SyncStamp } from "../utils/sync-echo";
import { applyObservedTaskValue } from "./apply-observed-task-value";
@@ -21,6 +25,7 @@ export async function syncLatestTaskValue(
write: (value: string) => Promise<string | undefined>,
readCurrent?: () => Promise<string>,
expectedBinding?: { type?: string; config?: string },
+ repair = false,
) {
let value = initialValue;
let attempts = 0;
@@ -51,6 +56,19 @@ export async function syncLatestTaskValue(
identity ??= binding.integration
? { type: binding.integration.type, config: binding.integration.config }
: undefined;
+ const queued = parseDeferredIssueEdit(
+ parseLinkMetadata<{ deferredIssueEdit?: unknown }>(binding.metadata, {
+ externalLinkId: link.id,
+ source: "outbound_repair",
+ }).deferredIssueEdit,
+ );
+ const repairing =
+ repair ||
+ !!(
+ queued?.repairFields?.includes(field) &&
+ binding.integration &&
+ issueEditScope(binding.integration) === queued.scope
+ );
const intentId = randomUUID();
// Webhooks may arrive before PATCH returns, including from another instance.
const persisted = await updateExternalLink(link.id, {
@@ -78,12 +96,17 @@ export async function syncLatestTaskValue(
uncertain: !rejected,
},
}).catch(() => {});
+ if (!rejected && binding.integration?.config && (await currentBinding()))
+ await deferTaskSync({ id: link.id, taskId }, binding.integration, [
+ field,
+ ]).catch(() => {});
throw error;
}
if (!(await currentBinding())) return;
await updateExternalLink(link.id, {
...(field === "title" ? { title: value } : {}),
outbound: { field, value, updatedAt, intentId, pending: false },
+ ...(repairing ? { retireUncertainOutbound: field } : {}),
...(field === "state"
? { metadata: { state: value, lastOutboundStateSyncAt: Date.now() } }
: {}),
diff --git a/apps/api/src/plugins/github/utils/sync-echo.ts b/apps/api/src/plugins/github/utils/sync-echo.ts
index d0e9fb033..ca80894a5 100644
--- a/apps/api/src/plugins/github/utils/sync-echo.ts
+++ b/apps/api/src/plugins/github/utils/sync-echo.ts
@@ -197,14 +197,14 @@ export function hasNewerObservedEdit(
export function uncertainOutboundIntents(
stamp: SyncStamp | undefined,
- value: string,
+ value?: string,
) {
- const valueHash = hash(value);
+ const valueHash = value === undefined ? undefined : hash(value);
return (stamp?.outbound ?? []).filter(
(entry) =>
!entry.cancelled &&
- entry.hash === valueHash &&
- (entry.uncertain ||
+ (valueHash === undefined || entry.hash === valueHash) &&
+ ((!entry.pending && entry.uncertain) ||
(entry.pending && Date.now() - Date.parse(entry.timestamp) >= 300_000)),
);
}
diff --git a/tests/api-integration/deferred-issue-edits.test.ts b/tests/api-integration/deferred-issue-edits.test.ts
index 3963ac4d3..2d16db507 100644
--- a/tests/api-integration/deferred-issue-edits.test.ts
+++ b/tests/api-integration/deferred-issue-edits.test.ts
@@ -1281,7 +1281,7 @@ it.each(
);
it.each(["uncertain", "pending"])(
- "keeps a newer matching %s write that arrives while a queued repair is in flight",
+ "settles a matching %s write during repair while preserving active requests",
async (kind) => {
const { integration, link } = await seed();
await db
@@ -1319,12 +1319,12 @@ it.each(["uncertain", "pending"])(
entries.find((entry: { intentId: string }) => entry.intentId === "new"),
).toMatchObject({
pending: kind === "pending",
- uncertain: kind === "uncertain",
+ uncertain: false,
});
expect(
entries.find((entry: { intentId: string }) => entry.intentId === "new")
.cancelled,
- ).not.toBe(true);
+ ).toBe(kind === "uncertain" ? true : undefined);
},
);
it("retains every captured uncertain intent when the corrective provider write fails", async () => {
@@ -1503,3 +1503,188 @@ it.each(
).toBe(field === "state" ? "done" : before);
},
);
+
+it.each(providerFields)(
+ "settles a $provider/$field write that becomes uncertain during correction before later genuine edits",
+ async ({ provider, field }) => {
+ const { task, integration, link } = await seed(provider);
+ const older = field === "state" ? "closed" : "A";
+ await db
+ .update(schema.externalLinkTable)
+ .set({
+ metadata: JSON.stringify({
+ lastSync: {
+ [field]: outboundStamp(undefined, older, undefined, {
+ intentId: "old",
+ uncertain: true,
+ }),
+ },
+ }),
+ })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ await deferTaskSync(link, integration, [field]);
+ m.write.mockImplementationOnce(async () => {
+ await updateExternalLink(link.id, {
+ outbound: {
+ field,
+ value: older,
+ intentId: "during-repair",
+ pending: false,
+ uncertain: true,
+ },
+ });
+ return { updated_at: "2026-09-30T00:00:04Z" };
+ });
+ await replayDeferredIssueEdits();
+ const column = field === "state" ? "status" : field;
+ const later = field === "state" ? "open" : "C";
+ await db
+ .update(schema.taskTable)
+ .set({ [column]: field === "state" ? "in-progress" : later })
+ .where(eq(schema.taskTable.id, task.id));
+ await syncLatestTaskValue(
+ task.id,
+ integration.projectId,
+ link,
+ field,
+ later,
+ async () => "2026-09-30T00:00:05Z",
+ );
+ m.read.mockResolvedValue({
+ title: older,
+ body: older,
+ state: "closed",
+ updated_at: "2026-09-30T00:00:06Z",
+ });
+ await deliverField(
+ provider,
+ field,
+ older,
+ "2026-09-30T00:00:06Z",
+ integration.id,
+ );
+ expect((await current(task.id))?.[column]).toBe(
+ field === "state" ? "done" : older,
+ );
+ },
+);
+it("queues an intent inserted after the repair receipt for a fresh correction", async () => {
+ const { task, integration, link } = await seed();
+ await db
+ .update(schema.externalLinkTable)
+ .set({
+ metadata: JSON.stringify({
+ lastSync: {
+ title: outboundStamp(undefined, "A", undefined, {
+ intentId: "old",
+ uncertain: true,
+ }),
+ },
+ }),
+ })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ await deferTaskSync(link, integration, ["title"]);
+ const find = db.query.externalLinkTable.findMany.bind(
+ db.query.externalLinkTable,
+ );
+ let inserted = false;
+ const spy = vi
+ .spyOn(db.query.externalLinkTable, "findMany")
+ .mockImplementation(async (options) => {
+ const rows = await find(options);
+ if (
+ !inserted &&
+ m.write.mock.calls.length &&
+ rows.some(
+ (row) =>
+ JSON.parse(row.metadata ?? "{}").lastSync?.title?.value === "B",
+ )
+ ) {
+ inserted = true;
+ await updateExternalLink(link.id, {
+ outbound: {
+ field: "title",
+ value: "A",
+ intentId: "after-receipt",
+ pending: false,
+ uncertain: true,
+ },
+ });
+ return find(options);
+ }
+ return rows;
+ });
+ try {
+ await replayDeferredIssueEdits();
+ } finally {
+ spy.mockRestore();
+ }
+ expect(inserted).toBe(true);
+ expect((await metadata(link.id)).deferredIssueEdit.repairFields).toEqual([
+ "title",
+ ]);
+ await db
+ .update(schema.taskTable)
+ .set({ title: "C" })
+ .where(eq(schema.taskTable.id, task.id));
+ await syncLatestTaskValue(
+ task.id,
+ integration.projectId,
+ link,
+ "title",
+ "C",
+ async () => "2026-09-30T00:00:05Z",
+ );
+ m.read.mockResolvedValue({
+ title: "A",
+ body: "body",
+ state: "open",
+ updated_at: "2026-09-30T00:00:06Z",
+ });
+ await deliverField(
+ "github",
+ "title",
+ "A",
+ "2026-09-30T00:00:06Z",
+ integration.id,
+ );
+ expect((await current(task.id))?.title).toBe("A");
+});
+it("durably queues an uncertain standalone writer and later settles it", async () => {
+ const { task, integration, link } = await seed();
+ await db
+ .update(schema.externalLinkTable)
+ .set({ metadata: "{}" })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ await expect(
+ syncLatestTaskValue(
+ task.id,
+ integration.projectId,
+ link,
+ "title",
+ "A",
+ async () => {
+ throw new Error("provider unavailable");
+ },
+ ),
+ ).rejects.toThrow("provider unavailable");
+ expect((await metadata(link.id)).deferredIssueEdit.repairFields).toEqual([
+ "title",
+ ]);
+ await replayDeferredIssueEdits();
+ expect((await metadata(link.id)).deferredIssueEdit).toBeUndefined();
+ m.read.mockResolvedValue({
+ title: "A",
+ body: "body",
+ state: "open",
+ updated_at: "2026-09-30T00:00:06Z",
+ });
+ await deliverField(
+ "github",
+ "title",
+ "A",
+ "2026-09-30T00:00:06Z",
+ integration.id,
+ );
+ expect((await current(task.id))?.title).toBe("A");
+});