fix(backup): explain a second restore of one file into another account

Restored rows keep the ids they had in the file. Once an erased
account's copy had gone into one account, the same file uploaded into a
second account restored into a primary-key conflict, reported only as
the generic "the database rejected a record" failure.

For a copy put into a chosen account, a primary-key conflict now ends
the restore with backup.restore.rows_exist_elsewhere and a sentence that
says the file was most likely restored into another account already.
The transaction still rolls back, so neither account changes. The code
is in the catalogue, the console names it, and the runbook says a file
goes into one account only.
This commit is contained in:
Marc-André Bombeck committed 2026-10-29 21:50:34 +01:00
1 parent 94854bd8f7
commit c920266f32
20 files changed
+183 -35

No files matched your search

@@ -98,6 +98,8 @@ function failureText(
});
case "backup.foreign_reference":
return t("admin.section.backups.restoreFailureForeignReference");
case "backup.restore.rows_exist_elsewhere":
return t("admin.section.backups.restoreFailureRowsElsewhere");
case "time_budget":
return t("admin.section.backups.restoreFailureTimeBudget");
case "transaction_failed":
@@ -15,6 +15,7 @@ import { describe, expect, it } from "vitest";
import {
classifyRestoreFailure,
isPrimaryKeyConflict,
RESTORE_FAILURE_CAUSE_MESSAGES,
RESTORE_FAILURE_CAUSES,
} from "@/lib/export/restore-failure-cause";
@@ -147,3 +148,43 @@ describe("classifyRestoreFailure", () => {
}
});
});
describe("isPrimaryKeyConflict", () => {
it("names a duplicate primary key, as the driver reports it", () => {
expect(
isPrimaryKeyConflict(
adapterError("P2010", "23505", {
kind: "UniqueConstraintViolation",
constraint: { index: "measurements_pkey" },
}),
),
).toBe(true);
// Without the structured name, read from the message.
expect(
isPrimaryKeyConflict(
adapterError("P2010", "23505", {
originalMessage:
'duplicate key value violates unique constraint "mood_entries_pkey"',
}),
),
).toBe(true);
});
it("does not name another unique rule, or another failure", () => {
expect(
isPrimaryKeyConflict(
adapterError("P2002", "23505", {
constraint: { index: "measurements_user_id_external_id_key" },
}),
),
).toBe(false);
expect(
isPrimaryKeyConflict(
adapterError("P2010", "23503", {
constraint: { index: "measurements_pkey" },
}),
),
).toBe(false);
expect(isPrimaryKeyConflict(new Error("measurements_pkey"))).toBe(false);
});
});
+23 -1
View File
@@ -49,6 +49,7 @@ import {
import {
classifyRestoreFailure,
RESTORE_FAILURE_CAUSE_MESSAGES,
isPrimaryKeyConflict,
} from "@/lib/export/restore-failure-cause";
import { takeRestoreLock } from "@/lib/export/restore-lock";
import {
@@ -135,6 +136,9 @@ export type RestoreProgressSink = (
* before the first delete or rolls the whole transaction back, so each means
* the account is unchanged.
*/
/** A retargeted copy whose rows another account already holds. */
const ROWS_EXIST_ELSEWHERE_CODE = "backup.restore.rows_exist_elsewhere";
export type RestoreFailureCode =
| "backup_not_found"
| "backup_changed"
@@ -147,6 +151,7 @@ export type RestoreFailureCode =
| "document_ciphertext_missing"
| "backup.key.missing"
| "backup.foreign_reference"
| "backup.restore.rows_exist_elsewhere"
| "time_budget"
| "transaction_failed"
| "interrupted"
@@ -345,6 +350,7 @@ async function transactionRefusal(
input: RestoreBackupInput,
ownerId: string,
transactionTimeoutMs: number,
retargeted: boolean,
err: unknown,
): Promise<RestoreBackupOutcome> {
const verbose = err instanceof Error ? err.message : String(err);
@@ -375,6 +381,16 @@ async function transactionRefusal(
references: err.edges,
});
}
if (retargeted && isPrimaryKeyConflict(err)) {
// Rows keep their ids from the file, so the copy of an erased account
// can live in one account only. Rolled back, so nothing was changed.
return refused(
409,
ROWS_EXIST_ELSEWHERE_CODE,
"Records in this copy are already in this database, so the file was most likely already restored into another account. A file can be restored into one account only. Nothing was changed.",
{ errorCode: ROWS_EXIST_ELSEWHERE_CODE },
);
}
if (isStoredBackupReadError(err)) {
// The second read, inside the transaction, found the copy replaced or
// altered. The transaction rolled back, so nothing was changed.
@@ -614,7 +630,13 @@ export async function restoreBackup(
prepass,
);
} catch (err) {
return transactionRefusal(input, owner.id, transactionTimeoutMs, err);
return transactionRefusal(
input,
owner.id,
transactionTimeoutMs,
retargeted,
err,
);
}
const response = await afterCommit(input, read, owner, result, tracker);
+19
View File
@@ -108,6 +108,25 @@ export function classifyRestoreFailure(err: unknown): ClassifiedRestoreFailure {
return { cause: "other", code: prisma };
}
/**
* Whether a restore failed because a row it inserted carries a primary key
* already taken. The restore deletes the receiving account's own rows first,
* so the key belongs to a row of another account: for a copy put into a
* chosen account, the same file restored into a different account before.
*/
export function isPrimaryKeyConflict(err: unknown): boolean {
if (sqlState(err) !== "23505") return false;
const cause = field(field(field(err, "meta"), "driverAdapterError"), "cause");
const index = field(field(cause, "constraint"), "index");
const name =
typeof index === "string"
? index
: /unique constraint "([^"]+)"/.exec(
String(field(cause, "originalMessage") ?? field(err, "message")),
)?.[1];
return typeof name === "string" && name.endsWith("_pkey");
}
/** The sentence the job row and the audit trail carry for each cause. */
export const RESTORE_FAILURE_CAUSE_MESSAGES: Record<
RestoreFailureCause,
@@ -39,6 +39,7 @@ const CODE_TABLE: Record<BackupRestoreFailureCode, true> = {
document_ciphertext_missing: true,
"backup.key.missing": true,
"backup.foreign_reference": true,
"backup.restore.rows_exist_elsewhere": true,
time_budget: true,
transaction_failed: true,
interrupted: true,
+1
View File
@@ -104,6 +104,7 @@ export const ERROR_CODE_CATALOGUE: Readonly<Record<string, readonly string[]>> =
"backup.owner.missing",
"backup.payload.undecryptable",
"backup.restore.active",
"backup.restore.rows_exist_elsewhere",
"backup.section.missing",
"backup.target.admin_account",
"backup.target.holds_records",
+1 -1
View File
@@ -96,7 +96,7 @@ const restoreFailure = z
.object({
code: z.string().meta({
description:
"Stable reason: `backup_not_found`, `backup_changed`, `backup.payload.undecryptable`, `schema_invalid`, `incompatible_schema_version`, `owner_mismatch`, `owner_not_found`, `backup.section.missing`, `document_ciphertext_missing`, `backup.key.missing`, `backup.foreign_reference`, `time_budget`, `transaction_failed`, `interrupted`, `not_started`, `enqueue_failed`, `failed_after_commit`, `unexpected`. Every code but `failed_after_commit` means the account was not changed.",
"Stable reason: `backup_not_found`, `backup_changed`, `backup.payload.undecryptable`, `schema_invalid`, `incompatible_schema_version`, `owner_mismatch`, `owner_not_found`, `backup.section.missing`, `document_ciphertext_missing`, `backup.key.missing`, `backup.foreign_reference`, `backup.restore.rows_exist_elsewhere` (a copy put into a chosen account whose records another account already holds, because the same file was restored there before), `time_budget`, `transaction_failed`, `interrupted`, `not_started`, `enqueue_failed`, `failed_after_commit`, `unexpected`. Every code but `failed_after_commit` means the account was not changed.",
}),
message: z.string(),
sections: z.array(z.string()).optional(),