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: measure long composition renders outside the test temp root (#9075)

[._.]/ Adam Eivya89033b1c957
diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.js
index 41a5619f3f..8726680ea1 100644
--- a/server/services/htmlComposition/encode.js
+++ b/server/services/htmlComposition/encode.js
@@ -20,10 +20,10 @@ async function frameFormat(page, { width, height, layout }) {
// Stream one frame at a time. The write callback supplies back-pressure and
// the terminal race releases a pending write on exit, disconnect or cancel.
-export async function encodeComposition(page, contract, outputPath, { musicPath, audio, signal, onProgress } = {}) {
- const ffmpeg = await findFfmpeg();
+export async function encodeComposition(page, contract, outputPath, { musicPath, audio, signal, onProgress, spawnProcess = spawn, locateFfmpeg = findFfmpeg, tagFilter = bt709TagFilter } = {}) {
+ const ffmpeg = await locateFfmpeg();
if (!ffmpeg) throw new Error('ffmpeg not found on PATH');
- const tag = await bt709TagFilter();
+ const tag = await tagFilter();
signal?.throwIfAborted();
const { fps, durationSec, width, height, motionBlur } = contract;
const numFrames = Math.round(durationSec * fps);
@@ -49,7 +49,7 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,
if (exactAudio) args.push('-map', '1:a', ...AAC_ENCODE_ARGS);
else if (musicPath) args.push('-map', '1:a', '-af', `atrim=duration=${durationSec},asetpts=PTS-STARTPTS,afade=t=out:st=${durationSec - 0.5}:d=0.5`, ...AAC_ENCODE_ARGS);
args.push('-frames:v', String(numFrames), '-t', String(durationSec), '-movflags', '+faststart', '-y', outputPath);
- const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['pipe', 'ignore', 'pipe'] }));
+ const proc = spawnProcess(ffmpeg, args, safeChildProcessOptions({ stdio: ['pipe', 'ignore', 'pipe'] }));
let stderr = '';
let exited = false;
let stopping = false;
diff --git a/server/services/htmlComposition/encode.musicVideo.memory-check.mjs b/server/services/htmlComposition/encode.musicVideo.memory-check.mjs
new file mode 100644
index 0000000000..bb5ab6f8de
--- /dev/null
+++ b/server/services/htmlComposition/encode.musicVideo.memory-check.mjs
@@ -0,0 +1,51 @@
+// Measures encodeComposition's retained heap across a 600s/12fps job.
+// Run with `node --expose-gc`. Kept out of vitest so it cannot tear down the
+// suite's shared temp root.
+import { EventEmitter } from 'node:events';
+import { encodeComposition } from './encode.js';
+
+if (typeof global.gc !== 'function') {
+ console.error('forced GC is required');
+ process.exit(2);
+}
+
+const FRAME = Buffer.alloc(4 * 1024, 7).toString('base64');
+const page = {
+ check() {},
+ async evaluate() {},
+ async send(method) {
+ if (method === 'Emulation.setDeviceMetricsOverride') return {};
+ return { data: FRAME };
+ },
+};
+
+let bytes = 0;
+const spawnProcess = () => {
+ const proc = new EventEmitter();
+ proc.stderr = new EventEmitter();
+ proc.stdin = new EventEmitter();
+ proc.stdin.write = (buf, cb) => { bytes += buf.length; cb?.(); return true; };
+ proc.stdin.end = () => { proc.emit('close', 0); };
+ proc.kill = () => {};
+ return proc;
+};
+
+const samples = [];
+await encodeComposition(page, { fps: 12, durationSec: 600, width: 1280, height: 720, motionBlur: 1 }, '/tmp/long.mp4', {
+ spawnProcess,
+ locateFfmpeg: async () => '/usr/bin/ffmpeg',
+ tagFilter: async () => 'format=yuv420p',
+ onProgress: (_fraction, detail) => {
+ if (detail.frame === 400 || detail.frame === 7200) {
+ global.gc();
+ samples.push(process.memoryUsage().heapUsed);
+ }
+ },
+});
+
+const delta = samples.length === 2 ? samples[1] - samples[0] : Number.POSITIVE_INFINITY;
+if (!(bytes > 0) || samples.length !== 2 || delta >= 12 * 1024 * 1024) {
+ console.error(`retained-heap delta=${delta} bytes=${bytes} samples=${samples.length}`);
+ process.exit(1);
+}
+console.log(`retained-heap delta=${delta}`);
diff --git a/server/services/htmlComposition/encode.musicVideo.test.js b/server/services/htmlComposition/encode.musicVideo.test.js
index ca1367317b..f2a64e6c25 100644
--- a/server/services/htmlComposition/encode.musicVideo.test.js
+++ b/server/services/htmlComposition/encode.musicVideo.test.js
@@ -1,5 +1,8 @@
import { EventEmitter } from 'node:events';
import { spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it, vi } from 'vitest';
@@ -61,33 +64,19 @@ describe('encodeComposition music-video audio', () => {
expect(args).toContain('-frames:v');
});
- it('does not retain per-frame buffers across a long synthetic job', async () => {
- // Forced GC is what makes "not retained" observable. Re-exec once under
- // --expose-gc so a normal vitest run still executes the measurement.
- if (typeof global.gc !== 'function') {
- if (process.env.PORTOS_GC_CHILD === '1') throw new Error('forced GC was not available in the vitest worker');
- const serverRoot = fileURLToPath(new URL('../..', import.meta.url));
- const vitestBin = fileURLToPath(new URL('../../node_modules/vitest/vitest.mjs', import.meta.url));
- const result = spawnSync(process.execPath, [vitestBin, 'run', 'services/htmlComposition/encode.musicVideo.test.js', '-t', 'per-frame buffers'], {
- cwd: serverRoot, encoding: 'utf8', timeout: 180000,
- env: { ...process.env, PORTOS_GC_CHILD: '1', NODE_OPTIONS: `${process.env.NODE_OPTIONS || ''} --expose-gc`.trim() },
- });
- expect(result.status, result.stderr || result.stdout).toBe(0);
- return;
- }
- spawned.length = 0;
- const samples = [];
- await encodeComposition(page, contract(600), '/tmp/long.mp4', {
- onProgress: (_fraction, detail) => {
- if (detail.frame === 400 || detail.frame === 7200) {
- global.gc();
- samples.push(process.memoryUsage().heapUsed);
- }
- },
+ it('does not retain per-frame buffers across a long synthetic job', () => {
+ // A separate node process so its temp directory and forced GC stay out of
+ // this vitest run. A nested vitest shares the suite temp root and deletes
+ // it out from under the other shards.
+ const scratch = mkdtempSync(join(tmpdir(), 'portos-encode-mem-'));
+ const script = fileURLToPath(new URL('./encode.musicVideo.memory-check.mjs', import.meta.url));
+ const result = spawnSync(process.execPath, ['--expose-gc', script], {
+ cwd: fileURLToPath(new URL('../..', import.meta.url)),
+ encoding: 'utf8',
+ timeout: 120000,
+ env: { PATH: process.env.PATH, HOME: process.env.HOME, TMPDIR: scratch, TEMP: scratch, TMP: scratch },
});
- expect(spawned[0].bytes()).toBeGreaterThan(0);
- expect(samples).toHaveLength(2);
- // Frames 401–7200 of retained 4 KiB screenshots stay well over 12 MiB after GC.
- expect(samples[1] - samples[0]).toBeLessThan(12 * 1024 * 1024);
- }, 200000);
+ rmSync(scratch, { recursive: true, force: true });
+ expect(result.status, `${result.stderr || ''}\n${result.stdout || ''}`).toBe(0);
+ }, 150000);
});