From fb555f65a6f8f3b733eca076f5fe90be88b045d3 Mon Sep 17 00:00:00 2001 From: setkyar Date: Thu, 12 Nov 2026 16:33:21 +0700 Subject: [PATCH] fix(api): only reverse the merge that is in effect unmergeContacts decided whether a merge was still in effect by checking that the source still pointed at the event's target. Merging, unmerging and merging the same pair again leaves two events with one target, so the older, already-reversed event passed the check: undoing it revived the source and orphaned the newer merge, which could then never be reversed. Record the event in effect on the contact (active_merge_event_id, set on merge and cleared on unmerge), check it under a row lock, and report reversibility in the merge history from the same pointer. Purges that separate aliases clear it too, and the foreign key is ON DELETE SET NULL, so a purged event can never be reversed. Migration 118 adds the column, key and index to existing tenants and backfills the newest matching event for contacts that are still merged; new tenants get the same through tenant-schema reconciliation. Fixes #378 --- .../services/channel-account-purge.service.ts | 6 +- .../contact-merge.service.integration.test.ts | 62 +++++++++++++++++++ .../api/src/services/contact-merge.service.ts | 28 ++++++--- apps/api/src/services/whatsapp/connection.ts | 6 +- packages/database/src/client.ts | 2 + .../src/contact-active-merge-event-schema.ts | 54 ++++++++++++++++ .../118_track_active_merge_event.ts | 36 +++++++++++ packages/database/src/tenant-schema.ts | 4 ++ 8 files changed, 188 insertions(+), 10 deletions(-) create mode 100644 packages/database/src/contact-active-merge-event-schema.ts create mode 100644 packages/database/src/migrations/118_track_active_merge_event.ts diff --git a/apps/api/src/services/channel-account-purge.service.ts b/apps/api/src/services/channel-account-purge.service.ts index 689eb45f..b8401673 100644 --- a/apps/api/src/services/channel-account-purge.service.ts +++ b/apps/api/src/services/channel-account-purge.service.ts @@ -191,7 +191,11 @@ export async function purgeArchivedChannelAccount( .execute(); separatedContacts = await trx .updateTable("contacts") - .set({ merged_into_contact_id: null, updated_at: new Date() }) + .set({ + merged_into_contact_id: null, + active_merge_event_id: null, + updated_at: new Date(), + }) .where("merged_into_contact_id", "in", contactIds) // A customer that is itself being purged is deleted, not separated. // Reporting it would tell an operator a customer came back when the diff --git a/apps/api/src/services/contact-merge.service.integration.test.ts b/apps/api/src/services/contact-merge.service.integration.test.ts index ad09e119..b93e254a 100644 --- a/apps/api/src/services/contact-merge.service.integration.test.ts +++ b/apps/api/src/services/contact-merge.service.integration.test.ts @@ -8,6 +8,7 @@ import { sql } from "kysely"; import { ConflictError, ValidationError } from "../lib/errors.js"; import { resolveWorkflowIdentity } from "./channel-workflow.service.js"; import { + listMergeHistory, mergeContacts, resolveCanonicalContactId, suggestContactMerges, @@ -533,6 +534,67 @@ describe("unmergeContacts", () => { reason: "no such event", }), ).rejects.toBeInstanceOf(ValidationError); + + // #378: merge A, unmerge A, merge B over the same pair. Both events + // name the same survivor, so the survivor alone cannot tell them + // apart; only B is in effect and only B may be reversed. + await tenantDb + .updateTable("contact_endpoints") + .set({ contact_id: source.id }) + .where("id", "=", sourceEndpoint.id) + .execute(); + const third = await mergeContacts(tenantDb, { + sourceContactId: source.id, + targetContactId: target.id, + actorUserId: ownerId, + reason: "merged a third time", + }); + const history = await listMergeHistory(tenantDb, target.id); + expect( + history.map(({ mergeEventId, reversible }) => [ + mergeEventId, + reversible, + ]), + ).toEqual([ + [third.mergeEventId, true], + [second.mergeEventId, false], + [merge.mergeEventId, false], + ]); + for (const stale of [merge.mergeEventId, second.mergeEventId]) { + await expect( + unmergeContacts(tenantDb, { + mergeEventId: stale, + actorUserId: ownerId, + reason: "reverse an old merge", + }), + ).rejects.toBeInstanceOf(ValidationError); + } + // The refused attempts changed nothing: the source is still merged, + // and the endpoint is still where the in-effect merge put it. + expect( + ( + await tenantDb + .selectFrom("contacts") + .select("merged_into_contact_id") + .where("id", "=", source.id) + .executeTakeFirstOrThrow() + ).merged_into_contact_id, + ).toBe(target.id); + expect( + ( + await tenantDb + .selectFrom("contact_endpoints") + .select("contact_id") + .where("id", "=", sourceEndpoint.id) + .executeTakeFirstOrThrow() + ).contact_id, + ).toBe(target.id); + const current = await unmergeContacts(tenantDb, { + mergeEventId: third.mergeEventId, + actorUserId: ownerId, + reason: "reverse the merge in effect", + }); + expect(current.restoredEndpoints).toBe(1); } finally { clearTenantConnection(companyId); await sql diff --git a/apps/api/src/services/contact-merge.service.ts b/apps/api/src/services/contact-merge.service.ts index 94a4a31e..6a58831b 100644 --- a/apps/api/src/services/contact-merge.service.ts +++ b/apps/api/src/services/contact-merge.service.ts @@ -164,6 +164,7 @@ export async function mergeContacts( .updateTable("contacts") .set({ merged_into_contact_id: target.id, + active_merge_event_id: mergeEvent.id, archived_at: new Date(), updated_at: new Date(), }) @@ -213,9 +214,10 @@ export interface MergeHistoryEntry { * records were folded together, who decided it, or what to reverse. Showing * the event id is not enough - the name is what makes the decision legible. * - * `reversible` mirrors what the unmerge path will actually accept: the source - * must still point at this target. A source that was merged on again, or - * already restored, is reported as a fact of history rather than as an action. + * `reversible` mirrors what the unmerge path will actually accept: this must + * be the merge in effect for the source. A source that was merged again, even + * into the same customer, or already restored, is reported as a fact of + * history rather than as an action. */ export async function listMergeHistory( db: MergeDb, @@ -234,7 +236,7 @@ export async function listMergeHistory( "source.push_name as push_name", "source.display_name as display_name", "source.phone_number as phone_number", - "source.merged_into_contact_id as merged_into_contact_id", + "source.active_merge_event_id as active_merge_event_id", ]) .where("event.target_contact_id", "=", targetContactId) .orderBy("event.created_at", "desc") @@ -251,7 +253,7 @@ export async function listMergeHistory( actorUserId: row.actor_user_id, reason: row.reason, mergedAt: row.created_at, - reversible: row.merged_into_contact_id === targetContactId, + reversible: row.active_merge_event_id === row.merge_event_id, })); } @@ -287,16 +289,25 @@ export async function unmergeContacts( } const source = await trx .selectFrom("contacts") - .select(["id", "merged_into_contact_id"]) + .select(["id", "merged_into_contact_id", "active_merge_event_id"]) .where("id", "=", mergeEvent.source_contact_id) + // Two concurrent unmerges of the same event must not both pass the + // check below and replay the endpoints twice. + .forUpdate() .executeTakeFirst(); if (!source) { throw new ValidationError("The merged-away contact no longer exists"); } // Only the merge that is currently in effect can be corrected. If the // source was merged again afterwards, undoing this older event would - // revive it into a state that no longer describes anything. - if (source.merged_into_contact_id !== mergeEvent.target_contact_id) { + // revive it into a state that no longer describes anything. The survivor + // alone cannot tell: merge, unmerge, and merge again into the same + // customer leaves two events with one target (#378). A pointer that was + // never set, or cleared by a purge, fails closed. + if ( + source.active_merge_event_id !== mergeEvent.id || + source.merged_into_contact_id !== mergeEvent.target_contact_id + ) { throw new ValidationError( "This merge has already been superseded and cannot be reversed", ); @@ -351,6 +362,7 @@ export async function unmergeContacts( .updateTable("contacts") .set({ merged_into_contact_id: null, + active_merge_event_id: null, archived_at: null, updated_at: new Date(), }) diff --git a/apps/api/src/services/whatsapp/connection.ts b/apps/api/src/services/whatsapp/connection.ts index 7ffffefb..33b25b0d 100644 --- a/apps/api/src/services/whatsapp/connection.ts +++ b/apps/api/src/services/whatsapp/connection.ts @@ -450,7 +450,11 @@ export async function purgeArchivedConnection( // would still point at a row about to disappear. const separatedContacts = await trx .updateTable("contacts") - .set({ merged_into_contact_id: null, updated_at: new Date() }) + .set({ + merged_into_contact_id: null, + active_merge_event_id: null, + updated_at: new Date(), + }) .where("merged_into_contact_id", "in", purgedContacts) // A customer on this connection is deleted, not separated. Reporting it // would tell an operator a customer came back when the row disappeared diff --git a/packages/database/src/client.ts b/packages/database/src/client.ts index f72b3af6..3d0e1b0f 100644 --- a/packages/database/src/client.ts +++ b/packages/database/src/client.ts @@ -834,6 +834,8 @@ export interface ContactsTable { avatar_url: string | null; record_kind: "customer" | "legacy_group_projection" | null; merged_into_contact_id: string | null; + /** The merge event in effect while merged_into_contact_id is set. */ + active_merge_event_id: string | null; archived_at: Date | null; created_at: Generated; updated_at: Generated; diff --git a/packages/database/src/contact-active-merge-event-schema.ts b/packages/database/src/contact-active-merge-event-schema.ts new file mode 100644 index 00000000..1f26b441 --- /dev/null +++ b/packages/database/src/contact-active-merge-event-schema.ts @@ -0,0 +1,54 @@ +import { type Kysely, sql } from "kysely"; + +/** Index names must stay under PostgreSQL's 63-byte identifier limit. */ +export const CONTACT_ACTIVE_MERGE_EVENT_INDEX = (schemaName: string): string => + `${schemaName}_active_merge_idx`; + +/** + * Migration 118 and new-tenant reconciliation share this additive upgrade. + * + * `merged_into_contact_id` names the survivor, not the merge that put the + * contact there, and two merge events can share a survivor (merge A, unmerge + * A, merge B). `active_merge_event_id` names the one in effect, so only that + * merge can be reversed. + * + * ON DELETE SET NULL rather than RESTRICT: the connection and channel-account + * purges delete merge events while a contact on another connection may still + * point at one, and a RESTRICT key would make those purges fail. A cleared + * pointer fails closed - the merge can no longer be reversed. + * + * The partial index serves that foreign key; without it every merge-event + * delete scans the contact table. It is built non-concurrently, as migration + * 107's is, because only merged rows enter it. + */ +export async function ensureContactActiveMergeEventSchema( + db: Kysely, + schemaName: string, +): Promise { + const contacts = sql.table(`${schemaName}.contacts`); + const events = sql.table(`${schemaName}.contact_merge_events`); + await sql`ALTER TABLE ${contacts} + ADD COLUMN IF NOT EXISTS active_merge_event_id UUID`.execute(db); + const constraint = await sql<{ exists: boolean }>` + SELECT EXISTS ( + SELECT 1 + FROM pg_constraint AS constraint_record + JOIN pg_class AS table_record ON table_record.oid = constraint_record.conrelid + JOIN pg_namespace AS schema_record ON schema_record.oid = table_record.relnamespace + WHERE schema_record.nspname = ${schemaName} + AND table_record.relname = 'contacts' + AND constraint_record.conname = 'contacts_active_merge_event_fk' + ) AS exists + `.execute(db); + if (!constraint.rows[0]?.exists) { + await sql`ALTER TABLE ${contacts} + ADD CONSTRAINT contacts_active_merge_event_fk + FOREIGN KEY (active_merge_event_id) REFERENCES ${events}(id) + ON DELETE SET NULL`.execute(db); + } + await sql` + CREATE INDEX IF NOT EXISTS ${sql.ref(CONTACT_ACTIVE_MERGE_EVENT_INDEX(schemaName))} + ON ${contacts} (active_merge_event_id) + WHERE active_merge_event_id IS NOT NULL + `.execute(db); +} diff --git a/packages/database/src/migrations/118_track_active_merge_event.ts b/packages/database/src/migrations/118_track_active_merge_event.ts new file mode 100644 index 00000000..0a9d28c9 --- /dev/null +++ b/packages/database/src/migrations/118_track_active_merge_event.ts @@ -0,0 +1,36 @@ +import { type Kysely, sql } from "kysely"; +import { ensureContactActiveMergeEventSchema } from "../contact-active-merge-event-schema.js"; +import { executeOnAllTenants } from "./migration-helpers.js"; + +/** + * Record which merge is in effect for a merged-away contact (#378), and + * backfill it for contacts merged before the column existed. + * + * A merge only happens to an unmerged contact and an unmerge clears the + * alias, so for a contact that is still merged the newest event moving it + * into its current survivor is the one in effect. + */ +export async function up(db: Kysely): Promise { + await executeOnAllTenants(db, async (schemaName) => { + await ensureContactActiveMergeEventSchema(db, schemaName); + const contacts = sql.table(`${schemaName}.contacts`); + const events = sql.table(`${schemaName}.contact_merge_events`); + await sql` + UPDATE ${contacts} AS source + SET active_merge_event_id = ( + SELECT merge_event.id + FROM ${events} AS merge_event + WHERE merge_event.source_contact_id = source.id + AND merge_event.target_contact_id = source.merged_into_contact_id + ORDER BY merge_event.created_at DESC, merge_event.id DESC + LIMIT 1 + ) + WHERE source.merged_into_contact_id IS NOT NULL + AND source.active_merge_event_id IS NULL + `.execute(db); + }); +} + +export async function down(): Promise { + throw new Error("migration 118 is forward-only"); +} diff --git a/packages/database/src/tenant-schema.ts b/packages/database/src/tenant-schema.ts index 2b1124c6..0e286fb9 100644 --- a/packages/database/src/tenant-schema.ts +++ b/packages/database/src/tenant-schema.ts @@ -5,6 +5,7 @@ import type { TenantDatabase } from "./client"; import { ensureConnectionAlertMessageIdSchema } from "./connection-alert-message-id-schema.js"; import { ensureConnectionAlertSchema } from "./connection-alert-schema.js"; import { ensureConnectionSystemNotificationSchema } from "./connection-system-notification-schema.js"; +import { ensureContactActiveMergeEventSchema } from "./contact-active-merge-event-schema.js"; import { installOutboxDispatchTrigger, installOutboxRecipientIndex, @@ -388,6 +389,7 @@ export const TENANT_SCHEMA_CONTRACT = { "avatar_url", "record_kind", "merged_into_contact_id", + "active_merge_event_id", "archived_at", "created_at", "updated_at", @@ -2165,6 +2167,8 @@ export async function reconcileTenantSchema( // reads/writes remain authoritative until workspace flags enable later // phases. await ensureChannelSpineTenantSchema(db, schemaName); + // Migration 118 parity; needs contact_merge_events from the spine schema. + await ensureContactActiveMergeEventSchema(db, schemaName); // Migration 063 parity. The historical index names above overflow // PostgreSQL's 63-byte identifier limit once a 43-character tenant schema