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: import commit merges canon/seasons against fresh state, not a stale snapshot (#8453)

[._.]/ Adam Eivycd924ab7b43f
diff --git a/server/services/importer.js b/server/services/importer.js
index 480dbc5231..a3601a3100 100644
--- a/server/services/importer.js
+++ b/server/services/importer.js
@@ -1024,9 +1024,16 @@ export async function commitImport({
throw makeErr('At least one issue is required', ERR_VALIDATION);
}
- // Re-fetch under the universe + series lock window so we apply the merge
- // against the freshest persisted state — the user may have edited the
- // universe canon in another tab between analyze and commit.
+ // Read for validation (universeId/seriesId linkage, lock checks, the
+ // arcPosition/season-number gates below) and for the up-front counts used
+ // to size auto-assigned positions and the additive issue-count target.
+ // NOT the source of truth the universe/series writes below merge against —
+ // `cleanupFormatting` can spend minutes in per-issue LLM calls after this
+ // read, so a concurrent edit to universe canon or series seasons could
+ // land in that window. The actual canon/season merges use the mutator form
+ // of `updateUniverse`/`updateSeries`, which re-reads the freshest persisted
+ // record inside the write queue (issue #8453) — this snapshot is stale by
+ // the time those writes run.
const universe = await getUniverse(universeId);
const series = await getSeries(seriesId);
@@ -1266,23 +1273,33 @@ export async function commitImport({
// Only merge kinds the user actually supplied entries for — calling
// mergeExtractedBible with an empty list still rebuilds the array and
// re-stamps timestamps, churning the file write for no behavior change.
- const universePatch = Object.fromEntries(
- KIND_MAP
- .filter(([selectionKey]) => (canonSelections[selectionKey] || []).length > 0)
- .map(([selectionKey, kind, storageKey]) => [
- storageKey,
- mergeExtractedBible(
- universe[storageKey] || [],
- canonSelections[selectionKey],
- kind,
- { source: 'imported' },
- ),
- ]),
- );
+ // Selection kinds are fixed by `canonSelections` (the AI-extraction output),
+ // not by anything on `universe`, so this gate is safe to evaluate against
+ // the up-front snapshot even though the write below re-reads fresh state.
+ const selectedKindMap = KIND_MAP
+ .filter(([selectionKey]) => (canonSelections[selectionKey] || []).length > 0);
// If the user supplied no canon at all (arc-only import), skip the
// updateUniverse round-trip entirely.
- const updatedUniverse = Object.keys(universePatch).length > 0
- ? await updateUniverse(universe.id, universePatch)
+ //
+ // Mutator form (issue #8453): `cleanupFormatting` above can spend minutes
+ // in per-issue LLM calls between the up-front `getUniverse` read and this
+ // write. Merging against the stale `universe` snapshot here would silently
+ // drop any canon edit a concurrent tab/job made to the SAME array during
+ // that window (mergeExtractedBible rebuilds the whole array from its base
+ // list). Merging against `latest` — the freshest persisted record, read
+ // inside updateUniverse's write queue — closes that race.
+ const updatedUniverse = selectedKindMap.length > 0
+ ? await updateUniverse(universe.id, (latest) => Object.fromEntries(
+ selectedKindMap.map(([selectionKey, kind, storageKey]) => [
+ storageKey,
+ mergeExtractedBible(
+ latest[storageKey] || [],
+ canonSelections[selectionKey],
+ kind,
+ { source: 'imported' },
+ ),
+ ]),
+ ))
: universe;
const sanitizedArc = sanitizeArc(arc);
@@ -1325,20 +1342,40 @@ export async function commitImport({
...biblePatch,
});
} else if (sanitizedArc || seasons.length > 0 || Object.keys(biblePatch).length > 0) {
- // Only build + persist a seasons array when the caller actually sent
- // some — otherwise an arc-only re-import on a series that already has
- // seasons rewrites the array byte-for-byte identical (just to bump
- // sanitizeSeasonList's normalization), a wasted disk write.
- const seasonsPatch = seasons.length > 0
- ? { seasons: sanitizeSeasonList(mergeSeasons(
- Array.isArray(series.seasons) ? series.seasons : [],
- seasons,
- )) }
- : {};
- updatedSeries = await updateSeries(series.id, {
- ...(sanitizedArc ? { arc: sanitizedArc } : {}),
- ...seasonsPatch,
- ...biblePatch,
+ // Mutator form (issue #8453): same race as the universe write above —
+ // `cleanupFormatting` can run for minutes before this write, during which
+ // a concurrent tab/job may add or edit a season on this series.
+ // `mergeSeasons` rebuilds the whole array from its base list, so merging
+ // against the stale `series` snapshot captured before that window would
+ // silently drop the concurrent edit. Recompute the seasons merge and the
+ // empty-field fill-ins against `latest` — the freshest persisted record,
+ // read inside updateSeries's write queue.
+ updatedSeries = await updateSeries(series.id, (latest) => {
+ // Only build + persist a seasons array when the caller actually sent
+ // some — otherwise an arc-only re-import on a series that already has
+ // seasons rewrites the array byte-for-byte identical (just to bump
+ // sanitizeSeasonList's normalization), a wasted disk write.
+ const seasonsPatch = seasons.length > 0
+ ? { seasons: sanitizeSeasonList(mergeSeasons(
+ Array.isArray(latest.seasons) ? latest.seasons : [],
+ seasons,
+ )) }
+ : {};
+ const latestBiblePatch = {};
+ if (arcLogline && !(latest.logline || '').trim()) latestBiblePatch.logline = arcLogline;
+ if (arcPremise && !(latest.premise || '').trim()) latestBiblePatch.premise = arcPremise;
+ // Additive: target the POST-import total (issues already on the series
+ // plus the ones being added), not just this batch — adding 3 issues to
+ // a series that already has 2 should target 5, not 3. `existingIssues`
+ // is the up-front count; the issue-create loop below still runs
+ // sequentially against `latest`'s state, so this total stays accurate.
+ const additiveTotal = existingIssues.length + issueCount;
+ if (additiveTotal > 0 && !(latest.issueCountTarget > 0)) latestBiblePatch.issueCountTarget = additiveTotal;
+ return {
+ ...(sanitizedArc ? { arc: sanitizedArc } : {}),
+ ...seasonsPatch,
+ ...latestBiblePatch,
+ };
});
}
diff --git a/server/services/importer.test.js b/server/services/importer.test.js
index 543eb5ec7f..6fe220f708 100644
--- a/server/services/importer.test.js
+++ b/server/services/importer.test.js
@@ -998,6 +998,79 @@ describe('commitImport', () => {
expect(issue.stages.prose.output).toBe('The vault loomed in the dark.');
});
+ // Race-safety regression coverage for issue #8453: commitImport reads the
+ // universe/series once, then (with cleanupFormatting on) can spend minutes
+ // in per-issue LLM calls before writing the merged canon/seasons. These
+ // tests simulate a concurrent edit landing DURING that window via the mock
+ // `runStagedLLM` — the one async gap the real reformat pass creates — and
+ // assert the concurrent edit survives the eventual merge instead of being
+ // silently overwritten by a merge against the stale up-front snapshot.
+ it('a universe canon edit made during cleanupFormatting survives the import merge (issue #8453)', async () => {
+ const { uni, ser } = await setupForCommit();
+ mockRunStagedLLM.mockImplementation(async () => {
+ // Simulates a user adding a character in another tab (or an Autopilot/
+ // Series job editing canon) while the AI cleanup pass is in flight.
+ await universeSvc.updateUniverse(uni.id, {
+ characters: [{ name: 'Concurrent Editor', role: 'supporting' }],
+ });
+ return { content: 'The vault loomed in the dark.', runId: 'r1' };
+ });
+ const result = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ contentType: 'short-story',
+ cleanupFormatting: true,
+ canonSelections: { characters: [{ name: 'Aria', role: 'protagonist' }] },
+ issues: [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed in the\ndark.' }],
+ });
+ const names = result.universe.characters.map((c) => c.name);
+ expect(names).toContain('Aria');
+ expect(names).toContain('Concurrent Editor');
+ });
+
+ it('a season edit made during cleanupFormatting survives the import merge (issue #8453)', async () => {
+ const { uni, ser } = await setupForCommit();
+ mockRunStagedLLM.mockImplementation(async () => {
+ // Simulates a season edited on the series in another tab while the AI
+ // cleanup pass is in flight.
+ await seriesSvc.updateSeries(ser.id, {
+ seasons: [{ number: 5, title: 'Concurrent Season' }],
+ });
+ return { content: 'The vault loomed in the dark.', runId: 'r1' };
+ });
+ const result = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ contentType: 'short-story',
+ cleanupFormatting: true,
+ seasons: [{ number: 1, title: 'Foundry' }],
+ issues: [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed in the\ndark.' }],
+ });
+ const numbers = result.series.seasons.map((s) => s.number);
+ expect(numbers).toContain(1);
+ expect(numbers).toContain(5);
+ });
+
+ it('an arc-only import (no canon selections) makes no universe write', async () => {
+ // importDraft:false so commitImport's own post-commit promotion (gated
+ // strictly on importDraft === true) doesn't also call updateUniverse —
+ // isolating the assertion to the canon-merge write this test targets.
+ const uni = await universeSvc.createUniverse({ name: 'Commit U', ephemeral: true, importDraft: false });
+ const ser = await seriesSvc.createSeries({
+ name: 'Commit S', universeId: uni.id, ephemeral: true, importDraft: false,
+ });
+ const updateUniverseSpy = vi.spyOn(universeSvc, 'updateUniverse');
+ const result = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ arc: { logline: 'A reluctant heir.', summary: 'Big story.' },
+ issues: [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed in the dark.' }],
+ });
+ expect(updateUniverseSpy).not.toHaveBeenCalled();
+ expect(result.universe.characters ?? []).toHaveLength(0);
+ updateUniverseSpy.mockRestore();
+ });
+
it('seeds stages.comicScript (not prose) for a comic-script import', async () => {
// A comic-script source is already script-form, so its verbatim excerpt
// must land in comicScript (ready) — seeding prose would make the
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index f0c3fe1f1c..8b2b0ab791 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -892,19 +892,58 @@ async function reconcileDraftParentUniverse(universeId) {
});
}
-export async function updateSeries(id, patch = {}) {
+export async function updateSeries(id, patchOrMutator = {}) {
+ // `patchOrMutator` overloads (mirrors updateUniverse in
+ // server/services/universeBuilder/crud.js):
+ // - Plain object: patch is applied directly inside the queue (legacy).
+ // - `async (latest) => patch | null`: mutator runs INSIDE the write queue
+ // against the freshest persisted record so a caller whose read-modify-
+ // write straddles a slow LLM call (commitImport's cleanupFormatting
+ // pass) can't clobber a concurrent edit to the same series (issue
+ // #8453). Returning `null`/`undefined` short-circuits the write and
+ // resolves with the unchanged record.
+ const isMutator = typeof patchOrMutator === 'function';
// Pre-B.4 canon (characters/settings/objects) lives on the universe, not the
// series — but a stale browser tab can still POST a legacy series shape and
// see a silent 200. Warn so a regression that re-introduces the legacy
- // payload is observable in logs instead of vanishing canon.
- const legacyFields = ['characters', 'settings', 'objects'].filter((k) => k in patch);
- if (legacyFields.length > 0) {
- console.warn(`⚠️ series PATCH ${id.slice(0, 8)} stripped legacy canon fields: ${legacyFields.join(', ')}`);
+ // payload is observable in logs instead of vanishing canon. Only checkable
+ // for a literal-object patch; a mutator's patch isn't known until it runs
+ // inside the queue, and mutator callers are trusted (server-authored).
+ if (!isMutator) {
+ const legacyFields = ['characters', 'settings', 'objects'].filter((k) => k in patchOrMutator);
+ if (legacyFields.length > 0) {
+ console.warn(`⚠️ series PATCH ${id.slice(0, 8)} stripped legacy canon fields: ${legacyFields.join(', ')}`);
+ }
}
- const { merged, nameChanged, prevEphemeral, nextEphemeral, linkedUniverseId } = await store().queueRecordWrite(id, async () => {
+ const {
+ merged, nameChanged, skipped, prevEphemeral, nextEphemeral, linkedUniverseId,
+ } = await store().queueRecordWrite(id, async () => {
const cur = await store().loadOne(id);
if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
+
+ let patch;
+ if (isMutator) {
+ patch = await patchOrMutator(cur);
+ if (patch === null || patch === undefined) {
+ return {
+ merged: cur,
+ nameChanged: false,
+ skipped: true,
+ prevEphemeral: cur.ephemeral === true,
+ nextEphemeral: cur.ephemeral === true,
+ linkedUniverseId: null,
+ };
+ }
+ // `typeof === 'object'` matches arrays and null — reject both so a
+ // stray `return []` can't slip through unnoticed.
+ if (Array.isArray(patch) || typeof patch !== 'object') {
+ throw makeErr('updateSeries mutator must return a plain object or null', ERR_VALIDATION);
+ }
+ } else {
+ patch = patchOrMutator;
+ }
+
if (cur.locked?.arc === true && Object.hasOwn(patch, 'arc')
&& (patch.arc === null || Object.hasOwn(patch.arc || {}, 'seriesDesign'))
&& JSON.stringify(sanitizeSeriesDesign(patch.arc?.seriesDesign)) !== JSON.stringify(cur.arc?.seriesDesign ?? null)) {
@@ -1005,6 +1044,7 @@ export async function updateSeries(id, patch = {}) {
return {
merged: next,
nameChanged: next.name !== cur.name,
+ skipped: false,
// See updateUniverse — surface the transition pair so the post-queue
// side effects can wire subscribe / unsubscribe.
prevEphemeral: cur.ephemeral === true,
@@ -1012,6 +1052,7 @@ export async function updateSeries(id, patch = {}) {
linkedUniverseId: (linkChanged && isPromotingChild(next)) ? next.universeId : null,
};
});
+ if (skipped) return merged;
// Ephemeral lifecycle wiring — see updateUniverse for the rationale. false→true
// tears down per-record subs; true→false re-auto-subscribes so the now-
// shareable series reaches every peer with the pipeline category enabled.
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index b216a1dfc8..b1596fdd38 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -304,6 +304,64 @@ describe('pipeline series service', () => {
await expect(svc.updateSeries('ser-nope', { name: 'x' })).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
+ // Mutator-form coverage (issue #8453) — mirrors updateUniverse's mutator
+ // tests in server/services/universeBuilder.test.js. commitImport needs this
+ // overload so a read-modify-write that straddles a slow LLM call (the
+ // importer's cleanupFormatting pass) merges against the freshest persisted
+ // series instead of a snapshot taken before the call.
+ it('updateSeries accepts a mutator(latest) callback that runs inside the queue', async () => {
+ const s = await svc.createSeries({ name: 'Salt Run', logline: 'before' });
+ const mutator = vi.fn(async (latest) => {
+ expect(latest.id).toBe(s.id);
+ return { logline: `${latest.logline} → after` };
+ });
+ const patched = await svc.updateSeries(s.id, mutator);
+ expect(mutator).toHaveBeenCalledTimes(1);
+ expect(patched.logline).toBe('before → after');
+ });
+
+ it('updateSeries short-circuits with no write when the mutator returns null', async () => {
+ const s = await svc.createSeries({ name: 'Salt Run' });
+ const beforeUpdatedAt = s.updatedAt;
+ const patched = await svc.updateSeries(s.id, async () => null);
+ expect(patched.updatedAt).toBe(beforeUpdatedAt);
+ expect(patched.id).toBe(s.id);
+ });
+
+ it('updateSeries mutator that throws propagates without writing', async () => {
+ const s = await svc.createSeries({ name: 'Salt Run', logline: 'untouched' });
+ await expect(
+ svc.updateSeries(s.id, async () => { throw new Error('mutator boom'); }),
+ ).rejects.toThrow('mutator boom');
+ const fresh = await svc.getSeries(s.id);
+ expect(fresh.logline).toBe('untouched');
+ });
+
+ it('updateSeries mutator returning a non-object value throws ERR_VALIDATION', async () => {
+ const s = await svc.createSeries({ name: 'Salt Run' });
+ await expect(
+ svc.updateSeries(s.id, async () => 'not-an-object'),
+ ).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ await expect(
+ svc.updateSeries(s.id, async () => []),
+ ).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('updateSeries mutator sees a concurrent write that landed before it ran (queued)', async () => {
+ const s = await svc.createSeries({ name: 'Salt Run', seasons: [{ number: 1, title: 'Foundry' }] });
+ // A concurrent literal-patch write races the mutator; the write queue
+ // serializes them so the mutator observes whichever landed first.
+ const [, mutated] = await Promise.all([
+ svc.updateSeries(s.id, { seasons: [{ number: 1, title: 'Foundry' }, { number: 2, title: 'Concurrent' }] }),
+ svc.updateSeries(s.id, async (latest) => ({ seasons: [...latest.seasons, { number: 3, title: 'Mutator-added' }] })),
+ ]);
+ const numbers = mutated.seasons.map((season) => season.number).sort();
+ // Whichever write the queue ran first, the mutator's own write always
+ // carries season 3 forward — the regression this covers is losing it to
+ // a merge against a stale pre-queue snapshot.
+ expect(numbers).toContain(3);
+ });
+
it('updateSeries rejects clearing universeId once a series is linked (hierarchy invariant)', async () => {
const s = await svc.createSeries({ name: 'Linked', universeId: 'u-1' });
await expect(svc.updateSeries(s.id, { universeId: '' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });