Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion apps/api/src/services/channel-account-purge.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
62 changes: 62 additions & 0 deletions apps/api/src/services/contact-merge.service.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
28 changes: 20 additions & 8 deletions apps/api/src/services/contact-merge.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
})
Expand Down Expand Up @@ -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,
Expand All @@ -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")
Expand All @@ -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,
}));
}

Expand Down Expand Up @@ -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",
);
Expand Down Expand Up @@ -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(),
})
Expand Down
6 changes: 5 additions & 1 deletion apps/api/src/services/whatsapp/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions packages/database/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Date>;
updated_at: Generated<Date>;
Expand Down
54 changes: 54 additions & 0 deletions packages/database/src/contact-active-merge-event-schema.ts
Original file line number Diff line number Diff line change
@@ -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>(
db: Kysely<DB>,
schemaName: string,
): Promise<void> {
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);
}
36 changes: 36 additions & 0 deletions packages/database/src/migrations/118_track_active_merge_event.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>): Promise<void> {
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<void> {
throw new Error("migration 118 is forward-only");
}
4 changes: 4 additions & 0 deletions packages/database/src/tenant-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -2165,6 +2167,8 @@ export async function reconcileTenantSchema<Database>(
// 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
Expand Down