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 a shared beat grid analysis alive when one caller aborts, and time-box ffmpeg decode (#9652)

Adam Eivy2ce6ba293d28
diff --git a/server/lib/audioBeatDsp.js b/server/lib/audioBeatDsp.js
index 6db62ec598..38c046f290 100644
--- a/server/lib/audioBeatDsp.js
+++ b/server/lib/audioBeatDsp.js
@@ -33,6 +33,10 @@ export const ANALYSIS_SAMPLE_RATE = 22050;
// discarding) the rest of the stream.
export const MAX_ANALYSIS_SEC = 300;
+// Hard wall-clock cap on one ffmpeg decode. Without it a wedged ffmpeg (bad
+// container, pipe backpressure) never settles and pins callers forever.
+export const AUDIO_DECODE_TIMEOUT_MS = 60_000;
+
// Frame hop for the onset envelope. 512 samples @ 22.05kHz → ~43 frames/sec,
// which gives ~1 BPM tempo resolution across the musical range and ~23ms beat
// placement granularity — both well within what beat-snapping needs.
@@ -147,10 +151,12 @@ export function fftInPlace(real, imaginary, plan) {
* truncation path can be exercised against a short fixture rather than a
* real multi-minute file; real callers should not pass it. Clamped to
* MAX_ANALYSIS_SEC — it can only shrink the decode window, never grow it,
- * so it can't be used to defeat the memory bound.
+ * so it can't be used to defeat the memory bound. `timeoutMs` overrides
+ * AUDIO_DECODE_TIMEOUT_MS (test seam); on expiry ffmpeg is killed and the
+ * result is `null`.
* @returns {Promise<{ samples: Float32Array, sampleRate: number } | null>}
*/
-export async function decodeAudioToPcm(audioPath, { signal, maxDurationSec = MAX_ANALYSIS_SEC } = {}) {
+export async function decodeAudioToPcm(audioPath, { signal, maxDurationSec = MAX_ANALYSIS_SEC, timeoutMs = AUDIO_DECODE_TIMEOUT_MS } = {}) {
if (typeof audioPath !== 'string' || !audioPath) return null;
// A listener added to an already-aborted signal never fires, so without this
// guard a pre-cancelled request (plausible off the request lifecycle, under a
@@ -184,7 +190,11 @@ export async function decodeAudioToPcm(audioPath, { signal, maxDurationSec = MAX
onAbort = () => proc.kill('SIGTERM');
signal.addEventListener('abort', onAbort, { once: true });
}
- const cleanup = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort); };
+ const watchdog = setTimeout(() => proc.kill('SIGKILL'), timeoutMs);
+ const cleanup = () => {
+ clearTimeout(watchdog);
+ if (signal && onAbort) signal.removeEventListener('abort', onAbort);
+ };
proc.stdout.on('data', (c) => chunks.push(c));
proc.on('error', () => { cleanup(); resolve(null); });
diff --git a/server/lib/beatGrid.js b/server/lib/beatGrid.js
index 671b1518c0..a8cec9f46f 100644
--- a/server/lib/beatGrid.js
+++ b/server/lib/beatGrid.js
@@ -166,21 +166,53 @@ export async function getBeatGrid(audioPath, { signal } = {}) {
if (cached && cached.mtimeMs === stats.mtimeMs) return cached.result;
const key = inFlightKey(audioPath, stats.mtimeMs);
- const inFlight = beatGridInFlight.get(key);
- if (inFlight) return inFlight;
+ let entry = beatGridInFlight.get(key);
+ if (!entry) {
+ // The shared analysis runs on its OWN controller, never a single caller's
+ // signal: one caller aborting must not null the grid out from under the
+ // others awaiting the same promise. The decode is only aborted once every
+ // waiting caller has aborted.
+ const controller = new AbortController();
+ const promise = (async () => {
+ const analyzed = await analyzeBeatGridFile(audioPath, { signal: controller.signal });
+ if (!analyzed) return null;
+ const result = { bpm: analyzed.bpm, beats: analyzed.beats, downbeats: analyzed.downbeats, hits: analyzed.hits };
+ beatGridCache.set(audioPath, { mtimeMs: stats.mtimeMs, result });
+ return result;
+ })().finally(() => {
+ if (beatGridInFlight.get(key) === entry) beatGridInFlight.delete(key);
+ });
+ entry = { promise, controller, waiters: 0 };
+ beatGridInFlight.set(key, entry);
+ }
- const analysis = (async () => {
- const analyzed = await analyzeBeatGridFile(audioPath, { signal });
- if (!analyzed) return null;
- const result = { bpm: analyzed.bpm, beats: analyzed.beats, downbeats: analyzed.downbeats, hits: analyzed.hits };
- beatGridCache.set(audioPath, { mtimeMs: stats.mtimeMs, result });
- return result;
- })();
- beatGridInFlight.set(key, analysis);
+ if (signal?.aborted) return null;
+ entry.waiters += 1;
+ const shared = entry;
+ if (!signal) {
+ try { return await shared.promise; } finally { shared.waiters -= 1; }
+ }
+ // This caller's own abort resolves ITS call to null immediately and drops it
+ // from the waiter count; the shared decode is cancelled only at zero.
+ let onAbort;
+ const aborted = new Promise((resolve) => {
+ onAbort = () => {
+ shared.waiters -= 1;
+ if (shared.waiters <= 0) {
+ shared.controller.abort();
+ if (beatGridInFlight.get(key) === shared) beatGridInFlight.delete(key);
+ }
+ resolve(null);
+ };
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
try {
- return await analysis;
+ return await Promise.race([shared.promise, aborted]);
} finally {
- beatGridInFlight.delete(key);
+ if (!signal.aborted) {
+ signal.removeEventListener('abort', onAbort);
+ shared.waiters -= 1;
+ }
}
}
diff --git a/server/lib/beatGrid.test.js b/server/lib/beatGrid.test.js
index 27b1f8adc8..808de225a1 100644
--- a/server/lib/beatGrid.test.js
+++ b/server/lib/beatGrid.test.js
@@ -190,6 +190,15 @@ describe('decodeAudioToPcm (ffmpeg round-trip)', () => {
expect(await decodeAudioToPcm(join(tmpDir, 'whatever.wav'), { signal: controller.signal })).toBeNull();
});
+ // Issue #9652: a wedged ffmpeg must not hang the caller forever.
+ it('kills ffmpeg and resolves null when the decode exceeds timeoutMs (skipped without ffmpeg)', async () => {
+ if (!ffmpeg) { console.log('⏭️ ffmpeg not found — skipping decode-timeout test'); return; }
+ const wavSampleRate = 44100;
+ const wavPath = join(tmpDir, 'timeout.wav');
+ await writeFile(wavPath, encodeWav(clickTrack({ bpm: 120, durationSec: 10, sampleRate: wavSampleRate }), wavSampleRate));
+ expect(await decodeAudioToPcm(wavPath, { timeoutMs: 1 })).toBeNull();
+ });
+
it('decodes a synthesized WAV to PCM at BEAT_GRID_SAMPLE_RATE (skipped without ffmpeg)', async () => {
if (!ffmpeg) { console.log('⏭️ ffmpeg not found — skipping beat-grid decode round-trip'); return; }
const wavSampleRate = 44100;
@@ -293,4 +302,46 @@ describe('getBeatGrid (mtime-keyed cache)', () => {
expect(a).not.toBeNull();
expect(b).toBe(a);
});
+
+ // Issue #9652: the shared in-flight analysis used to run on the FIRST
+ // caller's signal, so that caller aborting nulled the grid for every other
+ // waiter. Caller A is the first to start (it owns the analysis) and aborts
+ // while B is still waiting; B must still get a real grid.
+ it('does not let the first caller aborting cancel the shared analysis for another caller (skipped without ffmpeg)', async () => {
+ if (!ffmpeg) { console.log('⏭️ ffmpeg not found — skipping abort-isolation test'); return; }
+ const wavSampleRate = 44100;
+ const wavPath = join(tmpDir, 'abort-isolation.wav');
+ await writeFile(wavPath, encodeWav(clickTrack({ bpm: 120, durationSec: 6, sampleRate: wavSampleRate }), wavSampleRate));
+
+ const controllerA = new AbortController();
+ const pA = getBeatGrid(wavPath, { signal: controllerA.signal });
+ // Let A register the shared analysis (stat resolved, decode starting)
+ // before B joins, so A is deterministically the analysis owner.
+ await new Promise((r) => setTimeout(r, 10));
+ const pB = getBeatGrid(wavPath);
+ controllerA.abort();
+ const [a, b] = await Promise.all([pA, pB]);
+ expect(a).toBeNull();
+ expect(b).not.toBeNull();
+ expect(b.bpm).toBeGreaterThan(120 - BPM_TOLERANCE);
+ expect(b.bpm).toBeLessThan(120 + BPM_TOLERANCE);
+ });
+
+ it('returns null for every caller when all of them abort, and leaves nothing wedged in flight (skipped without ffmpeg)', async () => {
+ if (!ffmpeg) { console.log('⏭️ ffmpeg not found — skipping all-abort test'); return; }
+ const wavSampleRate = 44100;
+ const wavPath = join(tmpDir, 'abort-all.wav');
+ await writeFile(wavPath, encodeWav(clickTrack({ bpm: 120, durationSec: 6, sampleRate: wavSampleRate }), wavSampleRate));
+
+ const c1 = new AbortController();
+ const c2 = new AbortController();
+ const p1 = getBeatGrid(wavPath, { signal: c1.signal });
+ const p2 = getBeatGrid(wavPath, { signal: c2.signal });
+ c1.abort();
+ c2.abort();
+ expect(await Promise.all([p1, p2])).toEqual([null, null]);
+ // A later, healthy caller measures fresh rather than inheriting the abort.
+ expect(await getBeatGrid(wavPath)).not.toBeNull();
+ });
});
+