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 disk reservation when Code Animation import cleanup fails (#9674)

[._.]/ Adam Eivy00193c2cb6e9
diff --git a/server/services/codeAnimation/db.test.js b/server/services/codeAnimation/db.test.js
index cc9aadc90e..12b68f9028 100644
--- a/server/services/codeAnimation/db.test.js
+++ b/server/services/codeAnimation/db.test.js
@@ -1,12 +1,37 @@
/** HTTP → PostgreSQL → immutable managed bytes; synthetic records only. */
import { afterAll, describe, expect, it, vi } from 'vitest';
import express from 'express';
-import { readFile, mkdir, symlink, rm, writeFile } from 'fs/promises';
+import { readFile, readdir, mkdir, symlink, rm, writeFile } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { lazyTempDataRoot, makePathsProxy, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';
vi.mock('../../lib/paths.js', async importOriginal =>
makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('code-animation-production-') }));
+// Narrow filesystem seam: one-shot faults for the staged-write and cleanup steps; everything else is real.
+const fsFaults = vi.hoisted(() => ({ failSecondWrite: false, refuseOwnedRemoval: false, writes: 0 }));
+vi.mock('fs/promises', async importOriginal => {
+ const real = await importOriginal();
+ return {
+ ...real,
+ open: async (path, flags, ...rest) => {
+ const handle = await real.open(path, flags, ...rest);
+ if (!fsFaults.failSecondWrite || typeof flags !== 'number' || !(flags & real.constants.O_CREAT)) return handle;
+ if (++fsFaults.writes < 2) return handle;
+ fsFaults.failSecondWrite = false;
+ return {
+ writeFile: async () => { throw Object.assign(new Error('synthetic ENOSPC'), { code: 'ENOSPC' }); },
+ sync: async () => {}, close: () => handle.close(),
+ };
+ },
+ rm: async (path, ...rest) => {
+ if (fsFaults.refuseOwnedRemoval && String(path).includes('revisions')) {
+ fsFaults.refuseOwnedRemoval = false;
+ throw Object.assign(new Error('synthetic EACCES'), { code: 'EACCES' });
+ }
+ return real.rm(path, ...rest);
+ },
+ };
+});
vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));
import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
import { requireDbOrSkip } from '../../lib/dbTestGate.js';
@@ -115,4 +140,94 @@ describe.skipIf(!ready)('Production persisted public boundary', () => {
await rm(file); await writeFile(file, '<html>changed</html>');
expect((await get(`/projects/${project.id}/revisions/${first.revision.id}/package`)).status).toBe(409);
});
+
+ describe('failed import disk reservations', () => {
+ // Same-length sources, so every import reserves the same byte count.
+ const variant = char => pkg(`<html>syntheti${char}</html>`);
+ const revisionsDir = projectId => join(PATHS.data, 'code-animations', 'projects', projectId, 'revisions');
+ const reservations = async projectId => (await query(
+ "SELECT status, (data->>'reservedBytes')::int AS reserved FROM code_animation_project_runs WHERE project_id = $1 ORDER BY created_at, id", [projectId])).rows;
+ const revisionCount = async projectId =>
+ Number((await query('SELECT COUNT(*) AS n FROM code_animation_project_revisions WHERE project_id = $1', [projectId])).rows[0].n);
+ const armFaults = faults => Object.assign(fsFaults, { failSecondWrite: false, refuseOwnedRemoval: false, writes: 0 }, faults);
+ // Accepted + candidate revisions exist; budget leaves room for exactly one more same-size import.
+ const seeded = async () => {
+ const project = await create();
+ const accepted = await imported(project.id, variant('A'));
+ await post(`/projects/${project.id}/accept`, { revisionId: accepted.revision.id });
+ const candidate = await imported(project.id, variant('B'));
+ const bytes = accepted.revision.totalBytes;
+ expect((await patch(`/projects/${project.id}`, { budgets: { ...project.budgets, diskBytes: bytes * 3 } })).status).toBe(200);
+ return { project, accepted, candidate, bytes };
+ };
+ const expectPointers = async ({ project, accepted, candidate }) =>
+ expect((await get(`/projects/${project.id}`)).body).toMatchObject({ acceptedRevisionId: accepted.revision.id, candidateRevisionId: candidate.revision.id });
+
+ it('keeps the full reservation when a write failure is followed by a refused cleanup, so retries cannot exceed the budget', async () => {
+ const state = await seeded();
+ const { project, bytes } = state;
+ armFaults({ failSecondWrite: true, refuseOwnedRemoval: true });
+ expect((await post(`/projects/${project.id}/import`, variant('C'))).status).toBe(500);
+ expect((await reservations(project.id)).at(-1)).toEqual({ status: 'failed', reserved: bytes });
+ expect(await revisionCount(project.id)).toBe(2);
+ await expectPointers(state);
+ const dirsBefore = await readdir(revisionsDir(project.id));
+ expect(dirsBefore).toHaveLength(3);
+ // The partial first file is still on disk and still owned by the failed run.
+ const failed = (await get(`/projects/${project.id}/history`)).body.items.find(run => run.status === 'failed');
+ expect((await readdir(join(PATHS.data, failed.data.relativePath, 'assets'))).length + (await readdir(join(PATHS.data, failed.data.relativePath, 'src'))).length).toBeGreaterThan(0);
+ for (let attempt = 0; attempt < 3; attempt++) {
+ expect((await post(`/projects/${project.id}/import`, variant('D'))).status).toBe(409);
+ }
+ expect(await readdir(revisionsDir(project.id))).toEqual(dirsBefore);
+ expect((await reservations(project.id)).reduce((sum, run) => sum + run.reserved, 0)).toBe(bytes * 3);
+ });
+
+ it('releases the reservation after a confirmed cleanup, and when no owned directory was ever created', async () => {
+ const state = await seeded();
+ const { project, bytes } = state;
+ armFaults({ failSecondWrite: true });
+ expect((await post(`/projects/${project.id}/import`, variant('C'))).status).toBe(500);
+ expect((await reservations(project.id)).at(-1)).toEqual({ status: 'failed', reserved: 0 });
+ expect(await readdir(revisionsDir(project.id))).toHaveLength(2);
+ await expectPointers(state);
+ const retry = await post(`/projects/${project.id}/import`, variant('D'));
+ expect(retry.status).toBe(201);
+ expect(retry.body.revision.totalBytes).toBe(bytes);
+
+ const linked = await create();
+ const outside = join(PATHS.data, 'synthetic-outside-reservation');
+ const parent = join(PATHS.data, 'code-animations', 'projects', linked.id);
+ await mkdir(parent, { recursive: true }); await mkdir(outside, { recursive: true });
+ await symlink(outside, join(parent, 'revisions'), process.platform === 'win32' ? 'junction' : 'dir');
+ expect((await post(`/projects/${linked.id}/import`, pkg())).status).toBe(409);
+ expect((await reservations(linked.id)).at(-1)).toEqual({ status: 'failed', reserved: 0 });
+ });
+
+ it('retains the staged tree and reservation when publication fails, rolls back the revision, and publishes a clean control import', async () => {
+ const state = await seeded();
+ const { project, bytes } = state;
+ const trigger = `code_animation_fail_${project.id.replaceAll('-', '')}`;
+ await query(`CREATE OR REPLACE FUNCTION ${trigger}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'synthetic publish failure'; END $$`);
+ await query(`CREATE TRIGGER ${trigger} BEFORE INSERT ON code_animation_project_revisions
+ FOR EACH ROW WHEN (NEW.project_id = '${project.id}') EXECUTE FUNCTION ${trigger}()`);
+ try {
+ expect((await post(`/projects/${project.id}/import`, variant('C'))).status).toBe(500);
+ } finally {
+ await query(`DROP TRIGGER IF EXISTS ${trigger} ON code_animation_project_revisions`);
+ await query(`DROP FUNCTION IF EXISTS ${trigger}()`);
+ }
+ expect((await reservations(project.id)).at(-1)).toEqual({ status: 'failed', reserved: bytes });
+ expect(await revisionCount(project.id)).toBe(2);
+ expect(await readdir(revisionsDir(project.id))).toHaveLength(3);
+ await expectPointers(state);
+ // The retained tree still counts against the budget until the operator raises it.
+ expect((await post(`/projects/${project.id}/import`, variant('D'))).status).toBe(409);
+ expect((await patch(`/projects/${project.id}`, { budgets: { ...project.budgets, diskBytes: bytes * 4 } })).status).toBe(200);
+ const control = await imported(project.id, variant('D'));
+ expect(await revisionCount(project.id)).toBe(3);
+ expect((await get(`/projects/${project.id}`)).body).toMatchObject({ acceptedRevisionId: state.accepted.revision.id, candidateRevisionId: control.revision.id });
+ expect((await get(`/projects/${project.id}/revisions/${control.revision.id}/package`)).body).toEqual(variant('D'));
+ });
+ });
});
diff --git a/server/services/codeAnimation/projectFiles.js b/server/services/codeAnimation/projectFiles.js
index b4a27c15de..877ad79376 100644
--- a/server/services/codeAnimation/projectFiles.js
+++ b/server/services/codeAnimation/projectFiles.js
@@ -37,6 +37,20 @@ async function root(projectId, revisionId, create) {
return path;
}
+const RETAINED = Symbol('ownedStorageRetained');
+function markOwnedStorageRetained(error, cleanupError) {
+ if (error === null || typeof error !== 'object') return;
+ error[RETAINED] = true;
+ error.cleanupError = String(cleanupError?.code || cleanupError?.message || 'cleanup failed').slice(0, 200);
+}
+
+/**
+ * True when staging failed after creating its owned revision directory and the
+ * directory could not be confirmed removed, so its bytes still count against
+ * the project's disk budget. Absent (never created) or removed means releasable.
+ */
+export const ownedStorageRetained = error => Boolean(error?.[RETAINED]);
+
export async function stageProjectFiles(projectId, revisionId, files) {
const owned = await root(projectId, revisionId, true);
try {
@@ -53,8 +67,15 @@ export async function stageProjectFiles(projectId, revisionId, files) {
} finally { await handle.close(); }
}
} catch (error) {
- // Only this invocation's exclusively-created directory can be removed.
- await rm(owned, { recursive: true, force: true });
+ // Only this invocation's exclusively-created directory can be removed. If
+ // removal fails, the partial bytes stay on disk: keep the staging error
+ // (the real cause), flag it so the caller keeps the disk reservation, and
+ // attach a bounded cleanup message.
+ try {
+ await rm(owned, { recursive: true, force: true });
+ } catch (cleanupError) {
+ markOwnedStorageRetained(error, cleanupError);
+ }
throw error;
}
return { relativePath: `code-animations/projects/${projectId}/revisions/${revisionId}` };
diff --git a/server/services/codeAnimation/projects.js b/server/services/codeAnimation/projects.js
index 2f07141878..49ff6fd2a9 100644
--- a/server/services/codeAnimation/projects.js
+++ b/server/services/codeAnimation/projects.js
@@ -6,7 +6,7 @@ import { validateRequest } from '../../lib/validation.js';
import { ServerError } from '../../lib/errorHandler.js';
import { emitCodeAnimationChanged } from '../socket.js';
import * as store from './projectStore.js';
-import { stageProjectFiles, readProjectFiles, sourceHashOf } from './projectFiles.js';
+import { stageProjectFiles, readProjectFiles, sourceHashOf, ownedStorageRetained } from './projectFiles.js';
import { activeStageRunIds } from './stages.js';
const activeImports = new Set();
@@ -69,7 +69,10 @@ export async function importProductionPackage(projectId, input) {
} catch (error) {
// Keep accepted work and the failed run. A staged orphan is retained on DB
// failure, never mistaken for an accepted revision or automatically run.
- await store.failImportRecord(runId, error.code || 'IMPORT_FAILED', !staged);
+ // Release the reservation only when no owned bytes can remain: the tree
+ // was never created or its cleanup was confirmed. Staging that failed with
+ // a refused cleanup keeps its partial bytes reserved.
+ await store.failImportRecord(runId, error.code || 'IMPORT_FAILED', !staged && !ownedStorageRetained(error));
emitCodeAnimationChanged(projectId);
throw error;
} finally {