Skip to content

Commit f8210d9

Browse files
committed
feat(cli): configurable transcribe timeout with duration-scaled default
Adds a `--timeout <ms>` CLI flag (and `HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS` env var) plus a model-slowdown factor in the auto-scaled default so `hyperframes transcribe` doesn't hard-fail with `spawnSync ETIMEDOUT` on slow CPUs running heavier whisper models. Field-signal ts=1784165471 (win32/arm64 emulating x64 on Snapdragon, CLI 0.7.59) reported the failure on a 63s wav with `-m medium` at ~13x realtime — the historical 10x-realtime scale (PR #2463) gave 10.5 min while the machine needed ~13.7 min. Splitting audio and merging offsets was the manual workaround. - Add `--timeout <ms>` and `HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS` (min 5000). Explicit override bypasses auto-scaling; still capped at 12h. - Add per-model slowdown factor (tiny 0.5, base 0.7, small 1, medium 2, large 4, large-v3-turbo 2). Multiplied into the 10s/audio-second baseline so medium/large get proportional headroom while `small.en` (the default) preserves the historical safety window. - Wrap whisper's spawn error with a discoverability hint naming `--timeout`, the env var, and the effective timeout when the child was killed by SIGTERM/ETIMEDOUT (mirrors PR #2504 protocol-timeout). - Docs: new `--timeout` row in `docs/packages/cli.mdx` Flags table. Regression coverage in `packages/cli/src/whisper/transcribe.test.ts` (56 tests) and `packages/cli/src/commands/transcribe.test.ts` (5 tests): - Model factor per known name + case-insensitive + safe unknown fallback. - 63s field-signal case on medium.en → 1_260_000ms (was 630_000ms). - Explicit override honored below the auto floor + capped at 12h. - Model factor ignored when overrideMs is set. - SIGTERM/ETIMEDOUT detection + augmented message contract. - CLI rejects below-minimum `--timeout` with error naming both the flag and the 5000ms floor. — Via Co-Authored-By: Claude Opus 4.7 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code)
1 parent 9ed255c commit f8210d9

5 files changed

Lines changed: 409 additions & 9 deletions

File tree

‎docs/packages/cli.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,7 @@ This is suppressed in CI environments, non-TTY shells, and when `HYPERFRAMES_NO_
289289
| `--to` | Export transcript sidecar format: `srt` or `vtt` |
290290
| `--output, -o` | Output path for exported SRT/VTT sidecar |
291291
| `--preserve-cues` | Keep each transcript entry as its own caption cue (skip word-level grouping) |
292+
| `--timeout` | Whisper spawn timeout in ms. Overrides the duration+model auto-scaled default. Increase on slow CPUs (e.g. emulated arm64/x64) where medium/large models take many seconds per audio second. Minimum 5000. Env: `HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS`. |
292293
| `--json` | Output result as JSON |
293294

294295
The command auto-detects the input type. Audio/video files are transcribed with whisper.cpp. Transcript files (`.json`, `.srt`, `.vtt`) are normalized and imported. Pass `--to srt` or `--to vtt` with a transcript input to write a caption sidecar instead.

‎packages/cli/src/commands/transcribe.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,32 @@ Render video. Built for agents.
9999
});
100100
});
101101

102+
it("rejects a below-minimum --timeout with a discoverable error", async () => {
103+
const { dir, input } = dummyAudio();
104+
dirs.push(dir);
105+
const consoleLog = vi.mocked(console.log);
106+
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
107+
throw new Error(`__exit_${code}__`);
108+
}) as never);
109+
110+
// 100 is well below the 5000ms minimum — must fail loud instead of silently
111+
// reverting to the auto-scaled default (the whole point of the flag is
112+
// that the user explicitly asked for a specific value).
113+
await expect(
114+
transcribeCmd.run!({ args: { input, json: true, timeout: "100" } } as never),
115+
).rejects.toThrow("__exit_1__");
116+
117+
const log = consoleLog.mock.calls.at(-1)?.[0];
118+
expect(typeof log).toBe("string");
119+
if (typeof log !== "string") throw new Error("Expected JSON log output");
120+
const parsed = JSON.parse(log);
121+
expect(parsed.ok).toBe(false);
122+
expect(parsed.error).toContain("--timeout");
123+
expect(parsed.error).toContain("5000");
124+
125+
exitSpy.mockRestore();
126+
});
127+
102128
it("--preserve-cues keeps single-word cues separate when exporting from JSON", async () => {
103129
const dir = mkdtempSync(join(tmpdir(), "hf-transcribe-test-"));
104130
dirs.push(dir);

‎packages/cli/src/commands/transcribe.ts‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ import { resolve, join, extname, dirname } from "node:path";
2323
import * as clack from "@clack/prompts";
2424
import { c } from "../ui/colors.js";
2525
import { DEFAULT_MODEL, isWhisperUnavailable } from "../whisper/manager.js";
26+
27+
// Minimum accepted value for `--timeout` / `HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS`.
28+
// Kept out of `whisper/transcribe.ts` (avoids a top-level import into this
29+
// command module) so the CLI test file can hoist its
30+
// `vi.mock("../whisper/transcribe.js")` factory without the mocked module
31+
// entering the sync-import graph. Below this floor the whisper spawn has no
32+
// realistic chance of completing even on the fastest hardware for the shortest clip.
33+
const CLI_TIMEOUT_MIN_MS = 5000;
2634
import { trackCommandFailure, trackTranscribeUnavailable } from "../telemetry/events.js";
2735

2836
export default defineCommand({
@@ -85,6 +93,16 @@ export default defineCommand({
8593
"Treat captions as optional: if whisper-cpp is unavailable, skip and exit 0 instead of failing. For pipelines that continue without captions.",
8694
default: false,
8795
},
96+
timeout: {
97+
type: "string",
98+
description:
99+
"Whisper spawn timeout in ms. Overrides the duration+model auto-scaled " +
100+
"default. Increase on slow CPUs (e.g. emulated arm64/x64, low-power " +
101+
"laptops) where whisper.cpp takes many seconds per audio second on " +
102+
"medium/large models. Applies to the whisper engine only; Parakeet has " +
103+
"a separate fixed timeout. Minimum 5000 (5 s). " +
104+
"Env: HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS.",
105+
},
88106
},
89107
async run({ args }) {
90108
const inputPath = resolve(args.input);
@@ -120,16 +138,42 @@ export default defineCommand({
120138
}
121139

122140
// ── Transcribe mode: run the ASR engine ──────────────────────────────
141+
const timeoutMs = parseTimeoutMs(args.timeout, args.json);
142+
123143
return transcribeAudio(inputPath, dir, {
124144
engine: args.engine,
125145
model: args.model,
126146
language: args.language,
127147
json: args.json,
128148
optional: args.optional,
149+
timeoutMs,
129150
});
130151
},
131152
});
132153

154+
/**
155+
* Resolve the whisper timeout override from `--timeout <ms>` or the
156+
* `HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS` env var. The flag wins over env; both
157+
* paths share the same integer + minimum-5000ms validation so a bad value
158+
* fails loud instead of silently reverting to the auto-scaled default.
159+
* Returns `undefined` when neither source is set — the transcribe layer then
160+
* derives the timeout from audio duration and model factor.
161+
*/
162+
function parseTimeoutMs(raw: string | undefined, json: boolean): number | undefined {
163+
const source = raw ?? process.env["HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS"];
164+
if (source == null || source === "") return undefined;
165+
166+
const parsed = Number.parseInt(source, 10);
167+
if (!Number.isFinite(parsed) || parsed < CLI_TIMEOUT_MIN_MS) {
168+
const origin = raw != null ? "--timeout" : "HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS";
169+
failWith(
170+
`Invalid ${origin}: "${source}". Must be an integer >= ${CLI_TIMEOUT_MIN_MS} (ms).`,
171+
json,
172+
);
173+
}
174+
return parsed;
175+
}
176+
133177
function failWith(message: string, json: boolean): never {
134178
trackCommandFailure("transcribe", message);
135179
if (json) {
@@ -226,7 +270,14 @@ async function exportTranscript(
226270
async function transcribeAudio(
227271
inputPath: string,
228272
dir: string,
229-
opts: { engine?: string; model?: string; language?: string; json?: boolean; optional?: boolean },
273+
opts: {
274+
engine?: string;
275+
model?: string;
276+
language?: string;
277+
json?: boolean;
278+
optional?: boolean;
279+
timeoutMs?: number;
280+
},
230281
): Promise<void> {
231282
const { transcribe } = await import("../whisper/transcribe.js");
232283
const { loadTranscript, patchCaptionHtml, stripBeforeOnset } =
@@ -260,6 +311,7 @@ async function transcribeAudio(
260311
model,
261312
language: opts.language,
262313
onProgress: spin ? (msg) => spin.message(msg) : undefined,
314+
timeoutMs: opts.timeoutMs,
263315
});
264316

265317
let { words } = loadTranscript(result.transcriptPath);

‎packages/cli/src/whisper/transcribe.test.ts‎

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import { describe, expect, it, test } from "vitest";
22
import {
33
dtwPresetForModel,
4+
isWhisperTimeoutError,
45
resolveAudioPreparationTimeoutMs,
56
resolveWhisperTimeoutMs,
7+
whisperModelSlowdownFactor,
8+
wrapWhisperTimeoutError,
69
} from "./transcribe.js";
710

811
describe("dtwPresetForModel", () => {
@@ -55,6 +58,179 @@ describe("resolveWhisperTimeoutMs", () => {
5558
});
5659
});
5760

61+
describe("whisperModelSlowdownFactor", () => {
62+
it.each([
63+
["tiny", 0.5],
64+
["tiny.en", 0.5],
65+
["base", 0.7],
66+
["base.en", 0.7],
67+
["small", 1],
68+
["small.en", 1],
69+
["medium", 2],
70+
["medium.en", 2],
71+
["large-v1", 4],
72+
["large-v2", 4],
73+
["large-v3", 4],
74+
["large-v3-turbo", 2],
75+
])("returns factor %s for known model %s", (model, expected) => {
76+
expect(whisperModelSlowdownFactor(model)).toBe(expected);
77+
});
78+
79+
it("is case-insensitive", () => {
80+
expect(whisperModelSlowdownFactor("MEDIUM.EN")).toBe(2);
81+
expect(whisperModelSlowdownFactor("Large-V3")).toBe(4);
82+
});
83+
84+
it("falls back to the small.en baseline (1) for unknown model names", () => {
85+
// Unknown model names must never shorten the safety window, so the default
86+
// is the baseline factor rather than a smaller (tiny/base) value.
87+
expect(whisperModelSlowdownFactor("my-custom-finetune")).toBe(1);
88+
});
89+
});
90+
91+
describe("resolveWhisperTimeoutMs with model factor", () => {
92+
it("keeps small.en (default) at the historical baseline for 63s clips", () => {
93+
// Regression guard: `small.en` (the CLI default model) must not lose
94+
// headroom when the caller passes a model. 63s * 10s/s * 1 = 630_000ms.
95+
expect(resolveWhisperTimeoutMs(63, { model: "small.en" })).toBe(630_000);
96+
});
97+
98+
it("doubles the auto-scaled window for medium.en (field-signal ts=1784165471)", () => {
99+
// 63s clip on medium.en: emulated arm64/x64 saw ~13x realtime — 63*13 =
100+
// 819s needed. The 10x baseline (630_000ms = 10.5min) was insufficient;
101+
// the 2x medium factor lifts it to 1_260_000ms (21min), covering the
102+
// reported case with margin.
103+
expect(resolveWhisperTimeoutMs(63, { model: "medium.en" })).toBe(1_260_000);
104+
});
105+
106+
it("quadruples the auto-scaled window for the large family", () => {
107+
expect(resolveWhisperTimeoutMs(60, { model: "large-v3" })).toBe(2_400_000);
108+
});
109+
110+
it("still enforces the five-minute floor on tiny/base short clips", () => {
111+
// 10s * 10 * 0.5 = 50_000ms — below the floor, so the floor wins.
112+
expect(resolveWhisperTimeoutMs(10, { model: "tiny.en" })).toBe(300_000);
113+
});
114+
115+
it("still enforces the twelve-hour cap on large-model marathon clips", () => {
116+
// 4320s * 10 * 4 = 172_800_000ms — the cap wins.
117+
expect(resolveWhisperTimeoutMs(4320, { model: "large-v3" })).toBe(43_200_000);
118+
});
119+
120+
it("scales the null-duration fallback by the model factor", () => {
121+
// When ffprobe can't read the WAV, we lose duration signal but still know
122+
// the model. Scaling the floor keeps heavy models proportionally covered.
123+
expect(resolveWhisperTimeoutMs(null, { model: "medium.en" })).toBe(600_000);
124+
expect(resolveWhisperTimeoutMs(null, { model: "large-v3" })).toBe(1_200_000);
125+
expect(resolveWhisperTimeoutMs(null, { model: "small.en" })).toBe(300_000);
126+
});
127+
});
128+
129+
describe("resolveWhisperTimeoutMs with overrideMs", () => {
130+
it("respects the explicit override even below the auto-scaled floor", () => {
131+
// A user who deliberately passed --timeout 30000 on a short clip meant 30s,
132+
// not five minutes. The auto-scaled floor must NOT stomp on the explicit
133+
// value — that would silently defeat the flag.
134+
expect(resolveWhisperTimeoutMs(60, { overrideMs: 30_000 })).toBe(30_000);
135+
});
136+
137+
it("caps the override at the twelve-hour ceiling", () => {
138+
// A runaway value still can't hang the process forever.
139+
expect(resolveWhisperTimeoutMs(60, { overrideMs: 999_999_999 })).toBe(43_200_000);
140+
});
141+
142+
it("ignores the model factor when overrideMs is set", () => {
143+
// Override wins outright — the model factor only affects the auto-scaled
144+
// path. Otherwise `--timeout 60000` on `medium.en` would silently become
145+
// 120_000ms and break the discoverability contract.
146+
expect(resolveWhisperTimeoutMs(60, { overrideMs: 60_000, model: "medium.en" })).toBe(60_000);
147+
});
148+
149+
it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])(
150+
"falls back to auto-scaling when overrideMs is invalid (%s)",
151+
(invalid) => {
152+
// Invalid override → auto-scaled default kicks in (10s * 10 = 100_000ms →
153+
// floor 300_000ms). Prevents callers from accidentally disabling the
154+
// timeout via a bad env var.
155+
expect(resolveWhisperTimeoutMs(10, { overrideMs: invalid })).toBe(300_000);
156+
},
157+
);
158+
});
159+
160+
describe("isWhisperTimeoutError", () => {
161+
it("returns true for a Node SIGTERM child-timeout error", () => {
162+
const err = Object.assign(new Error("Command failed"), { signal: "SIGTERM" });
163+
expect(isWhisperTimeoutError(err)).toBe(true);
164+
});
165+
166+
it("returns true for an ETIMEDOUT-coded error", () => {
167+
const err = Object.assign(new Error("Command failed"), { code: "ETIMEDOUT" });
168+
expect(isWhisperTimeoutError(err)).toBe(true);
169+
});
170+
171+
it("returns false for a non-timeout child error", () => {
172+
const err = Object.assign(new Error("Exit code 1"), { status: 1, signal: null });
173+
expect(isWhisperTimeoutError(err)).toBe(false);
174+
});
175+
176+
it("returns false for a plain string", () => {
177+
expect(isWhisperTimeoutError("boom")).toBe(false);
178+
});
179+
});
180+
181+
describe("wrapWhisperTimeoutError", () => {
182+
it("passes non-timeout errors through unchanged", () => {
183+
const err = new Error("segfault");
184+
const result = wrapWhisperTimeoutError(err, {
185+
effectiveTimeoutMs: 600_000,
186+
model: "small.en",
187+
wasOverride: false,
188+
});
189+
expect(result).toBe(err);
190+
});
191+
192+
it("wraps SIGTERM timeouts with a discoverable hint naming --timeout and the env var", () => {
193+
const original = Object.assign(new Error("Command failed"), { signal: "SIGTERM" });
194+
const wrapped = wrapWhisperTimeoutError(original, {
195+
effectiveTimeoutMs: 1_260_000,
196+
model: "medium.en",
197+
wasOverride: false,
198+
});
199+
// Discoverability contract: message must name the flag, env var, effective
200+
// timeout, and cite the model so slow-CPU reporters see the knob.
201+
expect(wrapped).not.toBe(original);
202+
expect(wrapped.message).toContain("--timeout");
203+
expect(wrapped.message).toContain("HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS");
204+
expect(wrapped.message).toContain("1260s");
205+
expect(wrapped.message).toContain("medium.en");
206+
expect((wrapped as { cause?: unknown }).cause).toBe(original);
207+
});
208+
209+
it("labels the source as explicit when wasOverride is true", () => {
210+
const original = Object.assign(new Error("Command failed"), { code: "ETIMEDOUT" });
211+
const wrapped = wrapWhisperTimeoutError(original, {
212+
effectiveTimeoutMs: 90_000,
213+
model: "medium.en",
214+
wasOverride: true,
215+
});
216+
expect(wrapped.message).toContain("explicit --timeout 90000ms");
217+
});
218+
219+
it("coerces non-Error timeout-shaped values to Error without augmenting", () => {
220+
// A non-Error thrown value can't carry `.signal`, so it flows through
221+
// untouched but is still normalized to an Error instance for downstream
222+
// handlers that use instanceof checks.
223+
const wrapped = wrapWhisperTimeoutError("something bad", {
224+
effectiveTimeoutMs: 600_000,
225+
model: "small.en",
226+
wasOverride: false,
227+
});
228+
expect(wrapped).toBeInstanceOf(Error);
229+
expect(wrapped.message).toBe("something bad");
230+
expect(wrapped.message).not.toContain("--timeout");
231+
});
232+
});
233+
58234
describe("resolveAudioPreparationTimeoutMs", () => {
59235
it.each([
60236
[10, 120_000],

0 commit comments

Comments
 (0)