Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): refuse a second replace-all import while one is running

Yudhi Armyndharisddc350f093e6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c0baf1735..2e7c3ba73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A second data import while one is running is now refused with `409`** — on SQLite both shared a single transaction, so the second one's rollback discarded a restore the first had already reported as successful.
- **A replace-all data import no longer disturbs the engines it left running** — the restore dropped each session's ownership lease and, on SQLite, the heartbeat could read the half-applied transaction, so a renewal concluded the claim was lost and tore down engines that had never stopped.
## [0.14.2] - 2026-08-06
diff --git a/dashboard/src/hooks/useDataBackup.ts b/dashboard/src/hooks/useDataBackup.ts
index 3d167471e..6a87e8b25 100644
--- a/dashboard/src/hooks/useDataBackup.ts
+++ b/dashboard/src/hooks/useDataBackup.ts
@@ -1,4 +1,5 @@
import { useState } from 'react';
+import { shouldOfferStopOrphansRetry } from '../utils/importRefusal';
import { useTranslation } from 'react-i18next';
import { infraApi } from '../services/api';
import { useToast } from './useToast';
@@ -42,11 +43,14 @@ export function useDataBackup(): DataBackup {
}
};
- // POST the replace-all restore and fold the backend's orphan-engine contract into the UI. A 409
- // means live engines exist for sessions the backup would remove (the server message lists them);
- // the contract's preferred retry is stopOrphans=true, which stops those engines inside the
- // request, so offer it as a confirm. force=true is deliberately not offered (the api client does
- // not even send it): it leaves the engines running until a restart.
+ // POST the replace-all restore and fold the backend's orphan-engine contract into the UI. The route
+ // answers 409 for TWO different reasons and they need opposite handling, so branch on the machine
+ // code, never on the status alone: IMPORT_ALREADY_RUNNING means another restore is in flight and
+ // there is nothing to decide (retrying with stopOrphans would run a second destructive replace the
+ // operator never asked for). The orphan case does have a decision — live engines exist for sessions
+ // the backup would remove — and its preferred retry is stopOrphans=true, which stops them inside
+ // the request, so that one is offered as a confirm. force=true is deliberately not offered (the api
+ // client does not even send it): it leaves the engines running until a restart.
const runImport = async (tables: Record<string, unknown[]>, stopOrphans = false): Promise<void> => {
try {
const res = await infraApi.importData(tables, stopOrphans ? { stopOrphans: true } : undefined);
@@ -66,7 +70,8 @@ export function useDataBackup(): DataBackup {
}
} catch (err) {
const status = (err as { status?: number } | null)?.status;
- if (status === 409 && !stopOrphans && err instanceof Error) {
+ const code = (err as { code?: string } | null)?.code;
+ if (shouldOfferStopOrphansRetry(status, code, stopOrphans) && err instanceof Error) {
// The confirm doubles as the refusal display: OK retries with stopOrphans=true, Cancel
// leaves the engines (and the current data) untouched. A 409 on the retry itself (an
// engine started mid-import) falls through to the plain error toast — no confirm loop.
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 3cd3f4a5d..18a1e6e99 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -1073,10 +1073,12 @@ export const infraApi = {
counts: Record<string, number>;
}>('/infra/export-data'),
// 200 contract includes the orphan-engine reconciliation result (restartRequired / notices /
- // stopped+failed ids). A 409 (live engines exist for sessions the backup would remove; the error
- // message lists them) is retried by the caller with stopOrphans=true, which stops those engines
- // inside the request. force is deliberately NOT exposed: it leaves the engines writing into the
- // restored tables until a restart — the window stopOrphans exists to close.
+ // stopped+failed ids). 409 has TWO causes and the error's `code` distinguishes them:
+ // IMPORT_ALREADY_RUNNING (another restore is in flight — nothing to retry), or the orphan case
+ // (live engines exist for sessions the backup would remove; the message lists them), which the
+ // caller retries with stopOrphans=true to stop those engines inside the request. force is
+ // deliberately NOT exposed: it leaves the engines writing into the restored tables until a
+ // restart — the window stopOrphans exists to close.
importData: (tables: Record<string, unknown[]>, options?: { stopOrphans?: boolean }) =>
request<{
imported: boolean;
diff --git a/dashboard/src/utils/importRefusal.test.ts b/dashboard/src/utils/importRefusal.test.ts
new file mode 100644
index 000000000..02bc10764
--- /dev/null
+++ b/dashboard/src/utils/importRefusal.test.ts
@@ -0,0 +1,32 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { shouldOfferStopOrphansRetry } from './importRefusal.ts';
+
+// The retry this predicate gates is DESTRUCTIVE: it re-POSTs the replace-all with stopOrphans=true,
+// which tears down live engines. Branching on the 409 status alone offered that retry from a dialog
+// whose message says "another import is already running; wait for it" — so OK read as an
+// acknowledgement and ran a second full replace nobody asked for.
+
+test('offers the retry for the orphan-engine refusal, which is a real decision', () => {
+ assert.equal(shouldOfferStopOrphansRetry(409, undefined, false), true);
+});
+
+test('never offers the retry when another import is already running', () => {
+ assert.equal(shouldOfferStopOrphansRetry(409, 'IMPORT_ALREADY_RUNNING', false), false);
+});
+
+test('does not loop: a 409 on the retry itself is not offered again', () => {
+ assert.equal(shouldOfferStopOrphansRetry(409, undefined, true), false);
+});
+
+test('leaves every other status alone', () => {
+ assert.equal(shouldOfferStopOrphansRetry(413, undefined, false), false);
+ assert.equal(shouldOfferStopOrphansRetry(500, undefined, false), false);
+ assert.equal(shouldOfferStopOrphansRetry(undefined, undefined, false), false);
+});
+
+test('an unknown future 409 code still gets the orphan treatment, not silence', () => {
+ // Fail toward showing the operator something actionable rather than swallowing a refusal we do
+ // not recognise; only the code we know needs no decision is excluded.
+ assert.equal(shouldOfferStopOrphansRetry(409, 'SOME_FUTURE_CODE', false), true);
+});
diff --git a/dashboard/src/utils/importRefusal.ts b/dashboard/src/utils/importRefusal.ts
new file mode 100644
index 000000000..d7abdad90
--- /dev/null
+++ b/dashboard/src/utils/importRefusal.ts
@@ -0,0 +1,22 @@
+/**
+ * POST /infra/import-data answers 409 for two unrelated reasons, and they need opposite handling.
+ *
+ * The orphan case is a DECISION: live engines exist for sessions the backup would remove, and the
+ * documented retry is `stopOrphans=true`, which stops them inside the request. Offering that as a
+ * confirm is right.
+ *
+ * IMPORT_ALREADY_RUNNING is not a decision — another restore is in flight and the caller can only
+ * wait. Retrying it with `stopOrphans` would run a second destructive replace-all the operator never
+ * asked for, from a dialog whose message says "wait". So the status alone must never drive the
+ * confirm; the machine code has to be read.
+ */
+export function shouldOfferStopOrphansRetry(
+ status: number | undefined,
+ code: string | undefined,
+ alreadyRetriedWithStopOrphans: boolean,
+): boolean {
+ if (status !== 409) return false;
+ // A 409 on the retry itself (an engine started mid-import) must not loop.
+ if (alreadyRetriedWithStopOrphans) return false;
+ return code !== 'IMPORT_ALREADY_RUNNING';
+}
diff --git a/openapi.json b/openapi.json
index 1a5015d1a..9b7a53506 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3410,7 +3410,7 @@
"description": "Data imported successfully"
},
"409": {
- "description": "Refused: live engines exist for sessions the backup would remove (retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after)"
+ "description": "Refused, for one of two reasons: another import is already running (code IMPORT_ALREADY_RUNNING — wait for it, do not retry immediately); or live engines exist for sessions the backup would remove (retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after)"
}
},
"summary": "Import data to Data DB (replaces existing data)",
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index f58bb5221..7610b6d5e 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -163,6 +163,34 @@ describe('InfraDataController.importData round-trips export-data (no silent mess
expect(held).toBe(0);
});
+ it('refuses a second concurrent import instead of letting two share one transaction', async () => {
+ await seedSession('s1');
+ const dump = await controller.exportData();
+
+ // Why this matters on the default dialect: BetterSqlite3Driver.createQueryRunner() returns a
+ // SINGLETON runner, so two overlapping imports share one transaction. The second startTransaction
+ // nests as SAVEPOINT, its commit issues RELEASE SAVEPOINT rather than COMMIT, and a rollback at
+ // depth 1 issues a full ROLLBACK — discarding a restore the other call already reported as
+ // imported:true.
+ //
+ // No gating needed to make this deterministic: the first call runs synchronously up to its first
+ // await, so the guard must be set before any await for the second call to see it. That ordering
+ // is the property under test as much as the 409 is.
+ const first = controller.importData({ tables: dump.tables });
+ const second = controller.importData({ tables: dump.tables });
+
+ await expect(second).rejects.toMatchObject({ status: 409 });
+ await expect(first).resolves.toMatchObject({ imported: true });
+ });
+
+ it('accepts an import again once the previous one has finished', async () => {
+ await seedSession('s1');
+ const dump = await controller.exportData();
+
+ await expect(controller.importData({ tables: dump.tables })).resolves.toMatchObject({ imported: true });
+ await expect(controller.importData({ tables: dump.tables })).resolves.toMatchObject({ imported: true });
+ });
+
it('releases the loss-detection token even when the transaction never opens', async () => {
await seedSession('s1');
const dump = await controller.exportData();
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.ts
index 926a05b32..482c566f8 100644
--- a/src/modules/infra/infra-data.controller.ts
+++ b/src/modules/infra/infra-data.controller.ts
@@ -99,6 +99,16 @@ const SHARED_CONNECTION_DIALECTS = new Set(['better-sqlite3', 'sqlite']);
export class InfraDataController {
private readonly logger = createLogger('InfraDataController');
+ /**
+ * Whether a replace-all import is already running in this process. Not a nicety: on better-sqlite3
+ * every query runner is a driver SINGLETON, so two overlapping imports share one transaction — the
+ * second nests as SAVEPOINT, its commit issues RELEASE SAVEPOINT rather than COMMIT, and a rollback
+ * at depth 1 issues a full ROLLBACK that discards a restore the other call already answered
+ * `imported: true` for. Serialising them is the only honest answer; queueing the second would still
+ * run a destructive replace nobody is waiting on.
+ */
+ private importInFlight = false;
+
constructor(
private readonly configService: ConfigService,
@InjectDataSource('data')
@@ -278,7 +288,7 @@ export class InfraDataController {
@ApiResponse({
status: 409,
description:
- 'Refused: live engines exist for sessions the backup would remove (retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after)',
+ 'Refused, for one of two reasons: another import is already running (code IMPORT_ALREADY_RUNNING — wait for it, do not retry immediately); or live engines exist for sessions the backup would remove (retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after)',
})
async importData(
@Body()
@@ -311,6 +321,37 @@ export class InfraDataController {
stoppedOrphanEngines: string[];
/** Orphan engines whose teardown threw or timed out (Map reconciled regardless; investigate). */
failedOrphanEngines: string[];
+ }> {
+ // Check-and-set with NO await between them, so the single-threaded event loop makes this atomic:
+ // the first call reaches the assignment before the second call starts. It guards the whole method,
+ // including the pre-flight orphan teardown below — running that twice concurrently would stop
+ // engines on behalf of a restore that is about to be refused.
+ if (this.importInFlight) {
+ throw new ConflictException({
+ statusCode: 409,
+ error: 'Conflict',
+ message: 'A data import is already running; wait for it to finish before starting another.',
+ code: 'IMPORT_ALREADY_RUNNING',
+ });
+ }
+ this.importInFlight = true;
+ try {
+ return await this.runImport(data);
+ } finally {
+ this.importInFlight = false;
+ }
+ }
+
+ /** The replace-all restore itself. Only ever entered through importData's single-flight guard. */
+ private async runImport(data: { tables: Partial<MigrationTables>; force?: boolean; stopOrphans?: boolean }): Promise<{
+ imported: boolean;
+ counts: TableCounts;
+ warnings: string[];
+ notices: string[];
+ restartRequired: boolean;
+ orphanedEngines: string[];
+ stoppedOrphanEngines: string[];
+ failedOrphanEngines: string[];
}> {
const warnings: string[] = [];