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: serialize federated video history merges with local completion writes (#9814)

[._.]/ Adam Eivy5e9fd9e771ad
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index f2f5f9650e..2abca8889a 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -34,6 +34,7 @@ import { getPipelineMutationEpoch } from './pipeline/syncEpoch.js';
import { mergeSeriesFromSync, listSeries } from './pipeline/series.js';
import { mergeIssuesFromSync, listAllIssues } from './pipeline/issues.js';
import { getPeers } from './instances.js';
+import { mutateVideoHistory, HISTORY_UNCHANGED } from './videoGen/history.js';
import { markHosted } from './peerHostedMedia.js';
import { referenceCollectionAssetManifest } from './sharing/peerSyncAssets.js';
import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './mediaCollections.js';
@@ -896,48 +897,48 @@ async function applyVideoHistoryRemote(remoteData) {
const incoming = Array.isArray(remoteData.videos) ? remoteData.videos : [];
if (incoming.length === 0) return { applied: false, count: 0 };
- // STRICT (#4115): this is the merge BASE, and the merged result is written
- // back over the whole file below. A swallowed unreadable read makes `local`
- // empty, so `next` becomes the remote rows alone — deleting every local-only
- // row, including the id-less ones the code below goes out of its way to keep.
- const localRaw = await readJSONFile(VIDEO_HISTORY_FILE, [], { strict: true });
- const local = Array.isArray(localRaw) ? localRaw : [];
-
- // Union by `id`, LWW on `createdAt` when both sides know the same row.
- // Video-history rows are append-mostly and immutable once written, so
- // `createdAt` is a sufficient (and the only) freshness signal — there's no
- // `updatedAt`. A row with no string id can't be keyed and is skipped (a
- // hand-edited or corrupt entry shouldn't clobber a real row at key
- // `undefined`); the snapshot side excludes the same rows so checksums agree.
- const hasId = hasVideoRowId;
- const keyed = local.filter(hasId);
- const before = new Map(keyed.map((r) => [r.id, r]));
- const { merged, changed } = mergeArraysByKey(
- keyed,
- incoming.filter(hasId),
- 'id',
- 'createdAt',
- );
- if (!changed) return { applied: false, count: 0 };
-
- // `count` reports rows actually added/updated by this merge (not total
- // post-merge size — that would over-report when callers sum across
- // categories or compare cycle deltas). Matches the pipeline category's
- // `count` contract.
+ // The whole read/merge/write runs inside the shared history mutation queue so
+ // a local completion (videoDownload) or another peer's snapshot can't be
+ // overwritten by this merge's stale base. The queue's read is STRICT (#4115):
+ // an unreadable file rejects instead of becoming an empty merge base that
+ // would delete every local-only row on write-back.
let changedCount = 0;
- for (const row of merged) {
- const prev = before.get(row.id);
- if (!prev || prev !== row) changedCount++;
- }
+ await mutateVideoHistory((local) => {
+ // Union by `id`, LWW on `createdAt` when both sides know the same row.
+ // Video-history rows are append-mostly and immutable once written, so
+ // `createdAt` is a sufficient (and the only) freshness signal — there's no
+ // `updatedAt`. A row with no string id can't be keyed and is skipped (a
+ // hand-edited or corrupt entry shouldn't clobber a real row at key
+ // `undefined`); the snapshot side excludes the same rows so checksums agree.
+ const hasId = hasVideoRowId;
+ const keyed = local.filter(hasId);
+ const before = new Map(keyed.map((r) => [r.id, r]));
+ const { merged, changed } = mergeArraysByKey(
+ keyed,
+ incoming.filter(hasId),
+ 'id',
+ 'createdAt',
+ );
+ if (!changed) return HISTORY_UNCHANGED;
+
+ // `count` reports rows actually added/updated by this merge (not total
+ // post-merge size — that would over-report when callers sum across
+ // categories or compare cycle deltas). Matches the pipeline category's
+ // `count` contract.
+ for (const row of merged) {
+ const prev = before.get(row.id);
+ if (!prev || prev !== row) changedCount++;
+ }
- // Preserve any local rows that lacked an id (the merge dropped them from its
- // keyed map) — don't let a sync silently delete un-keyable local history.
- const idless = local.filter((r) => !hasId(r));
- // Newest-first to match how generateVideo unshifts new rows + how the
- // Media History grid expects them.
- const next = [...merged, ...idless].sort((a, b) =>
- String(b?.createdAt ?? '').localeCompare(String(a?.createdAt ?? '')));
- await atomicWrite(VIDEO_HISTORY_FILE, next);
+ // Preserve any local rows that lacked an id (the merge dropped them from its
+ // keyed map) — don't let a sync silently delete un-keyable local history.
+ const idless = local.filter((r) => !hasId(r));
+ // Newest-first to match how generateVideo unshifts new rows + how the
+ // Media History grid expects them.
+ return [...merged, ...idless].sort((a, b) =>
+ String(b?.createdAt ?? '').localeCompare(String(a?.createdAt ?? '')));
+ });
+ if (changedCount === 0) return { applied: false, count: 0 };
console.log(`🔄 VideoHistory sync: merged ${changedCount} video row(s)`);
return { applied: true, count: changedCount };
}
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 0f04c8e603..5415408145 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -8,7 +8,7 @@
*/
import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
-import { writeFileSync, mkdirSync, readFileSync, rmSync, readdirSync, existsSync } from 'fs';
+import { writeFileSync, mkdirSync, readFileSync, rmSync, readdirSync, existsSync, statSync } from 'fs';
import { join } from 'path';
import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
@@ -871,6 +871,75 @@ describe('dataSync — videoHistory category', () => {
expect(persisted.map((v) => v.id).sort()).toEqual(['local-only', 'remote-only', 'shared']);
});
+ describe('serialization with local history writers (#9814)', () => {
+ const ids = () => readJSON(VIDEO_HISTORY_PATH).map((v) => v.id).sort();
+ // A local completion that is mid-flight (holding the queue) when the
+ // inbound snapshot arrives; `release()` lets it finish.
+ async function startPausedLocalCompletion(history) {
+ let release;
+ const gate = new Promise((r) => { release = r; });
+ let entered;
+ const started = new Promise((r) => { entered = r; });
+ const done = history.mutateVideoHistory(async (list) => {
+ entered();
+ await gate;
+ return [row('local-done'), ...list];
+ });
+ await started;
+ return { release, done };
+ }
+
+ it('keeps base, local and remote rows when a snapshot lands while a completion is in flight', async () => {
+ const history = await import('./videoGen/history.js');
+ writeJSON(VIDEO_HISTORY_PATH, [row('base')]);
+ const local = await startPausedLocalCompletion(history);
+ const apply = dataSync.applyRemote('videoHistory', { videos: [row('remote')] });
+ local.release();
+ await Promise.all([local.done, apply]);
+ expect(ids()).toEqual(['base', 'local-done', 'remote']);
+ });
+
+ it('keeps all rows when the completion is queued behind the snapshot', async () => {
+ const history = await import('./videoGen/history.js');
+ writeJSON(VIDEO_HISTORY_PATH, [row('base')]);
+ const apply = dataSync.applyRemote('videoHistory', { videos: [row('remote')] });
+ const local = history.mutateVideoHistory((list) => [row('local-done'), ...list]);
+ await Promise.all([apply, local]);
+ expect(ids()).toEqual(['base', 'local-done', 'remote']);
+ });
+
+ it('keeps both peers\' unique rows when two snapshots apply concurrently', async () => {
+ writeJSON(VIDEO_HISTORY_PATH, [row('base')]);
+ await Promise.all([
+ dataSync.applyRemote('videoHistory', { videos: [row('peer-a')] }),
+ dataSync.applyRemote('videoHistory', { videos: [row('peer-b')] }),
+ ]);
+ expect(ids()).toEqual(['base', 'peer-a', 'peer-b']);
+ });
+
+ it('replay is a no-op: no write, count 0, hidden and id-less rows preserved', async () => {
+ const idless = { prompt: 'legacy no-id', filename: 'legacy.mp4' };
+ writeJSON(VIDEO_HISTORY_PATH, [row('v1', { hidden: true }), idless]);
+ const before = readFileSync(VIDEO_HISTORY_PATH, 'utf-8');
+ const mtimeBefore = statSync(VIDEO_HISTORY_PATH).mtimeMs;
+ await new Promise((r) => setTimeout(r, 10));
+ const result = await dataSync.applyRemote('videoHistory', { videos: [row('v1')] });
+ expect(result).toEqual({ applied: false, count: 0 });
+ expect(statSync(VIDEO_HISTORY_PATH).mtimeMs).toBe(mtimeBefore);
+ expect(readFileSync(VIDEO_HISTORY_PATH, 'utf-8')).toBe(before);
+ });
+
+ it('a rejected mutation leaves the queue usable and history intact', async () => {
+ const history = await import('./videoGen/history.js');
+ writeJSON(VIDEO_HISTORY_PATH, [row('base')]);
+ await expect(history.mutateVideoHistory(() => { throw new Error('boom'); })).rejects.toThrow('boom');
+ expect(ids()).toEqual(['base']);
+ const result = await dataSync.applyRemote('videoHistory', { videos: [row('remote')] });
+ expect(result.applied).toBe(true);
+ expect(ids()).toEqual(['base', 'remote']);
+ });
+ });
+
it('applyRemote LWW: newer remote createdAt wins for the same id', async () => {
writeJSON(VIDEO_HISTORY_PATH, [row('v1', { createdAt: '2026-05-22T00:00:00Z', prompt: 'old' })]);
await dataSync.applyRemote('videoHistory', {
diff --git a/server/services/videoGen/history.js b/server/services/videoGen/history.js
index b3c9cbde76..366dcdde5b 100644
--- a/server/services/videoGen/history.js
+++ b/server/services/videoGen/history.js
@@ -50,11 +50,15 @@ export async function getHistoryItem(id) {
// the freshest persisted array and returns the array to persist (return the
// same reference after mutating it in place, or a new array). Any writer that
// can race another on this file should route through here.
+// A mutator that found nothing to change returns `HISTORY_UNCHANGED` so the
+// file is not rewritten (an idempotent replay stays a true no-op).
+export const HISTORY_UNCHANGED = Symbol('video-history-unchanged');
let historyWriteTail = Promise.resolve();
export function mutateVideoHistory(mutator) {
const run = historyWriteTail.then(async () => {
const history = await loadHistory();
const next = await mutator(Array.isArray(history) ? history : []);
+ if (next === HISTORY_UNCHANGED) return history;
const toSave = Array.isArray(next) ? next : history;
await saveHistory(toSave);
return toSave;