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

test: drain image cleaner requests before cancelled fixture teardown (#11537)

[._.]/037bc0699a76
diff --git a/scripts/imageCleanerCleanup.test.js b/scripts/imageCleanerCleanup.test.js
new file mode 100644
index 0000000000..b311b21983
--- /dev/null
+++ b/scripts/imageCleanerCleanup.test.js
@@ -0,0 +1,92 @@
+import { expect, it } from 'vitest';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createVitestTempFixture, fixtureReadyFailureSource } from './lib/vitestTempRootFixture.js';
+
+// Hold the real clean route at its first publication write, then let a different
+// worker cancel the test. Its body must finish before its gallery is removed.
+it('drains the image cleaner request before removing its cancelled fixture', () => {
+ const host = mkdtempSync(join(tmpdir(), 'image-clean-cancel-'));
+ try {
+ const { args, options } = createVitestTempFixture(host, 'server', '');
+ const fixture = join(host, 'fixture');
+ const ready = join(fixture, 'ready');
+ const traceFile = join(fixture, 'trace.json');
+ const resultsFile = join(fixture, 'results.json');
+ const junitFile = join(fixture, 'results.xml');
+ const sourcePath = fileURLToPath(new URL('../server/routes/imageGen.clean.test.js', import.meta.url));
+ const header = "it('cleans an existing PNG and writes _clean-resize-squeeze.png back to the gallery', async () => {";
+ const source = readFileSync(sourcePath, 'utf8')
+ .replace(/(['"])(\.\.?\/[^'"]+)\1/g, (_, quote, specifier) => JSON.stringify(resolve(dirname(sourcePath), specifier)))
+ .replace('let sandbox;', `let sandbox;
+ const probe = vi.hoisted(() => {
+ let finish;
+ return { events: [], finished: new Promise(resolve => { finish = resolve; }), finish: () => finish() };
+ });`)
+ .replace(' ...actual,\n get PATHS()', ` ...actual,
+ atomicWrite: async (...args) => {
+ if (args[0].endsWith('render-1_clean-resize-squeeze.png')) {
+ const { writeFileSync } = await import('node:fs');
+ const cancelled = new Promise(resolve => probe.signal.addEventListener('abort', () => setImmediate(resolve), { once: true }));
+ probe.events.push('publication-held');
+ writeFileSync(${JSON.stringify(ready)}, 'ready');
+ await cancelled;
+ probe.events.push('publication-released');
+ }
+ return actual.atomicWrite(...args);
+ },
+ get PATHS()`)
+ .replace(header, `${header.replace('async () =>', 'async ({ signal }) =>')}
+ probe.signal = signal;
+ try {`)
+ .replace(" });\n\n it('idempotent:", ` } finally {
+ probe.events.push('body-settled');
+ probe.finish();
+ }
+ });
+
+ it('idempotent:`)
+ .replace(' await rm(sandbox, { recursive: true, force: true });', ` probe.events.push('cleanup-start');
+ await rm(sandbox, { recursive: true, force: true });
+ probe.events.push('cleanup-finished');
+ await probe.finished;
+ const { writeFileSync, existsSync, readdirSync } = await import('node:fs');
+ writeFileSync(${JSON.stringify(traceFile)}, JSON.stringify({
+ events: probe.events,
+ remaining: existsSync(sandbox) ? readdirSync(sandbox) : null,
+ }));`);
+ expect(source).toContain('probe.signal = signal;');
+ expect(source).toContain('return actual.atomicWrite(...args);');
+ expect(source).toContain("probe.events.push('body-settled');");
+ writeFileSync(join(fixture, 'lifecycle.test.js'), source);
+ writeFileSync(join(fixture, 'failure.test.js'), fixtureReadyFailureSource(ready));
+ args[args.indexOf('--maxWorkers') + 1] = '2';
+ args.push('--bail=1', '--reporter=default', '--reporter=json', '--outputFile.json', resultsFile,
+ '--reporter=junit', '--outputFile.junit', junitFile);
+ const result = spawnSync(process.execPath, args, options);
+ const output = `${result.stdout}\n${result.stderr}`;
+ expect(result.error, output).toBeUndefined();
+ expect(result.status, output).toBe(1);
+ const trace = JSON.parse(readFileSync(traceFile, 'utf8'));
+ expect(trace, output).toEqual({
+ events: ['publication-held', 'publication-released', 'body-settled', 'cleanup-start', 'cleanup-finished'],
+ remaining: null,
+ });
+ const report = JSON.parse(readFileSync(resultsFile, 'utf8'));
+ expect(report.numFailedTests, output).toBe(1);
+ expect(report.numFailedTestSuites, output).toBe(1);
+ expect(report.testResults.map(file => file.message), output).toEqual(['', '']);
+ // Vitest's JSON reporter omits unhandled run errors; JUnit counts them.
+ const totals = readFileSync(junitFile, 'utf8').match(/<testsuites\b[^>]*>/)?.[0];
+ expect(totals, output).toMatch(/\berrors="0"/);
+ expect(totals, output).toMatch(/\bfailures="1"/);
+ const failures = report.testResults.flatMap(file => file.assertionResults).filter(test => test.status === 'failed');
+ expect(failures.map(test => test.title), output).toEqual(['controlled sibling failure']);
+ expect(output).not.toMatch(/ENOTEMPTY|ENOENT|Unhandled|test temp leak:/);
+ } finally {
+ rmSync(host, { recursive: true, force: true });
+ }
+}, 25000);
diff --git a/server/routes/imageGen.clean.test.js b/server/routes/imageGen.clean.test.js
index 3c55402fa6..42a9591e0c 100644
--- a/server/routes/imageGen.clean.test.js
+++ b/server/routes/imageGen.clean.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, beforeAll, afterAll, vi } from 'vitest';
+import { describe, it as vitestIt, expect, beforeEach, beforeAll, afterAll, vi } from 'vitest';
import express from 'express';
import sharp from 'sharp';
import { mkdtemp, rm, writeFile, readFile, stat } from 'fs/promises';
@@ -6,12 +6,14 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { request } from '../lib/testHelper.js';
+import { ownTestBodies } from '../lib/mockPathsDataRoot.js';
import { errorMiddleware } from '../lib/errorHandler.js';
// Sandbox PATHS.images to a tmp dir so the clean endpoint can read/write real
// files without touching data/images/. The mock has to be installed BEFORE the
// route module imports fileUtils.js, hence the dynamic import below.
let sandbox;
+const { it, drain } = ownTestBodies(vitestIt);
vi.mock('../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../lib/fileUtils.js');
@@ -84,7 +86,14 @@ beforeAll(async () => {
});
afterAll(async () => {
- await rm(sandbox, { recursive: true, force: true });
+ // Another worker's fail-fast cancellation settles Vitest's wrapper before
+ // this body's awaited clean request stops writing. Drain the actual body
+ // (including publication and assertions) before removing its gallery.
+ try {
+ await drain();
+ } finally {
+ await rm(sandbox, { recursive: true, force: true });
+ }
});
describe('POST /api/image-gen/:filename/clean', () => {