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: rebuild derived media after restore and admit operator purges

[._.]/ Adam Eivyc36b0278bde3
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index fb5970de16..9249ec678a 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -99,7 +99,9 @@ Admission inventory (`withBackupAssetPublication`):
| ChatGPT archive import and import-memory deletion (`chatgptImport.js`, `brain.js`; the ZIP's asset extraction in `chatgptZipImport.js`) | Covered (#9982 partial): assets are extracted outside admission and named only by the memory row; each conversation's archived transcript and that row commit under one lease, and deleting an import memory drops the record and unlinks its transcript and unreferenced assets under one lease |
| YouTube ingest (`youtubeIngest.js`) | Covered (#9982 partial): downloads run outside admission; the index record that first names a transcript or audio file takes the lease, and forgetting an ingest drops the record and unlinks its files under one lease |
| Digital twin documents and genome upload/delete (`digital-twin-documents.js`, `genome.js`) | Covered (#9982 partial): each document file or raw genome file and the meta record naming it is one lease, including deletion |
-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): video generation, image generation tails, derived media-index refresh |
+| Derived media index (`mediaAssetIndex/`) | Rebuilt: `media_assets` rows are excluded from snapshot dumps; database restore rebuilds atomically from disk before reopening admission, and relevant file restores refresh the mirror |
+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): video generation and image generation tails |
+| Explicit file purge (`dataManager.js`, `routes/uploads.js`, `routes/attachments.js`) | Covered: single and bulk deletions hold one lease. These operator-directed removals may intentionally leave external references; admission prevents a snapshot from interleaving with the removal, not from preserving that already-deleted state |
| Durable replacement/deletion owners not yet classified | Outstanding (#9982) |
| Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) |
| Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |
@@ -245,7 +247,7 @@ the existing thumbnail-less behavior. Terminal status and notifications follow
the durable commit. Caller publication latches keep committed outputs and earlier
batch members out of later failure or cancellation cleanup. Federated video
replacement/replay and derived stitch, upscale, timeline and HTML-composition
-lanes remain outstanding; this does not settle the derived media index.
+lanes remain outstanding. The derived media index is excluded from snapshot dumps: its asynchronous refresh may lag authoritative files, so preserving its rows would preserve stale file references. Both legacy and new database restores rebuild it atomically from local sidecars and video history before reopening admission. Unreadable sources or SQL failure keep recovery fenced for a same-operation retry, without replaying the dump. Full and media-selective file restores rebuild it too; a failed rebuild is reported as a reconciliation failure. This does not make unadmitted authoritative media workflows consistent.
Code Animation writes its HTML, revision trees and run artifacts before the row
that first names them. A generated animation's HTML and the job row marking it
@@ -297,8 +299,9 @@ grouped by domain with the modules whose file-plus-record workflows still run
outside admission, plus an `unclassified-durable-owners` entry for anything a
code sweep did not reach. Their persistence adapters and direct filesystem calls
still need workflow-level classification; independently locking `fileCore` or
-SQL primitives would not cover the gap between writes. No domain is excluded
-from the snapshot to satisfy the claim.
+SQL primitives would not cover the gap between writes. No authoritative asset domain is excluded
+from the snapshot to satisfy the claim; the derived media index is reconstructed
+from the authoritative files instead of preserving cache rows.
When wrapping one of them, remember the order a cut works in: it copies files,
then dumps rows. A row that names new bytes therefore has to commit under the
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 06fee816f8..8c57fdaaf4 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -249,7 +249,7 @@ goal data together; interrupted intents remain retryable after restore.
- Beeper attachment mirror (#37) — message media stays on disk under `data/beeper/attachments/<sha256 prefix>/<sha256>.<ext>` (content-addressed, so one forwarded photo is one file); `beeper_attachments` in PostgreSQL holds the metadata plus `local_path` / `sha256` / `byte_length` / `keep`. Machine-local and **never federated** (message content is PII — see the message-bodies ADR); a lazy CACHE rather than an archive, so it is excluded from backup by default (overridable) while the rows that describe it ride the Postgres dump. The bytes are re-fetchable from Beeper Desktop for as long as the source network still holds the media, and the surface renders a labelled reference when it does not.
- Media collections — many-to-many links over assets/universes/series/catalog media pointers (`db-primary` link tables) pointing at `asset-file-db-indexed` bytes. **Still `data/media-collections/*` JSON today** — a follow-up slice of #1000.
-**Media asset index (`media_assets`, #1000).** One row per generated image/video: `media_key` (`<kind>:<ref>`) PK, `kind`/`ref`/`created_at` mirror columns for queries, the full metadata record in `data` JSONB. It is a **derived index** — the on-disk sidecars + `video-history.json` stay authoritative — reconciled from disk at boot (upsert every asset, prune rows whose file is gone) and kept warm by a generation-`completed` hook. Local-only (rebuilt from disk), so no sync cursor/tombstone. Adapter: `server/services/mediaAssetIndex/{logic,db,index}.js`.
+**Media asset index (`media_assets`, #1000).** One row per generated image/video: `media_key` (`<kind>:<ref>`) PK, `kind`/`ref`/`created_at` mirror columns for queries, the full metadata record in `data` JSONB. It is a **derived index** — the on-disk sidecars + `video-history.json` stay authoritative — reconciled from disk at boot (upsert every asset, prune rows whose file is gone) and kept warm by a generation-`completed` hook. Local-only (rebuilt from disk), so no sync cursor/tombstone. Snapshot dumps exclude its rows; database restore atomically rebuilds it from the current local files before releasing recovery admission, and media file restores refresh it as well. Adapter: `server/services/mediaAssetIndex/{logic,db,index}.js`.
**Asset license provenance (#5638).** Every finished image and video stamps `data.provenance` at finalize time: the renderer/model id, every LoRA applied, and each one's license string and source URL *as known when the pixels were made*. Unknown stays `null` (displayed as "unknown") — never a permissive default. A license re-read months later can differ from the one in force at render, so the stamp is written into the authoritative sidecar / video-history row (the derived `media_assets.data` JSONB mirrors it). LoRA installs persist `license` on the `.metadata.json` sidecar so it is available at render rather than re-fetched. Collection and export surfaces roll the distinct sources up into an Attribution & licenses section.
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index 61efce2b65..f95cedeb0b 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -316,13 +316,12 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
],
},
{
- // Async completion hooks and full reconciliation read file-backed media
- // metadata before their derived Postgres writes, outside workflow admission.
- // Poster edits also leave old thumbnail metadata in this derived mirror.
- // Classify and verify the mirror's restore semantics in the final sweep;
- // admitting authoritative history alone does not settle these DB pointers.
+ // Derived rows are excluded from snapshot dumps. Restore reconstructs
+ // them from authoritative sidecars/history before releasing the DB fence;
+ // failed reads or SQL retain the fence and cannot report success. File
+ // restores refresh the same mirror. No asset bytes are owned here.
id: 'media-asset-index-refresh',
- status: 'outstanding',
+ status: 'reference-only',
modules: ['services/mediaAssetIndex/index.js', 'services/mediaAssetIndex/db.js'],
},
{
@@ -373,6 +372,12 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
status: 'admitted',
modules: ['services/digital-twin-documents.js', 'services/genome.js'],
},
+ {
+ // Explicit file cleanup can leave external references by design, but one
+ // lease keeps its single/bulk deletion out of a copy-then-dump snapshot.
+ id: 'operator-file-purge', status: 'admitted',
+ modules: ['services/dataManager.js', 'routes/uploads.js', 'routes/attachments.js'],
+ },
// Anything the sweep did not reach. A new asset owner lands here until it is
// classified; the claim cannot become `global` while this entry exists.
{ id: 'unclassified-durable-owners', status: 'outstanding', modules: [] },
diff --git a/server/lib/db.restoreRecovery.test.js b/server/lib/db.restoreRecovery.test.js
index 171fbaac90..012f244a87 100644
--- a/server/lib/db.restoreRecovery.test.js
+++ b/server/lib/db.restoreRecovery.test.js
@@ -39,6 +39,7 @@ vi.mock('../services/syncOrchestrator.js', () => ({
}));
// This suite isolates generic DB admission/release with a statement-free pg
// pool. Real execution-ledger SQL/capture/retry lives in the two DB fixtures.
+vi.mock('../services/mediaAssetIndex/db.js', () => ({ reconcileMediaAssets: vi.fn(async () => ({ ok: true })) }));
vi.mock('../services/peerExecutionRestore.js', () => ({
finishPeerExecutionRestore: vi.fn(async () => {
if (fixture.executionFault) throw Object.assign(new Error('synthetic execution reconciliation failure'), {
@@ -70,6 +71,8 @@ vi.mock('pg', async (importOriginal) => ({
}));
const { query, withTransaction, withDatabaseMaintenance, databaseRestoreRecovery } = await import('./db.js');
+const { acquireBackupSnapshotCut, withBackupAssetPublication } = await import('./backupSnapshotBoundary.js');
+const { reconcileMediaAssets } = await import('../services/mediaAssetIndex/db.js');
const { resumeDatabaseRestore, getDatabaseRestoreRecoveryStatus } = await import('../services/backupRestoreRecovery.js');
@@ -87,6 +90,67 @@ beforeEach(() => {
afterAll(() => rmSync(fixture.dataRoot, { recursive: true, force: true }));
describe('restore recovery admission', () => {
+ it('drains file publication before same-ID recovery and blocks later publication through media repair', async () => {
+ const record = databaseRestoreRecovery.markCommitted(begin().id);
+ const published = join(fixture.dataRoot, 'synthetic-history.json');
+ writeFileSync(published, 'before');
+ const firstReady = Promise.withResolvers();
+ const finishFirst = Promise.withResolvers();
+ const mediaReady = Promise.withResolvers();
+ const finishMedia = Promise.withResolvers();
+ const first = withBackupAssetPublication(async () => {
+ firstReady.resolve();
+ await finishFirst.promise;
+ writeFileSync(published, 'settled');
+ });
+ await firstReady.promise;
+ reconcileMediaAssets.mockImplementationOnce(async () => {
+ expect(readFileSync(published, 'utf8')).toBe('settled');
+ mediaReady.resolve();
+ await finishMedia.promise;
+ expect(readFileSync(published, 'utf8')).toBe('settled');
+ return { ok: true };
+ });
+ const recovery = resumeDatabaseRestore(record.id);
+ let laterPublished = false;
+ const later = withBackupAssetPublication(() => {
+ laterPublished = true;
+ writeFileSync(published, 'later');
+ });
+ try {
+ await new Promise(resolve => setImmediate(resolve));
+ expect(reconcileMediaAssets).not.toHaveBeenCalled();
+ expect(laterPublished).toBe(false);
+ expect(databaseRestoreRecovery.read()).toEqual(record);
+ finishFirst.resolve();
+ await mediaReady.promise;
+ expect(laterPublished).toBe(false);
+ await expect(query('SELECT ordinary')).rejects.toMatchObject({ code: 'DATABASE_MAINTENANCE' });
+ finishMedia.resolve();
+ expect(await recovery).toMatchObject({ status: 'ok', outcome: 'repaired' });
+ await later;
+ expect(readFileSync(published, 'utf8')).toBe('later');
+ expect(getDatabaseRestoreRecoveryStatus()).toEqual({ pending: false });
+ } finally {
+ finishFirst.resolve(); finishMedia.resolve();
+ await Promise.allSettled([first, recovery, later]);
+ }
+ });
+
+ it('does not release a competing snapshot cut or change the pending operation', async () => {
+ const record = databaseRestoreRecovery.markCommitted(begin().id);
+ const release = await acquireBackupSnapshotCut();
+ let published = false;
+ const waiting = withBackupAssetPublication(() => { published = true; });
+ try {
+ await expect(resumeDatabaseRestore(record.id)).rejects.toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY' });
+ expect(databaseRestoreRecovery.read()).toEqual(record);
+ expect(reconcileMediaAssets).not.toHaveBeenCalled();
+ expect(published).toBe(false);
+ } finally { release(); await waiting; }
+ expect(await resumeDatabaseRestore(record.id)).toMatchObject({ status: 'ok', outcome: 'repaired' });
+ });
+
it('retains generic admission when execution reconciliation fails and releases only after same-ID retry succeeds', async () => {
const record = databaseRestoreRecovery.markCommitted(begin().id);
fixture.executionFault = true;
diff --git a/server/routes/attachments.js b/server/routes/attachments.js
index 0a446ef3e3..554f1ad450 100644
--- a/server/routes/attachments.js
+++ b/server/routes/attachments.js
@@ -4,6 +4,7 @@
*/
import { Router } from 'express';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { readdir, stat } from 'fs/promises';
import { join, resolve } from 'path';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
@@ -52,7 +53,7 @@ router.get('/:filename', asyncHandler(async (req, res) => {
}));
// DELETE /api/attachments/:filename - Delete an attachment
-router.delete('/:filename', asyncHandler(async (req, res) => {
+router.delete('/:filename', asyncHandler(async (req, res) => withBackupAssetPublication(async () => {
const { filename } = req.params;
const safeFilename = sanitizeFilename(filename);
const filepath = resolve(ATTACHMENTS_DIR, safeFilename);
@@ -71,7 +72,7 @@ router.delete('/:filename', asyncHandler(async (req, res) => {
console.log(`🗑️ Attachment deleted: ${safeFilename}`);
res.json({ success: true, filename: safeFilename });
-}));
+})));
// GET /api/attachments - List all attachments (for debugging)
router.get('/', asyncHandler(async (req, res) => {
diff --git a/server/routes/uploads.js b/server/routes/uploads.js
index 2fcc7f6f78..183bb779af 100644
--- a/server/routes/uploads.js
+++ b/server/routes/uploads.js
@@ -4,6 +4,7 @@
*/
import { Router } from 'express';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { readdir, stat } from 'fs/promises';
import { join, resolve } from 'path';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
@@ -133,7 +134,7 @@ router.get('/:filename', asyncHandler(async (req, res) => {
}));
// DELETE /api/uploads/:filename - Delete a file
-router.delete('/:filename', asyncHandler(async (req, res) => {
+router.delete('/:filename', asyncHandler(async (req, res) => withBackupAssetPublication(async () => {
const { filename } = req.params;
const safeFilename = sanitizeFilename(filename);
const filepath = resolve(UPLOADS_DIR, safeFilename);
@@ -152,10 +153,10 @@ router.delete('/:filename', asyncHandler(async (req, res) => {
console.log(`🗑️ File deleted: ${safeFilename} (${formatSize(stats.size)})`);
res.json({ success: true, filename: safeFilename, size: stats.size });
-}));
+})));
// DELETE /api/uploads - Delete all files
-router.delete('/', asyncHandler(async (req, res) => {
+router.delete('/', asyncHandler(async (req, res) => withBackupAssetPublication(async () => {
const { confirm } = req.query;
if (confirm !== 'true') {
@@ -184,6 +185,6 @@ router.delete('/', asyncHandler(async (req, res) => {
freedSpace,
freedSpaceFormatted: formatSize(freedSpace)
});
-}));
+})));
export default router;
diff --git a/server/services/assetPurge.backup.test.js b/server/services/assetPurge.backup.test.js
new file mode 100644
index 0000000000..59bb49daaf
--- /dev/null
+++ b/server/services/assetPurge.backup.test.js
@@ -0,0 +1,68 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { acquireBackupSnapshotCut } from '../lib/backupSnapshotBoundary.js';
+
+const fixture = vi.hoisted(() => ({ root: null, beforeDelete: null }));
+vi.mock('../lib/fileUtils.js', async importOriginal => {
+ const actual = await importOriginal();
+ fixture.root = await mkdtemp(join(tmpdir(), 'portos-asset-purge-'));
+ return { ...actual, PATHS: { ...actual.PATHS, data: fixture.root,
+ images: join(fixture.root, 'images'), uploads: join(fixture.root, 'uploads'),
+ cosAttachments: join(fixture.root, 'attachments') },
+ rmGuarded: async (...args) => { await fixture.beforeDelete?.(); return actual.rmGuarded(...args); },
+ unlinkGuarded: async (...args) => { await fixture.beforeDelete?.(); return actual.unlinkGuarded(...args); } };
+});
+const { purgeCategory } = await import('./dataManager.js');
+const { default: uploads } = await import('../routes/uploads.js');
+const { default: attachments } = await import('../routes/attachments.js');
+const app = express();
+app.use('/uploads', uploads);
+app.use('/attachments', attachments);
+app.use(errorMiddleware);
+const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; };
+
+beforeEach(async () => {
+ fixture.beforeDelete = null;
+ for (const folder of ['images', 'messages', 'uploads', 'attachments']) {
+ await mkdir(join(fixture.root, folder), { recursive: true });
+ await writeFile(join(fixture.root, folder, 'one.txt'), 'first');
+ await writeFile(join(fixture.root, folder, 'two.txt'), 'second');
+ }
+});
+afterAll(() => rm(fixture.root, { recursive: true, force: true }));
+
+describe('operator file purges drain before a backup copies files', () => {
+ it.each([
+ ['category item', 'images', false, () => purgeCategory('images', { subPath: 'one.txt' })],
+ ['category bulk', 'messages', true, () => purgeCategory('messages')],
+ ['upload item', 'uploads', false, () => request(app).delete('/uploads/one.txt')],
+ ['upload bulk', 'uploads', true, () => request(app).delete('/uploads?confirm=true')],
+ ['attachment', 'attachments', false, () => request(app).delete('/attachments/one.txt')],
+ ])('%s finishes all removals before the snapshot begins', async (_name, folder, bulk, invoke) => {
+ const entered = deferred();
+ const proceed = deferred();
+ fixture.beforeDelete = async () => { entered.resolve(); await proceed.promise; };
+ const operation = Promise.resolve(invoke());
+ await entered.promise;
+ let acquired = false;
+ const cut = acquireBackupSnapshotCut().then(release => { acquired = true; return release; });
+ try {
+ await new Promise(resolve => setImmediate(resolve));
+ expect(acquired, 'a snapshot must wait for the entire admitted deletion').toBe(false);
+ expect(await readFile(join(fixture.root, folder, 'one.txt'), 'utf8')).toBe('first');
+ } finally {
+ proceed.resolve();
+ await operation;
+ const release = await cut;
+ release();
+ }
+ await expect(readFile(join(fixture.root, folder, 'one.txt'))).rejects.toMatchObject({ code: 'ENOENT' });
+ if (bulk) await expect(readFile(join(fixture.root, folder, 'two.txt'))).rejects.toMatchObject({ code: 'ENOENT' });
+ else expect(await readFile(join(fixture.root, folder, 'two.txt'), 'utf8')).toBe('second');
+ });
+});
diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.js
index 12a15aa86a..7d8a8a4614 100644
--- a/server/services/backup.db.test.js
+++ b/server/services/backup.db.test.js
@@ -16,6 +16,8 @@ import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.
// The real rewind rewrites this install's data/instances_sync_cursors.json.
const rewindPostgresSyncCursors = vi.hoisted(() => vi.fn(async () => 0));
vi.mock('./syncOrchestrator.js', () => ({ rewindPostgresSyncCursors }));
+// Restore schema fixtures own no gallery files; never scan the live install.
+vi.mock('./imageGen/local.js', () => ({ listGallery: async () => [] }));
// The restore recovery journal (#9725) lives in data/ and fences the pool; keep
// it in a disposable data root, never the install's live tree.
const dataRoot = vi.hoisted(() => ({ path: null }));
diff --git a/server/services/backup.js b/server/services/backup.js
index f795318454..1a2c3e9990 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -778,6 +778,9 @@ export async function dumpPostgres(outputPath) {
// Machine-local replay receipts (#9725) describe this install's past
// restores, not application data; the table definition is still dumped.
'--exclude-table-data=restore_receipts',
+ // The asynchronous media mirror can lag its authoritative files. Rebuild
+ // it after restore rather than snapshotting stale file references.
+ '--exclude-table-data=media_assets',
'-f', outputPath
], {
shell: false,
@@ -1238,6 +1241,13 @@ async function reconcileLiveFileRestore(subdirFilter) {
? [{ label: 'Brain cache invalidation', run: invalidateBrainCaches }]
: []),
{ label: 'settings reload', run: reloadSettings },
+ ...((!subdirFilter || ['images', 'videos', 'video-thumbnails', 'video-history.json']
+ .some(path => subdirFilter === path || subdirFilter.startsWith(`${path}/`)))
+ && getBackendName() !== 'file'
+ ? [{ label: 'media index rebuild', run: async () => {
+ const { reconcileMediaAssets } = await import('./mediaAssetIndex/db.js');
+ await reconcileMediaAssets({ rebuild: true });
+ } }] : []),
];
const results = await Promise.allSettled(
refreshes.map(({ run }) => Promise.resolve().then(run)),
@@ -1248,7 +1258,7 @@ async function reconcileLiveFileRestore(subdirFilter) {
if (failures.length > 0) {
throw new Error(
- `Live restore cache reconciliation failed (${failures.join('; ')}). Restart PortOS before relying on restored settings or Brain data.`,
+ `Live restore cache reconciliation failed (${failures.join('; ')}). Restart PortOS before relying on restored settings, Brain data or media.`,
{ cause: results.find(result => result.status === 'rejected').reason },
);
}
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index de823899fa..2673b3a7a1 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -73,6 +73,8 @@ vi.mock('../lib/databaseMaintenanceJournal.js', () => ({
vi.mock('../scripts/run-db-migrations.js', () => ({
runDbMigrations: vi.fn().mockResolvedValue(0),
}));
+const reconcileMediaAssets = vi.hoisted(() => vi.fn().mockResolvedValue({ ok: true }));
+vi.mock('./mediaAssetIndex/db.js', () => ({ reconcileMediaAssets }));
const executionRestore = vi.hoisted(() => ({ prepare: vi.fn(), finish: vi.fn() }));
vi.mock('./peerExecutionRestore.js', () => ({
preparePeerExecutionRestore: executionRestore.prepare,
@@ -979,6 +981,7 @@ describe('dumpPostgres status classification', () => {
const result = dumpPostgres('/tmp/example.sql');
await flush();
assertPoolToolSpawn(spawn.mock.calls[0]);
+ expect(spawn.mock.calls[0][1]).toContain('--exclude-table-data=media_assets');
proc.emit('close', 0);
expect(await result).toMatchObject({ status: 'ok' });
vi.unstubAllEnvs();
@@ -1553,6 +1556,7 @@ describe('restorePostgres', () => {
it.each([
['schema upgrade', () => ensureSchema.mockRejectedValueOnce(new Error('ddl failed')), 'restore_schema_reconciliation'],
['ordered migration', () => runDbMigrations.mockRejectedValueOnce(new Error('migration failed')), 'restore_schema_reconciliation'],
+ ['media rebuild', () => reconcileMediaAssets.mockRejectedValueOnce(new Error('media read failed')), 'restore_media_reconciliation'],
['cursor write', () => rewindPostgresSyncCursors.mockRejectedValueOnce(new Error('disk full')), 'restore_sync_resync'],
])('a %s fault after commit stays fenced, then recovery repairs from the original floors without replaying', async (_case, inject, reason) => {
inject();
@@ -3255,6 +3259,7 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
expect(reloadSettings).toHaveBeenCalledTimes(1);
expect(invalidateBrainCaches).toHaveBeenCalledTimes(1);
+ expect(reconcileMediaAssets).toHaveBeenCalledWith({ rebuild: true });
// A live restore must not pass --dry-run to rsync.
expect(spawn.mock.calls[0][1]).not.toContain('--dry-run');
});
@@ -3269,6 +3274,7 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
await runRestore('/dest', 'snap-1', { dryRun: false, subdirFilter: 'images' });
expect(invalidateBrainCaches).not.toHaveBeenCalled();
+ expect(reconcileMediaAssets).toHaveBeenCalledWith({ rebuild: true });
});
it('does not reload settings for a dry run', async () => {
@@ -3277,6 +3283,7 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
expect(reloadSettings).not.toHaveBeenCalled();
expect(invalidateBrainCaches).not.toHaveBeenCalled();
expect(spawn.mock.calls[0][1]).toContain('--dry-run');
+ expect(reconcileMediaAssets).not.toHaveBeenCalled();
});
it('defaults to a dry run (no settings reload) when no options are given', async () => {
diff --git a/server/services/backupRestoreRecovery.js b/server/services/backupRestoreRecovery.js
index e8bf2cd9b0..6af1cd27d0 100644
--- a/server/services/backupRestoreRecovery.js
+++ b/server/services/backupRestoreRecovery.js
@@ -12,6 +12,7 @@
import { databaseRestoreRecovery, ensureSchema, query, withDatabaseMaintenance } from '../lib/db.js';
import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.js';
import { restoreReceiptsDdl } from '../lib/db/schema/core.js';
+import { acquireBackupSnapshotCut } from '../lib/backupSnapshotBoundary.js';
// Ties the replay's psql session to its operation, so recovery can prove no
// session of that replay is still able to commit before reading "no receipt"
@@ -32,6 +33,7 @@ const MESSAGES = {
restore_commit_unknown: 'The restore could not confirm whether the database dump was committed. Ordinary database work stays paused and the dump will NOT be replayed; retry recovery from Settings > Backup once PostgreSQL is reachable.',
restore_schema_reconciliation: 'The database dump was applied, but schema recovery is incomplete. It was not rolled back and will not be replayed. Ordinary database work stays paused: retry recovery from Settings > Backup, or restart PortOS to retry automatically. If it keeps failing, check the server logs.',
restore_execution_reconciliation: 'Execution request consumption and unresolved ownership are awaiting reconciliation. Database work stays paused; the dump will not be replayed. Recovery retries automatically at startup and can also be retried from Settings > Backup.',
+ restore_media_reconciliation: 'The database dump was applied, but the media index could not be rebuilt from local files. It will not be replayed. Ordinary database work stays paused: retry recovery from Settings > Backup, or restart PortOS.',
restore_sync_resync: 'The database dump was applied, but peer sync could not be reset yet. It will not be replayed. Ordinary database work stays paused: retry recovery from Settings > Backup, or restart PortOS to retry automatically.',
restore_recovery_release: 'The database dump was applied and repaired, but the recovery journal could not be cleared. Ordinary database work stays paused: retry recovery from Settings > Backup.',
restore_recovery_pending: 'A previous database restore is awaiting recovery. Finish it from Settings > Backup before starting another restore.',
@@ -169,6 +171,16 @@ export async function repairCommittedRestore(record) {
console.error(`❌ DB restore ${record.id}: schema reconciliation failed: ${reconciliationError.message}`);
return pendingRecoveryResult('restore_schema_reconciliation', record);
}
+ // Old snapshots may contain stale mirror rows; new snapshots omit them.
+ // Either way disk is authoritative, including for a DB-only restore.
+ const mediaError = await (async () => {
+ const { reconcileMediaAssets } = await import('./mediaAssetIndex/db.js');
+ await reconcileMediaAssets({ rebuild: true });
+ })().then(() => null, error => error);
+ if (mediaError) {
+ console.error(`❌ DB restore ${record.id}: media reconciliation failed: ${mediaError.message}`);
+ return pendingRecoveryResult('restore_media_reconciliation', record);
+ }
const executionError = await (async () => {
const { finishPeerExecutionRestore } = await import('./peerExecutionRestore.js');
await finishPeerExecutionRestore(record.id);
@@ -235,17 +247,27 @@ export async function resumeDatabaseRestore(id) {
if (id && record.id !== id) {
throw Object.assign(new Error('A different database restore operation is pending.'), { status: 409, code: 'RESTORE_RECOVERY_MISMATCH' });
}
- return withDatabaseMaintenance(async () => {
- // Re-read inside maintenance: another resume may have finished meanwhile.
- let current = databaseRestoreRecovery.read();
- if (current?.id !== record.id) return { status: 'ok', outcome: 'none' };
- if (current.stage === 'replaying') {
- const settled = await settleReplayOutcome(current);
- if (settled.outcome === 'rolled_back') return { status: 'ok', outcome: 'rolled_back' };
- if (settled.outcome === 'uncertain') return pendingRecoveryResult(settled.reason ?? 'restore_commit_unknown', current);
- current = settled.record;
- }
- const repaired = await repairCommittedRestore(current);
- return repaired.status === 'ok' ? { ...repaired, outcome: 'repaired' } : repaired;
- }, { restoreRecoveryId: record.id });
+ // Initial replay holds this boundary, but a failed repair releases it while
+ // retaining the same-operation DB fence. Reacquire before DB maintenance:
+ // draining publications may still need the DB to finish their settlement.
+ // Keep file-backed authorities stable through the media rebuild on retries
+ // and restart, and release only this recovery attempt's cut on every outcome.
+ const releaseSnapshotCut = await acquireBackupSnapshotCut();
+ try {
+ return await withDatabaseMaintenance(async () => {
+ // Re-read inside maintenance: another resume may have finished meanwhile.
+ let current = databaseRestoreRecovery.read();
+ if (current?.id !== record.id) return { status: 'ok', outcome: 'none' };
+ if (current.stage === 'replaying') {
+ const settled = await settleReplayOutcome(current);
+ if (settled.outcome === 'rolled_back') return { status: 'ok', outcome: 'rolled_back' };
+ if (settled.outcome === 'uncertain') return pendingRecoveryResult(settled.reason ?? 'restore_commit_unknown', current);
+ current = settled.record;
+ }
+ const repaired = await repairCommittedRestore(current);
+ return repaired.status === 'ok' ? { ...repaired, outcome: 'repaired' } : repaired;
+ }, { restoreRecoveryId: record.id });
+ } finally {
+ releaseSnapshotCut();
+ }
}
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 737c884301..f20c617aa2 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -6,6 +6,7 @@ import { promisify } from 'util';
import { parseFilesystemStats } from '../lib/fileCore.js';
import { PATHS, ensureDir, isTopLevelEntryName, rmGuarded, writeFileGuarded } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import {
federatedMediaInboxBusy, imageCleanTmpBusy, trainingRunsBusy, updateDetachedBusy,
} from './dataManagerBusy.js';
@@ -444,80 +445,84 @@ export async function archiveCategory(categoryKey, options = {}) {
}
export async function purgeCategory(categoryKey, options = {}) {
- if (!SAFE_NAME.test(categoryKey)) throw new ServerError('Invalid category name', { status: 400, code: 'VALIDATION_ERROR' });
- const meta = CATEGORIES[categoryKey];
- if (!meta?.deletable) {
- throw new ServerError(`Category "${categoryKey}" is not purgeable`, { status: 403, code: 'CATEGORY_NOT_PURGEABLE' });
- }
- // "Caller asked for one entry" is keyed on the option being PRESENT, not on
- // it being truthy: `{ subPath: '' }` is a caller that meant to name something
- // and produced nothing, and must 400 — not fall through to the branch that
- // empties the whole directory (#3327).
- const wantsItem = options.subPath !== undefined && options.subPath !== null;
- if (wantsItem && !isTopLevelEntryName(options.subPath)) {
- // Refusing separators outright means no traversal segment can form and, more
- // importantly, no *intermediate* component can be a symlink for `rm` to
- // follow out of the category — the lexical containment check below never
- // touches the filesystem, so it cannot see that.
- throw new ServerError('subPath must name a single entry in the category', { status: 400, code: 'VALIDATION_ERROR' });
- }
- // Item-scoped categories only ever lose one entry at a time. Written as
- // "must be exactly 'category'" so an absent or misspelled scope refuses the
- // wipe instead of inheriting the old all-or-nothing behavior (#3327).
- if (!wantsItem && meta.purgeScope !== 'category') {
- throw new ServerError(
- `Category "${categoryKey}" only supports per-item purge — pass a subPath`,
- { status: 400, code: 'CATEGORY_ITEM_PURGE_ONLY' }
- );
- }
-
- const dirPath = join(DATA_DIR, categoryKey);
- if (!existsSync(dirPath)) {
- throw new ServerError(`Category directory not found: ${categoryKey}`, { status: 404, code: 'NOT_FOUND' });
- }
+ // A purge may retain external record references by explicit operator choice,
+ // but its deletions must never interleave with a snapshot's copy and dump.
+ return withBackupAssetPublication(async () => {
+ if (!SAFE_NAME.test(categoryKey)) throw new ServerError('Invalid category name', { status: 400, code: 'VALIDATION_ERROR' });
+ const meta = CATEGORIES[categoryKey];
+ if (!meta?.deletable) {
+ throw new ServerError(`Category "${categoryKey}" is not purgeable`, { status: 403, code: 'CATEGORY_NOT_PURGEABLE' });
+ }
+ // "Caller asked for one entry" is keyed on the option being PRESENT, not on
+ // it being truthy: `{ subPath: '' }` is a caller that meant to name something
+ // and produced nothing, and must 400 — not fall through to the branch that
+ // empties the whole directory (#3327).
+ const wantsItem = options.subPath !== undefined && options.subPath !== null;
+ if (wantsItem && !isTopLevelEntryName(options.subPath)) {
+ // Refusing separators outright means no traversal segment can form and, more
+ // importantly, no *intermediate* component can be a symlink for `rm` to
+ // follow out of the category — the lexical containment check below never
+ // touches the filesystem, so it cannot see that.
+ throw new ServerError('subPath must name a single entry in the category', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ // Item-scoped categories only ever lose one entry at a time. Written as
+ // "must be exactly 'category'" so an absent or misspelled scope refuses the
+ // wipe instead of inheriting the old all-or-nothing behavior (#3327).
+ if (!wantsItem && meta.purgeScope !== 'category') {
+ throw new ServerError(
+ `Category "${categoryKey}" only supports per-item purge — pass a subPath`,
+ { status: 400, code: 'CATEGORY_ITEM_PURGE_ONLY' }
+ );
+ }
- // A named directory can still contain a live job's working state. Apply
- // the same fail-closed busy probe to both deletion scopes.
- const { busy, busyReason } = await resolveCategoryBusy(categoryKey);
- if (busy) throw new ServerError(busyReason, { status: 409, code: 'CATEGORY_BUSY' });
-
- if (wantsItem) {
- const resolvedRoot = resolve(dirPath);
- const resolvedTarget = resolve(join(dirPath, options.subPath));
- // Boundary-aware containment check: use path.relative so a prefix like
- // `/data/cat` cannot satisfy containment for `/data/cat2`.
- const rel = relative(resolvedRoot, resolvedTarget);
- if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
- throw new ServerError('Invalid subPath', { status: 400, code: 'VALIDATION_ERROR' });
+ const dirPath = join(DATA_DIR, categoryKey);
+ if (!existsSync(dirPath)) {
+ throw new ServerError(`Category directory not found: ${categoryKey}`, { status: 404, code: 'NOT_FOUND' });
}
- // Item-scoped categories are flat directories of assets; their only
- // subdirectories are working state for other features (`data/videos/.detached`
- // holds the control files of in-flight renders). A one-click recursive
- // delete next to those on a cleanup page is a foot-gun, so an item purge
- // removes a single file and never recurses. `lstat`, not `stat`, so a
- // symlinked entry is judged as the link it is and simply unlinked.
- const itemScoped = meta.purgeScope === 'items';
- if (itemScoped) {
- const entryStat = await lstat(resolvedTarget).catch(() => null);
- if (!entryStat) {
- throw new ServerError(`Item not found in "${categoryKey}"`, { status: 404, code: 'NOT_FOUND' });
+
+ // A named directory can still contain a live job's working state. Apply
+ // the same fail-closed busy probe to both deletion scopes.
+ const { busy, busyReason } = await resolveCategoryBusy(categoryKey);
+ if (busy) throw new ServerError(busyReason, { status: 409, code: 'CATEGORY_BUSY' });
+
+ if (wantsItem) {
+ const resolvedRoot = resolve(dirPath);
+ const resolvedTarget = resolve(join(dirPath, options.subPath));
+ // Boundary-aware containment check: use path.relative so a prefix like
+ // `/data/cat` cannot satisfy containment for `/data/cat2`.
+ const rel = relative(resolvedRoot, resolvedTarget);
+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
+ throw new ServerError('Invalid subPath', { status: 400, code: 'VALIDATION_ERROR' });
}
- if (entryStat.isDirectory()) {
- throw new ServerError(
- `"${options.subPath}" is a directory — per-item purge in "${categoryKey}" only removes files`,
- { status: 400, code: 'ITEM_PURGE_FILE_ONLY' }
- );
+ // Item-scoped categories are flat directories of assets; their only
+ // subdirectories are working state for other features (`data/videos/.detached`
+ // holds the control files of in-flight renders). A one-click recursive
+ // delete next to those on a cleanup page is a foot-gun, so an item purge
+ // removes a single file and never recurses. `lstat`, not `stat`, so a
+ // symlinked entry is judged as the link it is and simply unlinked.
+ const itemScoped = meta.purgeScope === 'items';
+ if (itemScoped) {
+ const entryStat = await lstat(resolvedTarget).catch(() => null);
+ if (!entryStat) {
+ throw new ServerError(`Item not found in "${categoryKey}"`, { status: 404, code: 'NOT_FOUND' });
+ }
+ if (entryStat.isDirectory()) {
+ throw new ServerError(
+ `"${options.subPath}" is a directory — per-item purge in "${categoryKey}" only removes files`,
+ { status: 400, code: 'ITEM_PURGE_FILE_ONLY' }
+ );
+ }
}
+ await rmGuarded(resolvedTarget, { recursive: !itemScoped, force: true });
+ console.log(`🗑️ Purged item from data/${categoryKey}`);
+ } else {
+ const entries = await readdir(dirPath).catch(() => []);
+ await Promise.all(entries.map(entry => rmGuarded(join(dirPath, entry), { recursive: true, force: true })));
+ console.log(`🗑️ Purged all ${entries.length} entries from data/${categoryKey}`);
}
- await rmGuarded(resolvedTarget, { recursive: !itemScoped, force: true });
- console.log(`🗑️ Purged item from data/${categoryKey}`);
- } else {
- const entries = await readdir(dirPath).catch(() => []);
- await Promise.all(entries.map(entry => rmGuarded(join(dirPath, entry), { recursive: true, force: true })));
- console.log(`🗑️ Purged all ${entries.length} entries from data/${categoryKey}`);
- }
- return { category: categoryKey, subPath: wantsItem ? options.subPath : null };
+ return { category: categoryKey, subPath: wantsItem ? options.subPath : null };
+ });
}
export async function getBackups() {
diff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.js
index ff687a57fa..1a013969dd 100644
--- a/server/services/mediaAssetIndex/db.js
+++ b/server/services/mediaAssetIndex/db.js
@@ -22,10 +22,15 @@
* without it.
*/
-import { readFile } from 'fs/promises';
+import { readFile, readdir, stat } from 'fs/promises';
import { join } from 'path';
-import { query } from '../../lib/db.js';
+import { query, withTransaction } from '../../lib/db.js';
import { dedupeByKey } from '../../lib/arrayUtils.js';
+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
+
+// Queue the complete source-read → mirror-write flow, not merely SQL, so an
+// old completion hook cannot overwrite a restore's newer reconstruction.
+export const queueMediaIndexRefresh = createFileWriteQueue();
import {
imageToRow, videoToRow, compactGalleryRecord, compactSource, compactSourceToRow,
COMPACT_SOURCE_FIELDS, COMPACT_PREVIEW_KEY, COMPACT_PROMPT_CHARS,
@@ -59,7 +64,7 @@ export async function upsertAsset(row) {
// Upsert many rows in chunked multi-row INSERTs so reconcile (which runs every
// boot over the whole gallery) is a handful of round-trips, not one-per-asset.
const UPSERT_CHUNK = 500;
-async function upsertAssets(rows) {
+async function upsertAssets(rows, runQuery = query) {
// Collapse duplicate media_keys BEFORE chunking (see `dedupeByKey` for why a
// multi-row upsert cannot carry a repeated conflict key). Untreated, one throw
// aborted the WHOLE reconcile — a single duplicated gallery filename or
@@ -78,7 +83,7 @@ async function upsertAssets(rows) {
values.push(`($${b + 1}, $${b + 2}, $${b + 3}, $${b + 4}::jsonb, $${b + 5}, NOW())`);
params.push(row.mediaKey, row.kind, row.ref, JSON.stringify(row.data), row.createdAt);
});
- await query(
+ await runQuery(
`INSERT INTO media_assets (media_key, kind, ref, data, created_at, indexed_at)
VALUES ${values.join(', ')}
${UPSERT_CONFLICT}`,
@@ -357,6 +362,34 @@ export async function readVideoHistoryStrict(historyPath) {
return { ok: true, list: parsed };
}
+// Restore must distinguish an absent gallery/sidecar from an unreadable or
+// corrupt one. The interactive gallery intentionally tolerates both, which
+// is inappropriate when replacing every restored cache row.
+async function readGalleryForRestore() {
+ const { PATHS } = await import('../../lib/fileUtils.js');
+ let files;
+ try { files = await readdir(PATHS.images); }
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
+ const images = [];
+ for (const filename of files.filter(name => /\.png$/i.test(name))) {
+ const info = await stat(join(PATHS.images, filename));
+ if (!info.isFile()) throw new Error('Media gallery contains a non-file image');
+ let metadata = {};
+ for (const sidecar of [filename.replace(/\.png$/i, '.metadata.json'), `${filename}.metadata.json`]) {
+ let raw;
+ try { raw = await readFile(join(PATHS.images, sidecar), 'utf8'); }
+ catch (error) { if (error.code === 'ENOENT') continue; throw error; }
+ metadata = JSON.parse(raw);
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {
+ throw new Error('Media gallery sidecar must contain an object');
+ }
+ break;
+ }
+ images.push({ filename, path: `/data/images/${filename}`, createdAt: info.birthtime.toISOString(), ...metadata });
+ }
+ return images;
+}
+
// Wrap a reader so a thrown error becomes { ok:false } rather than a trusted
// empty list (the listGallery path throws on real I/O errors like EACCES/EIO).
async function readListStrict(fn) {
@@ -386,14 +419,19 @@ async function readListStrict(fn) {
* readers go through the same strict failure-vs-empty wrapper, so a throwing
* reader uniformly skips that kind's prune rather than wiping it.
*/
-export async function reconcileMediaAssets(deps = {}) {
+export function reconcileMediaAssets(deps = {}) {
+ return queueMediaIndexRefresh(() => reconcileNow(deps));
+}
+
+async function reconcileNow(deps) {
const now = new Date().toISOString();
// Rows indexed after this instant (a generation/upload/peer sync landing
// mid-reconcile) are absent from the disk snapshot but must not be pruned.
const startedAt = now;
const imageRead = await readListStrict(
- deps.listGallery || (await import('../imageGen/local.js')).listGallery,
+ deps.listGallery || (deps.rebuild || deps.requireComplete
+ ? readGalleryForRestore : (await import('../imageGen/local.js')).listGallery),
);
// The video default path needs the file-level missing-vs-corrupt distinction
// (loadHistory collapses both to []); an injected reader returns an array, so
@@ -407,6 +445,21 @@ export async function reconcileMediaAssets(deps = {}) {
const videoRows = (Array.isArray(videoRead.list) ? videoRead.list : [])
.map((v) => videoToRow(v, { now })).filter(Boolean);
+ // Restore cannot retain old or partially reconstructed cache rows. Read both
+ // authorities first, then replace the mirror atomically; a failed read is
+ // never a trusted empty gallery. This also removes future-dated legacy rows
+ // that the ordinary concurrent-generation prune deliberately preserves.
+ if ((deps.rebuild || deps.requireComplete) && (!imageRead.ok || !videoRead.ok)) {
+ throw new Error('Media index rebuild could not read authoritative files');
+ }
+ if (deps.rebuild) {
+ return withTransaction(async (client) => {
+ const removed = await client.query('DELETE FROM media_assets');
+ const indexed = await upsertAssets([...imageRows, ...videoRows], client.query.bind(client));
+ return { ok: true, indexed, pruned: removed.rowCount || 0, skippedPrune: [] };
+ });
+ }
+
// Rows WRITTEN, which is below the rows read when disk repeated a ref.
const indexed = await upsertAssets([...imageRows, ...videoRows]);
diff --git a/server/services/mediaAssetIndex/db.test.js b/server/services/mediaAssetIndex/db.test.js
index 2c799cceb5..950772ca0c 100644
--- a/server/services/mediaAssetIndex/db.test.js
+++ b/server/services/mediaAssetIndex/db.test.js
@@ -11,6 +11,18 @@
import { describe, it, expect, afterAll, beforeAll, vi } from 'vitest';
import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
import { requireDbOrSkip } from '../../lib/dbTestGate.js';
+import { writeFile, mkdir, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+
+const gallery = vi.hoisted(() => ({ root: null }));
+vi.mock('../../lib/fileUtils.js', async importOriginal => {
+ const actual = await importOriginal();
+ const { mkdtemp } = await import('node:fs/promises');
+ const { tmpdir } = await import('node:os');
+ gallery.root = await mkdtemp(join(tmpdir(), 'portos-index-restore-'));
+ return { ...actual, PATHS: { ...actual.PATHS, images: join(gallery.root, 'images'), data: gallery.root } };
+});
+afterAll(async () => { if (gallery.root) await rm(gallery.root, { recursive: true, force: true }); });
vi.mock('../../lib/db.js', async importOriginal => {
const actual = await importOriginal();
@@ -230,6 +242,64 @@ describe.skipIf(!runDb)('media asset index DB round-trip', () => {
expect(vids.some((x) => x.id === `${PFX}vid1`)).toBe(true);
});
+ it('rejects corrupt or non-file gallery sources instead of silently replacing restored metadata', async () => {
+ // Invoke the real restore reader, not an injected permissive gallery list.
+ await db.reconcileMediaAssets({ rebuild: true });
+ const dir = join(gallery.root, 'images');
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'example.PNG'), 'pixels');
+ await writeFile(join(dir, 'example.PNG.metadata.json'), JSON.stringify({ prompt: 'retained metadata' }));
+ await db.reconcileMediaAssets({ rebuild: true });
+ expect(await db.listAssets()).toEqual([expect.objectContaining({ filename: 'example.PNG', prompt: 'retained metadata' })]);
+ const before = await db.listAssets();
+ await writeFile(join(dir, 'example.metadata.json'), '{broken');
+ await expect(db.reconcileMediaAssets({ rebuild: true })).rejects.toThrow('authoritative files');
+ expect(await db.listAssets()).toEqual(before);
+ await rm(join(dir, 'example.metadata.json'));
+ await mkdir(join(dir, 'not-an-image.png'));
+ await expect(db.reconcileMediaAssets({ rebuild: true })).rejects.toThrow('authoritative files');
+ expect(await db.listAssets()).toEqual(before);
+ await rm(dir, { recursive: true });
+ });
+
+ it('drains an earlier source read before a restore rebuild can replace its mirror', async () => {
+ let start, finish;
+ const entered = new Promise(resolve => { start = resolve; });
+ const proceed = new Promise(resolve => { finish = resolve; });
+ const stale = db.reconcileMediaAssets({ listGallery: async () => {
+ start(); await proceed; return [{ filename: 'old.png' }];
+ }, loadHistory: async () => [] });
+ await entered;
+ const restored = db.reconcileMediaAssets({ rebuild: true,
+ listGallery: async () => [{ filename: 'restored.png' }], loadHistory: async () => [] });
+ finish();
+ await Promise.all([stale, restored]);
+ expect(await db.listAssets()).toEqual([expect.objectContaining({ filename: 'restored.png' })]);
+ });
+
+ it('rebuilds a restored mirror solely from authoritative files, including future-dated stale rows', async () => {
+ await db.upsertAsset({ mediaKey: `video:${PFX}restored`, kind: 'video', ref: `${PFX}restored`,
+ data: { id: `${PFX}restored`, thumbnail: 'missing.jpg' }, createdAt: '2026-01-01T00:00:00.000Z' });
+ await query(`UPDATE media_assets SET indexed_at = NOW() + INTERVAL '1 day' WHERE ref = $1`, [`${PFX}restored`]);
+ await db.reconcileMediaAssets({ rebuild: true, listGallery: async () => [],
+ loadHistory: async () => [{ id: `${PFX}current`, filename: 'current.mp4', thumbnail: 'current.jpg' }] });
+ expect(await db.listAssets()).toEqual([expect.objectContaining({ id: `${PFX}current`, thumbnail: 'current.jpg' })]);
+ });
+
+ it('preserves the prior mirror on failed source reads or a failed transactional rebuild', async () => {
+ await db.reconcileMediaAssets({ rebuild: true, listGallery: async () => [], loadHistory: async () => [] });
+ await db.upsertAsset({ mediaKey: `image:${PFX}keep.png`, kind: 'image', ref: `${PFX}keep.png`,
+ data: { filename: `${PFX}keep.png` }, createdAt: '2026-01-01T00:00:00.000Z' });
+ await expect(db.reconcileMediaAssets({ rebuild: true,
+ listGallery: async () => { throw new Error('unreadable'); }, loadHistory: async () => [],
+ })).rejects.toThrow('authoritative files');
+ // Serialization fails AFTER the DELETE; the transaction must restore it.
+ await expect(db.reconcileMediaAssets({ rebuild: true,
+ listGallery: async () => [{ filename: 'broken.png', prompt: 1n }], loadHistory: async () => [],
+ })).rejects.toThrow();
+ expect(await db.listAssets()).toEqual([{ filename: `${PFX}keep.png` }]);
+ });
+
it('does not prune a row indexed after reconcile started (concurrent generation)', async () => {
await new Promise((r) => setTimeout(r, 10));
const listGallery = async () => {
diff --git a/server/services/mediaAssetIndex/index.js b/server/services/mediaAssetIndex/index.js
index 3abd72a631..76a7ffe5dc 100644
--- a/server/services/mediaAssetIndex/index.js
+++ b/server/services/mediaAssetIndex/index.js
@@ -24,7 +24,7 @@ import { isTestRunner } from '../../lib/runtimeEnv.js';
import { checkHealth, ensureSchema } from '../../lib/db.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { videoGenEvents } from '../videoGen/events.js';
-import { upsertAsset, removeAsset, reconcileMediaAssets } from './db.js';
+import { upsertAsset, removeAsset, reconcileMediaAssets, queueMediaIndexRefresh } from './db.js';
import { imageMediaKey, imageToRow, videoMediaKey, videoToRow } from './logic.js';
export { reconcileMediaAssets } from './db.js';
@@ -44,18 +44,20 @@ export async function indexImage({ filename, temp } = {}) {
// gallery file or sidecar — skip indexing it. It lives in imageCleanTmp and
// is consumed by an explicit result-fetch, never listed in the gallery.
if (temp) return;
- const { readImageSidecar } = await import('../imageGen/local.js');
- const { metadata } = await readImageSidecar(filename);
- // Match disk gallery's timestamp fallback for uploads without a sidecar.
- let createdAt = metadata.createdAt;
- if (!createdAt) {
- const [{ stat }, { join }, { PATHS }] = await Promise.all([
- import('node:fs/promises'), import('node:path'), import('../../lib/fileUtils.js'),
- ]);
- createdAt = (await stat(join(PATHS.images, filename))).birthtime.toISOString();
- }
- const row = imageToRow({ filename, path: `/data/images/${filename}`, createdAt, ...metadata });
- await upsertAsset(row).catch((err) => console.error(`❌ Media index image upsert failed: ${err.message}`));
+ return queueMediaIndexRefresh(async () => {
+ const { readImageSidecar } = await import('../imageGen/local.js');
+ const { metadata } = await readImageSidecar(filename);
+ // Match disk gallery's timestamp fallback for uploads without a sidecar.
+ let createdAt = metadata.createdAt;
+ if (!createdAt) {
+ const [{ stat }, { join }, { PATHS }] = await Promise.all([
+ import('node:fs/promises'), import('node:path'), import('../../lib/fileUtils.js'),
+ ]);
+ createdAt = (await stat(join(PATHS.images, filename))).birthtime.toISOString();
+ }
+ const row = imageToRow({ filename, path: `/data/images/${filename}`, createdAt, ...metadata });
+ await upsertAsset(row).catch((err) => console.error(`❌ Media index image upsert failed: ${err.message}`));
+ });
}
// Index the just-generated video(s). The 'completed' event carries the job id
@@ -66,12 +68,14 @@ async function onVideoCompleted({ generationId, videos } = {}) {
const ids = Array.isArray(videos) ? videos.map((video) => video?.id) : [generationId];
const wanted = new Set(ids.filter((id) => typeof id === 'string' && id));
if (!wanted.size) return;
- const { loadHistory } = await import('../videoGen/local.js');
- const history = await loadHistory().catch(() => []);
- const entries = Array.isArray(history) ? history.filter((h) => wanted.has(h.id)) : [];
- for (const entry of entries) {
- await upsertAsset(videoToRow(entry)).catch((err) => console.error(`❌ Media index video upsert failed: ${err.message}`));
- }
+ return queueMediaIndexRefresh(async () => {
+ const { loadHistory } = await import('../videoGen/local.js');
+ const history = await loadHistory().catch(() => []);
+ const entries = Array.isArray(history) ? history.filter((h) => wanted.has(h.id)) : [];
+ for (const entry of entries) {
+ await upsertAsset(videoToRow(entry)).catch((err) => console.error(`❌ Media index video upsert failed: ${err.message}`));
+ }
+ });
}
// Drop one row, non-fatally. The delete paths call this AFTER the file is
@@ -80,7 +84,7 @@ async function onVideoCompleted({ generationId, videos } = {}) {
// behavior. Skipped under the escape hatch, where there's no index to maintain.
async function unindexKey(mediaKey, kind) {
if (!mediaKey || isEscapeHatch()) return;
- await removeAsset(mediaKey).catch((err) => console.error(`❌ Media index ${kind} remove failed: ${err.message}`));
+ await queueMediaIndexRefresh(() => removeAsset(mediaKey)).catch((err) => console.error(`❌ Media index ${kind} remove failed: ${err.message}`));
}
/**
diff --git a/server/services/mediaAssetIndex/index.test.js b/server/services/mediaAssetIndex/index.test.js
index ad2945bd66..fc4a10f2fc 100644
--- a/server/services/mediaAssetIndex/index.test.js
+++ b/server/services/mediaAssetIndex/index.test.js
@@ -15,7 +15,8 @@ const ensureSchema = vi.fn(async () => {});
const readImageSidecar = vi.fn(async () => ({ metadata: { prompt: 'p', createdAt: '2026-01-01T00:00:00.000Z' } }));
const loadHistory = vi.fn(async () => ([{ id: 'job-1', filename: 'job-1.mp4', createdAt: '2026-01-02T00:00:00.000Z' }]));
-vi.mock('./db.js', () => ({ upsertAsset, reconcileMediaAssets, removeAsset }));
+vi.mock('./db.js', async () => ({ upsertAsset, reconcileMediaAssets, removeAsset,
+ queueMediaIndexRefresh: (await import('../../lib/fileWriteQueue.js')).createFileWriteQueue() }));
vi.mock('../../lib/db.js', () => ({ checkHealth, ensureSchema }));
vi.mock('../imageGen/local.js', () => ({ readImageSidecar, listGallery: vi.fn(async () => []) }));
vi.mock('../videoGen/local.js', () => ({ loadHistory }));
@@ -89,6 +90,64 @@ describe('initMediaAssetIndex', () => {
});
});
+describe('completed hooks across a queued restore refresh', () => {
+ it.each(['image', 'video'])('reads %s metadata only when its queued publication starts', async kind => {
+ vi.stubEnv('NODE_ENV', 'production');
+ const { initMediaAssetIndex } = await import('./index.js');
+ const { queueMediaIndexRefresh } = await import('./db.js');
+ await initMediaAssetIndex();
+ const entered = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ const reader = kind === 'image' ? readImageSidecar : loadHistory;
+ const originalReader = reader.getMockImplementation();
+ const originalUpsert = upsertAsset.getMockImplementation();
+ let sourcePrompt = 'before restore';
+ let mirroredPrompt;
+ const written = [];
+ reader.mockImplementation(async () => {
+ const metadata = { prompt: sourcePrompt, createdAt: '2026-01-01T00:00:00.000Z' };
+ return kind === 'image' ? { metadata } : [{ id: 'job-1', filename: 'job-1.mp4', ...metadata }];
+ });
+ upsertAsset.mockImplementation(async row => {
+ if (!written.length) {
+ entered.resolve();
+ await release.promise;
+ }
+ written.push(row.data.prompt);
+ mirroredPrompt = row.data.prompt;
+ });
+ const emit = () => kind === 'image'
+ ? imageGenEvents.emit('completed', { filename: 'img-1.png' })
+ : videoGenEvents.emit('completed', { generationId: 'job-1' });
+ let rebuild;
+ try {
+ emit();
+ await entered.promise;
+ // This occupies the same queue as the real transactional rebuild (whose
+ // persistence is covered by db.test). A later completion must not read
+ // its source until that replacement has finished.
+ rebuild = queueMediaIndexRefresh(() => {
+ sourcePrompt = 'restored metadata';
+ mirroredPrompt = sourcePrompt;
+ });
+ emit();
+ await flush();
+ expect(reader).toHaveBeenCalledTimes(1);
+ expect(mirroredPrompt).toBeUndefined();
+ release.resolve();
+ await queueMediaIndexRefresh(() => {});
+ expect(written).toEqual(['before restore', 'restored metadata']);
+ expect(mirroredPrompt).toBe('restored metadata');
+ } finally {
+ release.resolve();
+ await rebuild;
+ await queueMediaIndexRefresh(() => {});
+ reader.mockImplementation(originalReader);
+ upsertAsset.mockImplementation(originalUpsert);
+ }
+ });
+});
+
describe('unindexImage / unindexVideo (delete hooks, #2738)', () => {
// The whole point of the hook: the key it deletes must be the key the upsert
// hook wrote, or the delete silently misses and the row lingers to the next