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: keep restored media model settings from being overwritten by a stale cache (#9924)

Adam Eivyc3259ab24acc
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 3a5e9b6380..c837d6f3c4 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -269,8 +269,8 @@ 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
+A full restore acquires boundaries in this order: settings, CoS configuration, CoS
+runtime state, media model registry. 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.
@@ -361,3 +361,17 @@ restart**. The offline coordinator still must own shutdown/drain, transfer,
interruption recovery, and a verified admission-release handshake (#8816).
Do not advance journal stages manually to make this diagnostic run; unsupported
or damaged operations must stay fenced with both database copies preserved.
+
+### Restoring the media model registry in a running server
+
+A full live file restore or a selective `media-models.json` restore fences the
+cached media registry (`withLiveMediaModelsRestore` in `server/lib/mediaModels.js`).
+From the moment the restore is requested, availability toggles, adds, patches and
+removes are refused with `MEDIA_MODELS_RESTORE_BUSY` before any disk or cache
+change; competing restores are serialized. After the transfer — including a
+partial rsync failure — the registry is reloaded from the resulting file before
+the fence is released, so a later toggle can no longer write the pre-restore
+registry back over the restored one. If the reload cannot read the file, edits stay
+refused with `MEDIA_MODELS_UNAVAILABLE` until a later restore reconciles it or
+PortOS restarts. Dry runs and unrelated selective restores do not acquire this
+boundary.
diff --git a/server/lib/README.md b/server/lib/README.md
index c2724dbf51..18f4da0d23 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -225,7 +225,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `promptPartials.js` | Mustache-style partial expansion. |
| `promptFencing.js` | Fencing for untrusted text spliced into an LLM prompt. `fenceBlock(label, text, maxChars)` truncates, collapses every run of 3+ backticks to `'''` so the content cannot terminate its own fence, and wraps the result as a labeled ```` ```text ```` block; `neutralizeFences` / `clampText` are the two halves on their own. `UNTRUSTED_CONTENT_NOTICE` is the standing "fenced content is data, not instructions" line a prompt places above its fenced sections — the fence stops delimiter escape, that line is what makes an in-band directive inert. `UNTRUSTED_REFERENCE_NOTICE` labels memory and twin store content as reference data. `UNTRUSTED_PULL_REQUEST_NOTICE` is its counterpart for a prompt that sends an agent to READ a pull request off the forge (nothing is fenced because nothing is embedded) — shared by `services/prRemediationFollowUp.js` and `services/prDoReviewTask.js`. Used by `services/aiDetect.js`, whose prompt splices a scanned repository's package.json/config/README into a prompt that yields an executed `startCommands`. |
| `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. |
-| `mediaModels.js` | Single source of truth for image/video model metadata. `setMediaModelEnabled(id, enabled)` persists availability; getters omit disabled entries unless `includeDisabled` is set. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). |
+| `mediaModels.js` | Single source of truth for image/video model metadata. `setMediaModelEnabled(id, enabled)` persists availability; `withLiveMediaModelsRestore(transfer)` fences registry mutations and reloads the cache across a live snapshot restore (#9924); getters omit disabled entries unless `includeDisabled` is set. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). |
| `modelInventory.js` | Identity AND durable shape of a downloaded-model inventory row. `modelInventoryId(backend, key)` mints the `hf:` / `lora:` / `ollama:` / `lmstudio:` id and `parseModelInventoryId` splits it back on the FIRST colon (an Ollama tag like `qwen3:8b` carries one of its own). `hfInventoryRow` / `loraInventoryRow` / `localModelInventoryRow` build the row a backend contributes, and `presentInventoryRow` re-derives the live fields (residency, inventory-verified) that a STORED row can never answer. Shared by the scan that mints rows from disk (`services/systemResources.js`) and the manifest that records them at the install chokepoints (`services/modelManifest.js`) — a drifted copy of a row's risk, manage path or delete action is a delete button pointed at the wrong place. Pure and dependency-free, so the install services reach the builders without pulling the scan's module graph. |
| `videoFailure.js` | `normalizeVideoFailure` classifies and scrubs local video causes; `createVideoDiagnosticTail` retains bounded stdout/stderr diagnostics without grouping bare exit codes. |
| `maintenanceSequence.js` | The maintenance ladder shared by both runners: `MAINTENANCE_TASK_ORDER` / `MAINTENANCE_ORDER_GUIDANCE`, the interleaved `MAINTENANCE_SEQUENCE_TYPES` (a perpetual `claim-issue` drain between every pair of audits), `maintenanceStepParams` (audits file issues, documentation does the work), and `buildMaintenanceSteps` (fix mode runs audits directly with one final drain; issue filing can omit claim jobs) which emits quota-burn-shaped run-once steps so `quotaBurnInvoke.js` can run a step from the Schedule tab's manual run or a Quota Burn family plan alike. Pure. |
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index c03cb327e7..c1299c5580 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -1165,6 +1165,16 @@ const DEFAULT_REGISTRY = {
};
let cached = null;
+// Whether the most recent fresh load parsed the file (false = fell back to the
+// in-memory defaults). Read only by withLiveMediaModelsRestore's reconciliation.
+let lastLoadReadOk = true;
+// Live-restore ownership: `restoreFences` counts restores that have been
+// requested and not yet reconciled; `restoreTail` serializes them;
+// `reconcileFailure` pins the registry read-only after a reload that could not
+// establish what the restored bytes say.
+let restoreFences = 0;
+let restoreTail = Promise.resolve();
+let reconcileFailure = null;
const ensureDir = (file) => {
const dir = dirname(file);
@@ -1744,6 +1754,7 @@ export const loadMediaModels = () => {
);
}
}
+ lastLoadReadOk = readOk;
cached = normalizeRegistry(parsed);
// Persist _shippedDefaults back to disk whenever it was absent or gained new
// ids (bootstrap run or a new built-in model shipped in this release). This
@@ -1792,6 +1803,60 @@ export const reloadMediaModels = () => {
return loadMediaModels();
};
+// Registry mutators are synchronous, so checking this at their top refuses a
+// write before any disk or cache change while a live restore owns the file (or
+// after a restore whose reload failed — persisting the stale/default cache then
+// would overwrite the restored bytes).
+const assertRegistryWritable = () => {
+ if (restoreFences > 0) {
+ throw new ServerError('The media model registry is being restored from a snapshot — retry once the restore finishes.', { status: 409, code: 'MEDIA_MODELS_RESTORE_BUSY' });
+ }
+ if (reconcileFailure) {
+ throw new ServerError(`The media model registry could not be reloaded after a snapshot restore (${reconcileFailure.message}). Restart PortOS before editing it.`, { status: 503, code: 'MEDIA_MODELS_UNAVAILABLE' });
+ }
+};
+
+/**
+ * Own data/media-models.json across an out-of-band live restore. Registry
+ * mutations are refused from the moment the restore is requested until the
+ * cache has been reloaded from the resulting file — including after a partial
+ * transfer, which may already have overwritten it. Competing restores are
+ * serialized. A reload that cannot parse the file leaves the registry
+ * read-only until a later restore reconciles it (or the process restarts).
+ * The callback must not call a registry mutator.
+ */
+export const withLiveMediaModelsRestore = (transfer) => {
+ restoreFences += 1;
+ const run = restoreTail.then(async () => {
+ try {
+ const [result] = await Promise.allSettled([Promise.resolve().then(transfer)]);
+ let reloadError = null;
+ try {
+ reloadMediaModels();
+ if (!lastLoadReadOk) throw new Error('media-models.json is unreadable or not valid JSON');
+ reconcileFailure = null;
+ } catch (err) {
+ reloadError = err;
+ reconcileFailure = err;
+ }
+ if (result.status === 'rejected') {
+ if (!reloadError) throw result.reason;
+ const error = new Error(`${result.reason.message}. Media model registry reload failed: ${reloadError.message}. Restart PortOS before editing media models.`, { cause: result.reason });
+ if (result.reason?.code) error.code = result.reason.code;
+ throw error;
+ }
+ if (reloadError) {
+ throw new Error(`Media model registry reload failed: ${reloadError.message}. Restart PortOS before editing media models.`, { cause: reloadError });
+ }
+ return result.value;
+ } finally {
+ restoreFences -= 1;
+ }
+ });
+ restoreTail = run.catch(() => {});
+ return run;
+};
+
// Persist a registry object to disk and swap it in as the cache. The cache is
// only replaced AFTER a successful write, so a persist failure leaves the live
// cache untouched (the mutators build an immutable `next` rather than editing
@@ -1854,6 +1919,7 @@ export const addUserModelEntry = (entry, { kind }) => {
if (kind !== 'video' && kind !== 'image') {
throw new ServerError(`Unknown model kind "${kind}" — expected "image" or "video".`, { status: 400, code: 'BAD_MODEL_KIND' });
}
+ assertRegistryWritable();
const reg = loadMediaModels();
const listKey = kind === 'video' ? activeVideoBucket() : 'image';
// Conflict-check against the ACTIVE-on-this-install lists — the current
@@ -1905,6 +1971,7 @@ const requireUserEntry = (reg, id, verb) => {
// built-ins and unknown ids. Persists + hot-reloads. Returns the updated entry.
const USER_EDITABLE_FIELDS = new Set(['name', 'steps', 'guidance']);
export const patchUserModelEntry = (id, patch) => {
+ assertRegistryWritable();
const reg = loadMediaModels();
const loc = requireUserEntry(reg, id, 'edited');
const cleanPatch = {};
@@ -1921,6 +1988,7 @@ export const patchUserModelEntry = (id, patch) => {
// Availability is install configuration, including for shipped entries. Keep
// disabled rows in the registry so they can be re-enabled without reinstalling.
export const setMediaModelEnabled = (id, enabled) => {
+ assertRegistryWritable();
const reg = loadMediaModels();
const loc = findModelLocation(reg, id);
if (!loc) throw new ServerError(`Unknown model id: ${id}`, { status: 404, code: 'NOT_FOUND' });
@@ -1933,6 +2001,7 @@ export const setMediaModelEnabled = (id, enabled) => {
// Remove a USER model entry. Refuses built-ins and unknown ids. Persists +
// hot-reloads. Returns `{ ok, id }`.
export const removeUserModelEntry = (id) => {
+ assertRegistryWritable();
const reg = loadMediaModels();
const loc = requireUserEntry(reg, id, 'removed');
const nextList = loc.list.filter((_, i) => i !== loc.idx);
diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.js
index d837d60f26..7c76e17664 100644
--- a/server/lib/mediaModels.test.js
+++ b/server/lib/mediaModels.test.js
@@ -1723,3 +1723,103 @@ describe('catalog availability', () => {
expect(() => registry.setMediaModelEnabled('missing', false)).toThrow(/Unknown/);
});
});
+
+describe('live snapshot restore ownership', () => {
+ const customEntry = { id: 'restored-custom', name: 'Restored', runner: 'flux2', source: 'user', repo: 'example/restored' };
+ // Stand-in for rsync landing snapshot bytes: a registry carrying an entry the
+ // warm process has never seen, plus a disabled shipped model.
+ const writeRestoredRegistry = (registry) => {
+ const restored = JSON.parse(JSON.stringify(registry.loadMediaModels()));
+ restored.image = [...restored.image, customEntry];
+ restored.image[0] = { ...restored.image[0], enabled: false };
+ writeFileSync(registryFile, JSON.stringify(restored, null, 2));
+ return restored.image[0].id;
+ };
+
+ it('serves restored values and keeps them through a later unrelated mutation', async () => {
+ const registry = await import('./mediaModels.js');
+ const disabledId = (registry.loadMediaModels(), registry.getImageModels()[0].id);
+ await registry.withLiveMediaModelsRestore(async () => { writeRestoredRegistry(registry); });
+ expect(registry.getImageModels({ includeDisabled: true }).some(m => m.id === customEntry.id)).toBe(true);
+
+ const video = registry.getVideoModels()[0];
+ registry.setMediaModelEnabled(video.id, false);
+ registry.patchUserModelEntry(customEntry.id, { name: 'Renamed' });
+ const onDisk = JSON.parse(readFileSync(registryFile, 'utf-8'));
+ expect(onDisk.image.find(m => m.id === customEntry.id).name).toBe('Renamed');
+ expect(onDisk.image.find(m => m.id === disabledId).enabled).toBe(false);
+ });
+
+ it('refuses every mutator before touching disk or cache while a transfer is in flight, then admits them', async () => {
+ const registry = await import('./mediaModels.js');
+ const builtin = registry.getImageModels()[0];
+ const started = Promise.withResolvers();
+ const finish = Promise.withResolvers();
+ const restoring = registry.withLiveMediaModelsRestore(async () => {
+ started.resolve();
+ await finish.promise;
+ });
+ await started.promise;
+ const before = readFileSync(registryFile, 'utf-8');
+ for (const attempt of [
+ () => registry.setMediaModelEnabled(builtin.id, false),
+ () => registry.addUserModelEntry(customEntry, { kind: 'image' }),
+ () => registry.patchUserModelEntry(customEntry.id, { name: 'x' }),
+ () => registry.removeUserModelEntry(customEntry.id),
+ ]) {
+ expect(attempt).toThrow(expect.objectContaining({ code: 'MEDIA_MODELS_RESTORE_BUSY' }));
+ }
+ expect(readFileSync(registryFile, 'utf-8')).toBe(before);
+ expect(registry.getImageModels().some(m => m.id === builtin.id)).toBe(true);
+ finish.resolve();
+ await restoring;
+ expect(registry.setMediaModelEnabled(builtin.id, false)).toMatchObject({ enabled: false });
+ });
+
+ it('reconciles from the resulting bytes after a partial transfer failure and rethrows it', async () => {
+ const registry = await import('./mediaModels.js');
+ registry.loadMediaModels();
+ const failure = Object.assign(new Error('rsync died'), { code: 'RSYNC_FAILED' });
+ await expect(registry.withLiveMediaModelsRestore(async () => {
+ writeRestoredRegistry(registry);
+ throw failure;
+ })).rejects.toMatchObject({ message: 'rsync died', code: 'RSYNC_FAILED' });
+ expect(registry.getImageModels({ includeDisabled: true }).some(m => m.id === customEntry.id)).toBe(true);
+ expect(registry.removeUserModelEntry(customEntry.id)).toMatchObject({ ok: true });
+ });
+
+ it('keeps the registry read-only when the reload cannot read the restored file, until a later restore repairs it', async () => {
+ const registry = await import('./mediaModels.js');
+ const builtin = registry.getImageModels()[0];
+ await expect(registry.withLiveMediaModelsRestore(async () => {
+ writeFileSync(registryFile, '{ not json');
+ })).rejects.toThrow(/reload failed/);
+ expect(() => registry.setMediaModelEnabled(builtin.id, false))
+ .toThrow(expect.objectContaining({ code: 'MEDIA_MODELS_UNAVAILABLE' }));
+ expect(readFileSync(registryFile, 'utf-8')).toBe('{ not json');
+
+ await registry.withLiveMediaModelsRestore(async () => {
+ writeFileSync(registryFile, JSON.stringify(registry.getShippedMediaRegistry()));
+ });
+ expect(registry.setMediaModelEnabled(builtin.id, false)).toMatchObject({ enabled: false });
+ });
+
+ it('serializes competing restores and releases ownership after a failure', async () => {
+ const registry = await import('./mediaModels.js');
+ const order = [];
+ const gate = Promise.withResolvers();
+ const first = registry.withLiveMediaModelsRestore(async () => {
+ order.push('first:start');
+ await gate.promise;
+ order.push('first:end');
+ throw new Error('first failed');
+ });
+ const second = registry.withLiveMediaModelsRestore(async () => { order.push('second'); });
+ await Promise.resolve();
+ gate.resolve();
+ await expect(first).rejects.toThrow('first failed');
+ await second;
+ expect(order).toEqual(['first:start', 'first:end', 'second']);
+ expect(registry.setMediaModelEnabled(registry.getImageModels()[0].id, false)).toMatchObject({ enabled: false });
+ });
+});
diff --git a/server/services/backup.js b/server/services/backup.js
index 19559c84ef..e3121075aa 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1521,14 +1521,24 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
return { dryRun, snapshotId, subdirFilter, changedFiles: transfer.value, verification };
};
const scope = subdirFilter?.split('/').filter(part => part && part !== '.').join('/');
+ // Innermost boundary: the media registry has no queue other boundaries wait
+ // on, and acquiring it last keeps its write fence from outliving a refused
+ // CoS restore.
+ const restoreWithMediaBoundary = async () => {
+ if (!dryRun && (!scope || scope === 'media-models.json')) {
+ const { withLiveMediaModelsRestore } = await import('../lib/mediaModels.js');
+ return withLiveMediaModelsRestore(restoreFiles);
+ }
+ return 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 withLiveCosRestore(restoreWithMediaBoundary);
}
- return restoreFiles();
+ return restoreWithMediaBoundary();
};
- // Fixed acquisition order: settings -> CoS config -> CoS runtime. Settings
+ // Fixed acquisition order: settings -> CoS config -> CoS runtime -> media registry. 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')) {
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 4d350a89c1..bc022fdf01 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -2695,6 +2695,8 @@ describe('getState and saveState', () => {
// is a data-loss-adjacent contract, not a style nit (issue #3917).
vi.mock('./cosState.js', () => ({ withLiveCosRestore: vi.fn(fn => fn()) }));
import { withLiveCosRestore } from './cosState.js';
+vi.mock('../lib/mediaModels.js', () => ({ withLiveMediaModelsRestore: vi.fn(fn => fn()) }));
+import { withLiveMediaModelsRestore } from '../lib/mediaModels.js';
describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () => {
beforeEach(() => {
@@ -2702,6 +2704,7 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
reloadSettings.mockClear();
invalidateBrainCaches.mockClear();
withLiveCosRestore.mockClear();
+ withLiveMediaModelsRestore.mockClear();
withLiveSettingsRestore.mockClear();
});
@@ -2827,6 +2830,41 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
});
});
+ describe('media registry restore ownership boundary', () => {
+ it.each([undefined, 'media-models.json'])('holds the boundary for affected live scope %s', async subdirFilter => {
+ await runRestore('/dest', 'snap-1', { dryRun: false, subdirFilter });
+ expect(withLiveMediaModelsRestore).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([{ dryRun: true }, { dryRun: true, subdirFilter: 'media-models.json' }, { dryRun: false, subdirFilter: 'images' }, { dryRun: false, subdirFilter: 'cos' }, { dryRun: false, subdirFilter: 'settings.json' }])('leaves unaffected scope alone: %j', async options => {
+ await runRestore('/dest', 'snap-1', options);
+ expect(withLiveMediaModelsRestore).not.toHaveBeenCalled();
+ });
+
+ it('acquires the registry after settings and CoS and releases it when the transfer fails', async () => {
+ const order = [];
+ withLiveSettingsRestore.mockImplementationOnce(async fn => { order.push('settings'); return fn(); });
+ withLiveCosRestore.mockImplementationOnce(async fn => { order.push('cos'); return fn(); });
+ withLiveMediaModelsRestore.mockImplementationOnce(async fn => {
+ order.push('media');
+ try { return await fn(); } finally { order.push('media:released'); }
+ });
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const pending = restoreSnapshot('/dest', 'snap-1', { dryRun: false });
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());
+ proc.emit('close', 1);
+ await expect(pending).rejects.toThrow();
+ expect(order).toEqual(['settings', 'cos', 'media', 'media:released']);
+ });
+
+ it('does not fence the registry when CoS refuses a full restore', 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(withLiveMediaModelsRestore).not.toHaveBeenCalled();
+ });
+ });
+
describe('settings restore ownership boundary', () => {
it.each([undefined, 'settings.json'])('holds the boundary for affected live scope %s', async subdirFilter => {
const proc = fakeProc();