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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: serialize settings restores with pending mutations (#9453)
[._.]/ Adam Eivyb1e6b2b49f1b
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex c4e2fbeca1..3008d8adf4 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -239,6 +239,21 @@ reports that replay committed and recovery still needs attention. Applicationdatabase operations drain before reset; new operations receive a temporarymaintenance error until replay and reconciliation finish (including failures).+### Restoring settings in a running server++Full live file restores and selective `settings.json` restores join the settings+write queue. Previously admitted mutations finish before transfer starts; later+mutations wait through transfer and cache reconciliation, then read the restored+file as their base. Partial transfer and reconciliation failures release the+queue while retaining the existing restore diagnostics. Malformed restored+settings still invalidate the cache rather than broadcasting empty defaults.+Dry runs and unrelated selective restores do not acquire this settings boundary.++A full restore acquires queues in this order: settings, CoS configuration, CoS+runtime state. The settings queue remains held through CoS reconciliation. A+restore callback must never call a queued settings write API; cache reload reads+directly and does not re-enter the queue.+### Restoring CoS files in a running serverA full live file restore or selective `cos` restore requires the CoS daemon anddiff --git a/server/services/backup.js b/server/services/backup.jsindex 8c55164d71..87b5ca3ff7 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -25,7 +25,7 @@ import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.import { getBackendName } from './memoryBackend.js';import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';import { isSafeSnapshotSource, isSafeSubdirFilter, anchorUserExcludes } from '../lib/sharedSchemas.js';-import { reloadSettings } from './settings.js';+import { reloadSettings, withLiveSettingsRestore } from './settings.js';import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';import { noteSystemActivity } from './systemActivityNotify.js';@@ -1509,11 +1509,20 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subreturn { dryRun, snapshotId, subdirFilter, changedFiles: transfer.value, verification };};const scope = subdirFilter?.split('/').filter(part => part && part !== '.').join('/');- if (!dryRun && (!scope || ['cos', 'cos/config.json', 'cos/state.json'].includes(scope))) {- const { withLiveCosRestore } = await import('./cosState.js');- return withLiveCosRestore(restoreFiles);+ const restoreWithCosBoundary = async () => {+ if (!dryRun && (!scope || ['cos', 'cos/config.json', 'cos/state.json'].includes(scope))) {+ const { withLiveCosRestore } = await import('./cosState.js');+ return withLiveCosRestore(restoreFiles);+ }+ return restoreFiles();+ };+ // Fixed acquisition order: settings -> CoS config -> CoS runtime. Settings+ // writers drain before any CoS queue is held, and remain fenced until both+ // the transfer and all cache reconciliation (including CoS) have settled.+ if (!dryRun && (!scope || scope === 'settings.json')) {+ return withLiveSettingsRestore(restoreWithCosBoundary);}- return restoreFiles();+ return restoreWithCosBoundary();}const DUMP_UNREADABLE = Object.freeze({ status: 'failed', reason: 'dump_unreadable', error: 'The snapshot database dump could not be read or staged for restore. Restore was refused without changing data.' });diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex e19fbd28d3..907838fb51 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -120,15 +120,19 @@ import * as fs from 'fs/promises';// Partial mock of the settings service: only reloadSettings is overridden, so a// live restore can be asserted to re-sync the settings caches without actually// touching the developer's settings.json or emitting socket events.-vi.mock('./settings.js', async (importOriginal) => ({- ...(await importOriginal()),- reloadSettings: vi.fn(async () => {}),-}));+vi.mock('./settings.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ reloadSettings: vi.fn(async () => {}),+ withLiveSettingsRestore: vi.fn(actual.withLiveSettingsRestore),+ };+});vi.mock('./brainStorage.js', async (importOriginal) => ({...(await importOriginal()),invalidateAllCaches: vi.fn(),}));-import { reloadSettings } from './settings.js';+import { reloadSettings, withLiveSettingsRestore } from './settings.js';import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, openSnapshotStream, restoreSnapshot, resolveRsyncBinary, deleteSnapshot } from './backup.js';import { EXCLUDE_PATTERN_MAX_LENGTH, anchorUserExclude, anchorUserExcludes, isSafeExcludePattern } from '../lib/sharedSchemas.js';@@ -2515,6 +2519,7 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>reloadSettings.mockClear();invalidateBrainCaches.mockClear();withLiveCosRestore.mockClear();+ withLiveSettingsRestore.mockClear();});// Drive a mocked rsync to a clean exit so restoreSnapshot resolves.@@ -2639,6 +2644,89 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>});});+ describe('settings restore ownership boundary', () => {+ it.each([undefined, 'settings.json'])('holds the boundary for affected live scope %s', async subdirFilter => {+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const reloading = Promise.withResolvers();+ const finishReload = Promise.withResolvers();+ reloadSettings.mockImplementationOnce(async () => {+ reloading.resolve();+ await finishReload.promise;+ });+ const pending = restoreSnapshot('/dest', 'snap-1', { dryRun: false, subdirFilter });+ await flush();+ expect(withLiveSettingsRestore).toHaveBeenCalledTimes(1);+ const later = vi.fn();+ const waitingWrite = withLiveSettingsRestore(later);+ proc.emit('close', 0);+ await reloading.promise;+ expect(later).not.toHaveBeenCalled();+ finishReload.resolve();+ await Promise.all([pending, waitingWrite]);+ expect(later).toHaveBeenCalledTimes(1);+ });++ it.each([{ dryRun: true }, { dryRun: true, subdirFilter: 'settings.json' }, { dryRun: false, subdirFilter: 'images' }, { dryRun: false, subdirFilter: 'cos' }])('leaves unaffected scope alone: %j', async options => {+ await runRestore('/dest', 'snap-1', options);+ expect(withLiveSettingsRestore).not.toHaveBeenCalled();+ });++ it('drains settings before acquiring CoS and holds them through CoS reconciliation', async () => {+ const admitted = Promise.withResolvers();+ const finishWrite = Promise.withResolvers();+ const writing = withLiveSettingsRestore(async () => {+ admitted.resolve();+ await finishWrite.promise;+ });+ await admitted.promise;+ const reconciled = Promise.withResolvers();+ const finishCosReload = Promise.withResolvers();+ withLiveCosRestore.mockImplementationOnce(async transfer => {+ const result = await transfer();+ reconciled.resolve();+ await finishCosReload.promise;+ return result;+ });+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const pending = restoreSnapshot('/dest', 'snap-1', { dryRun: false });+ await vi.waitFor(() => expect(withLiveSettingsRestore).toHaveBeenCalledTimes(2));+ expect(withLiveCosRestore).not.toHaveBeenCalled();+ finishWrite.resolve();+ await flush();+ const later = vi.fn();+ const waitingWrite = withLiveSettingsRestore(later);+ proc.emit('close', 0);+ await reconciled.promise;+ expect(later).not.toHaveBeenCalled();+ finishCosReload.resolve();+ await Promise.all([writing, pending, waitingWrite]);+ expect(later).toHaveBeenCalledTimes(1);+ });++ it('preserves full-restore CoS busy refusal and releases settings admission', async () => {+ withLiveCosRestore.mockRejectedValueOnce(Object.assign(new Error('Stop CoS before restoring'), { code: 'COS_RESTORE_BUSY' }));+ await expect(restoreSnapshot('/dest', 'snap-1', { dryRun: false })).rejects.toMatchObject({ code: 'COS_RESTORE_BUSY' });+ expect(spawn).not.toHaveBeenCalled();+ await expect(withLiveSettingsRestore(() => 'released')).resolves.toBe('released');+ });++ it.each([0, 1])('releases settings after reconciliation failure with rsync exit %s', async exitCode => {+ reloadSettings.mockRejectedValueOnce(new Error('settings reload failed'));+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const pending = restoreSnapshot('/dest', 'snap-1', { dryRun: false, subdirFilter: 'settings.json' });+ await flush();+ const later = vi.fn();+ const waitingWrite = withLiveSettingsRestore(later);+ proc.emit('close', exitCode);+ await expect(pending).rejects.toThrow(/settings reload failed/);+ await waitingWrite;+ expect(later).toHaveBeenCalledTimes(1);+ });+ });+describe('settings cache re-sync', () => {it('reloads settings after a live restore', async () => {await runRestore('/dest', 'snap-1', { dryRun: false });diff --git a/server/services/settings.js b/server/services/settings.jsindex 7c3d96f35d..249784e649 100644--- a/server/services/settings.js+++ b/server/services/settings.js@@ -183,6 +183,14 @@ export const reloadSettings = async () => {// stay off the queue — atomicWrite's temp-file+rename keeps every read whole.const queueWrite = createFileWriteQueue();+/**+ * Drain admitted settings writes and hold later writes through an out-of-band+ * restore and its cache reconciliation. The callback must not re-enter any+ * settings write API; reloadSettings reads directly and is safe inside it.+ * For a full restore acquire this queue before CoS config, then CoS state.+ */+export const withLiveSettingsRestore = (restore) => queueWrite(restore);+// Longest scalar the ledger keeps verbatim. A settings value longer than this// is a blob (a prompt template, a key list), and the useful fact for "what did I// change?" is THAT it changed, not its full text.diff --git a/server/services/settings.test.js b/server/services/settings.test.jsindex 6ccadb8e6d..4b52c8eaa8 100644--- a/server/services/settings.test.js+++ b/server/services/settings.test.js@@ -35,7 +35,7 @@ import { mkdtempSync, rmSync } from 'fs';import { join as joinPath } from 'path';import { tmpdir } from 'os';import { atomicWrite, tryReadFile, tryReadFileStrict } from '../lib/fileUtils.js';-import { getSettings, updateSettings, updateSettingsWith, reloadSettings, settingsEvents, __resetSettingsCache, readSettingsStrict } from './settings.js';+import { getSettings, updateSettings, updateSettingsWith, withLiveSettingsRestore, reloadSettings, settingsEvents, __resetSettingsCache, readSettingsStrict } from './settings.js';describe('settings.js', () => {beforeEach(() => {@@ -348,6 +348,59 @@ describe('settings.js', () => {});});+ describe('live settings restore boundary', () => {+ it('drains admitted mutations and gives waiting mutations the restored warm-store base', async () => {+ let disk = { exampleSetting: 'before' };+ tryReadFile.mockImplementation(async () => JSON.stringify(disk));+ atomicWrite.mockImplementation(async (_path, content) => { disk = JSON.parse(content); });+ expect(await getSettings()).toEqual(disk);+ const admitted = Promise.withResolvers();+ const resumeMutation = Promise.withResolvers();+ const transferStarted = Promise.withResolvers();+ const finishTransfer = Promise.withResolvers();+ const mutation = updateSettingsWith(async current => {+ admitted.resolve();+ await resumeMutation.promise;+ return { ...current, earlier: true };+ });+ await admitted.promise;+ const transfer = vi.fn(async () => {+ expect(disk).toEqual({ exampleSetting: 'before', earlier: true });+ disk = { exampleSetting: 'snapshot' };+ transferStarted.resolve();+ await finishTransfer.promise;+ await reloadSettings();+ });+ const restore = withLiveSettingsRestore(transfer);+ await Promise.resolve();+ expect(transfer).not.toHaveBeenCalled();+ resumeMutation.resolve();+ await transferStarted.promise;+ const laterMutation = vi.fn(current => ({ ...current, later: true }));+ const later = updateSettingsWith(laterMutation);+ await Promise.resolve();+ expect(laterMutation).not.toHaveBeenCalled();+ finishTransfer.resolve();+ await Promise.all([mutation, restore, later]);+ expect(disk).toEqual({ exampleSetting: 'snapshot', later: true });+ expect(await getSettings()).toEqual(disk);+ });++ it('releases a rejected restore so a later update reads the partially restored file', async () => {+ let disk = { exampleSetting: 'before' };+ tryReadFile.mockImplementation(async () => JSON.stringify(disk));+ atomicWrite.mockImplementation(async (_path, content) => { disk = JSON.parse(content); });+ await getSettings();+ await expect(withLiveSettingsRestore(async () => {+ disk = { exampleSetting: 'partial snapshot' };+ await reloadSettings();+ throw new Error('partial transfer failed');+ })).rejects.toThrow('partial transfer failed');+ await updateSettings({ later: true });+ expect(await getSettings()).toEqual({ exampleSetting: 'partial snapshot', later: true });+ });+ });+describe('timezoneUpdatedAt stamping (#2040)', () => {it('stamps timezoneUpdatedAt when the timezone value actually changes', async () => {tryReadFile.mockResolvedValue(JSON.stringify({ timezone: 'UTC', theme: 'dark' }));