Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([merge-cascade-no-rollback]): make merge cascade resilient and resumable

[._.]/ Adam Eivy9631bb4adb01
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 9553c14bd4..fcf6b72a23 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -60,7 +60,7 @@ import {
import { extractCanonFromProse, summarizeCanonExtraction } from '../services/universeCanon.js';
import { getSeriesCanon } from '../services/pipeline/seriesCanon.js';
import { findDuplicateSeriesGroups, findSameNameSeries } from '../services/duplicateDetection.js';
-import { mergeSeries } from '../services/recordMerge.js';
+import { mergeSeries, ERR_CASCADE as MERGE_CASCADE_INCOMPLETE_CODE } from '../services/recordMerge.js';
import { mergeFieldsWithAI } from '../services/recordMergeAI.js';
import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipeline/episodeVideo.js';
import { generateSeriesTitleLogo } from '../services/pipeline/seriesTitleLogo.js';
@@ -133,11 +133,21 @@ const SERVICE_ERROR_STATUS = {
[ERR_NO_RENDERED_ISSUES]: 409,
// recordMerge validation (unresolved conflicts, bad ids, cross-universe).
MERGE_VALIDATION: 400,
+ // recordMerge cascade partially completed (the issue reassign failed) → 409 so
+ // the client can surface "merge incomplete, re-run to finish".
+ MERGE_CASCADE_INCOMPLETE: 409,
};
const mapServiceError = (err) => {
const status = SERVICE_ERROR_STATUS[err?.code];
- if (status) return new ServerError(err.message, { status, code: err.code });
+ if (status) {
+ // An incomplete merge cascade forwards the survivor/loser ids + which step
+ // failed so the UI can tell the user exactly what didn't move.
+ const context = err?.code === MERGE_CASCADE_INCOMPLETE_CODE
+ ? { survivorId: err.survivorId, loserId: err.loserId, failed: err.failed }
+ : undefined;
+ return new ServerError(err.message, { status, code: err.code, context });
+ }
return err;
};
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index e65af28c1f..f1e2240a75 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -34,7 +34,7 @@ import { enqueueJob } from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';
import { findDuplicateUniverseGroups, findSameNameUniverses } from '../services/duplicateDetection.js';
-import { mergeUniverses } from '../services/recordMerge.js';
+import { mergeUniverses, ERR_CASCADE as MERGE_CASCADE_INCOMPLETE_CODE } from '../services/recordMerge.js';
import { mergeFieldsWithAI } from '../services/recordMergeAI.js';
import { registerUniverseBuilderRun } from '../services/universeBuilderCollectionHook.js';
import { getImageModels, isFlux2 } from '../lib/mediaModels.js';
@@ -53,15 +53,22 @@ const SERVICE_ERROR_STATUS = {
[svc.ERR_HAS_LIVE_SERIES]: 409,
// recordMerge validation (unresolved conflicts, bad ids).
MERGE_VALIDATION: 400,
+ // recordMerge cascade partially completed (a child re-point failed) → 409 so
+ // the client can surface "merge incomplete, re-run to finish".
+ MERGE_CASCADE_INCOMPLETE: 409,
};
const mapServiceError = (err) => {
const status = SERVICE_ERROR_STATUS[err?.code];
if (status) {
- // Propagate the blocking-series list (if any) so the UI can list which
- // series block the delete — rides in `context`, which the error handler
- // serializes onto the response body.
- const context = err?.blockingSeries ? { blockingSeries: err.blockingSeries } : undefined;
+ // Propagate diagnostic context onto the response body via `context`: the
+ // blocking-series list for a delete-guard 409, or the survivor/loser ids +
+ // which children re-pointed vs. failed for an incomplete merge cascade.
+ const context = err?.blockingSeries
+ ? { blockingSeries: err.blockingSeries }
+ : err?.code === MERGE_CASCADE_INCOMPLETE_CODE
+ ? { survivorId: err.survivorId, loserId: err.loserId, repointed: err.repointed, failed: err.failed }
+ : undefined;
return new ServerError(err.message, { status, code: err.code, context });
}
return err;
diff --git a/server/services/recordMerge.js b/server/services/recordMerge.js
index 431d62841b..82d02d2906 100644
--- a/server/services/recordMerge.js
+++ b/server/services/recordMerge.js
@@ -43,8 +43,32 @@ import {
// 400). get*() NOT_FOUND errors propagate with their own per-record codes,
// which each router already maps to 404.
export const ERR_VALIDATION = 'MERGE_VALIDATION';
+
+// Raised when the cascade (re-point children → tombstone loser) partially
+// completes: the survivor is already merged but one or more child re-points (or
+// the issue reassign) failed, so the loser is intentionally left LIVE rather
+// than tombstoned over un-moved children. The merge is resumable — re-running
+// it converges cleanly because every step is idempotent: buildXUnion dedupes
+// its list unions, the child re-point / issue-reassign only touch records still
+// pointing at the loser, and the survivor write is a verbatim overwrite. Both
+// routers map it to 409 and forward its `{ survivorId, loserId, repointed,
+// failed }` context so the UI can name exactly which children are stuck.
+export const ERR_CASCADE = 'MERGE_CASCADE_INCOMPLETE';
+
const makeErr = (message, code) => Object.assign(new Error(message), { code });
+// Build the resumable cascade error. `failed` is `[{ id, name, error, step? }]`;
+// `repointed` (universes only) is the children that DID move on this pass.
+const cascadeError = (kind, survivorId, loserId, failed, repointed = []) =>
+ Object.assign(
+ new Error(
+ `${kind} merge could not complete: ${failed.length} cascade step(s) failed ` +
+ `(${failed.map((f) => f.name || f.id).join(', ')}). The survivor already holds the ` +
+ `merged data and the loser was left intact — resolve the failure and re-run the merge to finish.`,
+ ),
+ { code: ERR_CASCADE, survivorId, loserId, failed, repointed },
+ );
+
// ---- pure union helpers (exported for unit tests) ----
const lc = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');
@@ -347,8 +371,23 @@ export async function mergeUniverses(survivorId, loserId, fieldChoices = {}, { d
// 2. Re-point child series to the survivor BEFORE tombstoning the loser, so
// the block-until-empty delete guard doesn't trip and nothing is orphaned.
+ // The cascade has no transaction, so a single child's failure must not
+ // strand the whole merge mid-loop with no cleanup: collect per-child
+ // failures and keep going so every child that CAN move, moves. If any
+ // failed, abort BEFORE the tombstone — the loser still has live children,
+ // so deleting it would trip the block-until-empty guard anyway — and
+ // surface a resumable cascade error (the survivor already holds the union;
+ // re-running re-points only the children still under the loser, then
+ // tombstones). Best-effort-tombstoning instead would orphan those children.
+ const repointed = [];
+ const repointFailed = [];
for (const s of childSeries) {
- await updateSeries(s.id, { universeId: survivorId });
+ await updateSeries(s.id, { universeId: survivorId })
+ .then(() => repointed.push({ id: s.id, name: s.name }))
+ .catch((err) => repointFailed.push({ id: s.id, name: s.name, error: err?.message || String(err) }));
+ }
+ if (repointFailed.length > 0) {
+ throw cascadeError('Universe', survivorId, loserId, repointFailed, repointed);
}
// 3. Fold the loser's auto-collection into the survivor's. The deterministic
@@ -442,7 +481,15 @@ export async function mergeSeries(survivorId, loserId, fieldChoices = {}, { dryR
const survivorSeasonId = survivorSeasonIdByNumber.get(ls.number);
if (survivorSeasonId) seasonIdMap[ls.id] = survivorSeasonId;
}
- await reassignIssuesToSeries(loserId, survivorId, { seasonIdMap });
+ // The reassign is one queued write that persists nothing until it succeeds,
+ // so a failure leaves the issues fully under the loser. Abort BEFORE the
+ // tombstone (deleting the loser now would orphan its un-moved issues) and
+ // surface a resumable cascade error — the survivor already holds the union;
+ // re-running reassigns only the issues still under the loser, then tombstones.
+ await reassignIssuesToSeries(loserId, survivorId, { seasonIdMap }).catch((err) => {
+ throw cascadeError('Series', survivorId, loserId,
+ [{ id: loserId, name: loser.name, error: err?.message || String(err), step: 'reassign-issues' }]);
+ });
}
// 3. Fold the loser's series-collection into the survivor's, then tombstone it.
diff --git a/server/services/recordMerge.test.js b/server/services/recordMerge.test.js
index 9901e8895b..dd6cfd05aa 100644
--- a/server/services/recordMerge.test.js
+++ b/server/services/recordMerge.test.js
@@ -162,6 +162,7 @@ describe('recordMerge — pure union helpers', () => {
describe('recordMerge — mergeUniverses (integration)', () => {
beforeEach(() => {
+ vi.restoreAllMocks();
rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
mkdirSync(TEST_DATA_ROOT, { recursive: true });
uuidCounter = 0;
@@ -221,6 +222,36 @@ describe('recordMerge — mergeUniverses (integration)', () => {
expect(survivorCol.items.map((i) => i.ref)).toContain('loser-pic.png');
});
+ it('aborts the cascade before tombstoning when a child re-point fails, and is resumable', async () => {
+ const { survivor, loser } = await seed();
+ const childA = await seriesSvc.createSeries({ name: 'A', universeId: loser.id });
+ const childB = await seriesSvc.createSeries({ name: 'B', universeId: loser.id });
+
+ // Force ONLY the second child's re-point to fail (disk error mid-cascade).
+ const realUpdate = seriesSvc.updateSeries;
+ const spy = vi.spyOn(seriesSvc, 'updateSeries').mockImplementation((id, patch) =>
+ (id === childB.id ? Promise.reject(new Error('disk full')) : realUpdate(id, patch)));
+
+ await expect(merge.mergeUniverses(survivor.id, loser.id, {}))
+ .rejects.toMatchObject({ code: 'MERGE_CASCADE_INCOMPLETE', failed: [{ id: childB.id }] });
+
+ // Loser left LIVE (NOT tombstoned over its un-moved child).
+ expect((await universeSvc.getUniverse(loser.id)).deleted).toBeFalsy();
+ // Survivor already holds the union (the write is idempotent across re-runs).
+ expect(Object.keys((await universeSvc.getUniverse(survivor.id)).categories))
+ .toEqual(expect.arrayContaining(['landscapes', 'outfits']));
+ // Child A moved; child B is still under the loser.
+ expect((await seriesSvc.getSeries(childA.id)).universeId).toBe(survivor.id);
+ expect((await seriesSvc.getSeries(childB.id)).universeId).toBe(loser.id);
+
+ // Clear the fault and re-run → converges: B re-points, loser tombstoned.
+ spy.mockRestore();
+ const result = await merge.mergeUniverses(survivor.id, loser.id, {});
+ expect(result.merged).toBe(true);
+ expect((await seriesSvc.getSeries(childB.id)).universeId).toBe(survivor.id);
+ await expect(universeSvc.getUniverse(loser.id)).rejects.toMatchObject({ code: universeSvc.ERR_NOT_FOUND });
+ });
+
it('refuses to execute with an unresolved scalar conflict', async () => {
const survivor = await universeSvc.createUniverse({ name: 'X', starterPrompt: 'survivor-prompt' });
const loser = await universeSvc.createUniverse({ name: 'X', starterPrompt: 'loser-prompt' });
@@ -234,6 +265,7 @@ describe('recordMerge — mergeUniverses (integration)', () => {
describe('recordMerge — mergeSeries (integration)', () => {
beforeEach(() => {
+ vi.restoreAllMocks();
rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
mkdirSync(TEST_DATA_ROOT, { recursive: true });
uuidCounter = 0;
@@ -315,6 +347,29 @@ describe('recordMerge — mergeSeries (integration)', () => {
expect(moved.seasonId).toBeNull();
});
+ it('aborts the series cascade before tombstoning when the issue reassign fails, and is resumable', async () => {
+ const u = await universeSvc.createUniverse({ name: 'U' });
+ const survivor = await seriesSvc.createSeries({ name: 'Twin', universeId: u.id });
+ const loser = await seriesSvc.createSeries({ name: 'Twin', universeId: u.id });
+ await issuesSvc.createIssue({ seriesId: loser.id, title: 'Loser Issue' });
+
+ const spy = vi.spyOn(issuesSvc, 'reassignIssuesToSeries').mockRejectedValueOnce(new Error('reassign boom'));
+
+ await expect(merge.mergeSeries(survivor.id, loser.id, {}))
+ .rejects.toMatchObject({ code: 'MERGE_CASCADE_INCOMPLETE', failed: [{ step: 'reassign-issues' }] });
+
+ // Loser left LIVE; its issue is still under the loser (nothing was moved).
+ await expect(seriesSvc.getSeries(loser.id)).resolves.toMatchObject({ id: loser.id });
+ expect(await issuesSvc.listIssues({ seriesId: loser.id })).toHaveLength(1);
+
+ // Clear the fault and re-run → converges: issue moves, loser tombstoned.
+ spy.mockRestore();
+ const result = await merge.mergeSeries(survivor.id, loser.id, {});
+ expect(result.merged).toBe(true);
+ expect(await issuesSvc.listIssues({ seriesId: survivor.id })).toHaveLength(1);
+ await expect(seriesSvc.getSeries(loser.id)).rejects.toMatchObject({ code: seriesSvc.ERR_NOT_FOUND });
+ });
+
it('rejects merging series from different universes', async () => {
const u1 = await universeSvc.createUniverse({ name: 'U1' });
const u2 = await universeSvc.createUniverse({ name: 'U2' });