diff --git a/packages/cli/src/commands/render/present.ts b/packages/cli/src/commands/render/present.ts index b14fa4d14c..471c191c31 100644 --- a/packages/cli/src/commands/render/present.ts +++ b/packages/cli/src/commands/render/present.ts @@ -1,6 +1,6 @@ import { readFileSync } from "node:fs"; -import { availableParallelism } from "node:os"; import { fpsToFfmpegArg, terminalText } from "@hyperframes/core"; +import { cpuBudget } from "@hyperframes/engine"; import { c } from "../../ui/colors.js"; import type { RenderPlan } from "./plan.js"; @@ -28,9 +28,7 @@ async function presentRenderWarnings(plan: RenderPlan): Promise { function presentRenderSummary(plan: RenderPlan): void { const workerLabel = - plan.workers != null - ? `${plan.workers} workers` - : `auto workers (${availableParallelism()} cores usable)`; + plan.workers != null ? `${plan.workers} workers` : `auto workers (${cpuBudget()} cores usable)`; const nameLabel = plan.entryFile ? `${plan.project.name}/${plan.entryFile}` : plan.project.name; console.log(""); console.log( diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts index 2eb58eab61..0e66e7f750 100644 --- a/packages/engine/src/index.ts +++ b/packages/engine/src/index.ts @@ -88,6 +88,7 @@ export { getSystemTotalMb, hostCpuCount, usableCpuCount, + cpuBudget, isLowMemorySystem, LOW_MEMORY_TOTAL_MB_THRESHOLD, } from "./services/systemMemory.js"; diff --git a/packages/engine/src/services/softwareEncoderThreads.ts b/packages/engine/src/services/softwareEncoderThreads.ts index faa26a03e3..5229711344 100644 --- a/packages/engine/src/services/softwareEncoderThreads.ts +++ b/packages/engine/src/services/softwareEncoderThreads.ts @@ -1,4 +1,4 @@ -import { usableCpuCount } from "./systemMemory.js"; +import { cpuBudget } from "./systemMemory.js"; export const X265_MAX_THREADS = 16; @@ -6,7 +6,7 @@ export const X265_MAX_THREADS = 16; export function appendSoftwareEncoderThreadsArg( args: string[], encoder: "libx264" | "libx265", - parallelism: number = usableCpuCount(), + parallelism: number = cpuBudget(), ): void { const cap = encoder === "libx265" ? X265_MAX_THREADS : Infinity; args.push("-threads", String(Math.min(cap, Math.max(1, Math.floor(parallelism))))); diff --git a/packages/engine/src/services/systemMemory.test.ts b/packages/engine/src/services/systemMemory.test.ts index 603d702adc..2da2f103b5 100644 --- a/packages/engine/src/services/systemMemory.test.ts +++ b/packages/engine/src/services/systemMemory.test.ts @@ -19,6 +19,8 @@ const CGROUP_V1_MEMORY_LIMIT_PATH = "/sys/fs/cgroup/memory/memory.limit_in_bytes type SystemMemoryModule = typeof import("./systemMemory.js"); type MockSystemMemoryOptions = { + availableParallelism?: number; + hostCpus?: number; files?: Record; hostTotalMb?: number; platform?: NodeJS.Platform; @@ -43,6 +45,8 @@ async function withSystemMemoryMocks( run: (systemMemory: SystemMemoryModule) => void | Promise, ): Promise { const { + availableParallelism = 32, + hostCpus = 32, files = {}, hostTotalMb = 32768, platform = "linux", @@ -54,6 +58,8 @@ async function withSystemMemoryMocks( vi.resetModules(); vi.doMock("os", () => ({ + availableParallelism: () => availableParallelism, + cpus: () => Array.from({ length: hostCpus }, () => ({})), totalmem: () => hostTotalMb * BYTES_PER_MIB, })); vi.doMock("fs", () => ({ @@ -194,6 +200,72 @@ describe("getCgroupCpuLimit", () => { }); }); +describe("usableCpuCount under a CPU quota", () => { + // Node 22.23 (libuv 1.51) clamps availableParallelism() to a cgroup v2 quota, as on a Kubernetes CPU limit. + const quotaOfSix = { + availableParallelism: 6, + files: { "/sys/fs/cgroup/cpu.max": "600000 100000" }, + }; + + it("is the affinity count, leaving the quota to getCgroupCpuLimit", async () => { + await withSystemMemoryMocks( + { + ...quotaOfSix, + files: { + ...quotaOfSix.files, + "/proc/self/status": "Name:\tnode\nCpus_allowed_list:\t0-31\n", + }, + }, + ({ usableCpuCount, getCgroupCpuLimit }) => { + expect(usableCpuCount()).toBe(32); + expect(getCgroupCpuLimit()).toBe(6); + }, + ); + }); + + it("is a cpuset's count when a cpuset and a quota both apply", async () => { + await withSystemMemoryMocks( + { + ...quotaOfSix, + files: { ...quotaOfSix.files, "/proc/self/status": "Cpus_allowed_list:\t0-3,8,10-11\n" }, + }, + ({ usableCpuCount }) => expect(usableCpuCount()).toBe(7), + ); + }); + + it("never counts more CPUs than the host has online", async () => { + await withSystemMemoryMocks( + { + ...quotaOfSix, + hostCpus: 16, + files: { ...quotaOfSix.files, "/proc/self/status": "Cpus_allowed_list:\t0-63\n" }, + }, + ({ usableCpuCount }) => expect(usableCpuCount()).toBe(16), + ); + }); + + it("leaves cpuBudget at the quota's whole CPUs", async () => { + await withSystemMemoryMocks( + { + files: { + "/sys/fs/cgroup/cpu.max": "350000 100000", + "/proc/self/status": "Cpus_allowed_list:\t0-31\n", + }, + }, + ({ cpuBudget, usableCpuCount }) => { + expect(usableCpuCount()).toBe(32); + expect(cpuBudget()).toBe(3); + }, + ); + }); + + it("falls back to availableParallelism when the affinity list is unreadable", async () => { + await withSystemMemoryMocks(quotaOfSix, ({ usableCpuCount }) => + expect(usableCpuCount()).toBe(6), + ); + }); +}); + describe("getCgroupMemoryLimitMb", () => { it("returns only an actual cgroup limit and never host RAM", async () => { await withSystemMemoryMocks( diff --git a/packages/engine/src/services/systemMemory.ts b/packages/engine/src/services/systemMemory.ts index bfce941589..a4d22f6356 100644 --- a/packages/engine/src/services/systemMemory.ts +++ b/packages/engine/src/services/systemMemory.ts @@ -275,7 +275,27 @@ export function getAvailableMemoryMb(): number { /** CPUs this process may run on: a cpuset (taskset, --cpuset-cpus) lowers it, a CPU quota does not. */ export function usableCpuCount(): number { - return availableParallelism(); + // libuv clamps availableParallelism() to a cgroup v2 quota; getCgroupCpuLimit owns the quota, so count the affinity. + if (getCgroupCpuLimit() === null) return availableParallelism(); + const affinity = countCpuList(readCgroupFile("/proc/self/status")); + // The affinity mask can name offline CPUs; cpus() lists only online ones. + return affinity === null ? availableParallelism() : Math.min(affinity, cpus().length); +} + +/** Whole CPUs of time this process gets: the usable CPUs, lowered by a CPU quota. */ +export function cpuBudget(): number { + const quota = getCgroupCpuLimit(); + return Math.max(1, Math.min(usableCpuCount(), quota === null ? Infinity : Math.floor(quota))); +} + +function countCpuList(status: string | null): number | null { + const list = status?.match(/^Cpus_allowed_list:\s*(\S+)/m)?.[1]; + if (!list) return null; + const count = list.split(",").reduce((sum, range) => { + const [first, last = first] = range.split("-").map(Number); + return sum + last! - first! + 1; + }, 0); + return count > 0 ? count : null; } export function hostCpuCount(): number { diff --git a/packages/producer/src/services/distributed/assemble.test.ts b/packages/producer/src/services/distributed/assemble.test.ts index d4376512c4..7c9ae3e657 100644 --- a/packages/producer/src/services/distributed/assemble.test.ts +++ b/packages/producer/src/services/distributed/assemble.test.ts @@ -26,10 +26,11 @@ import { statSync, writeFileSync, } from "node:fs"; -import { availableParallelism, tmpdir } from "node:os"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { applyFaststart, + cpuBudget, muxVideoWithAudio, PROVENANCE_RENDERER_NAME, PROVENANCE_VERSION, @@ -722,7 +723,7 @@ describe("assemble()", () => { it("cfr re-encode pins x264 threads to the CPU quota", () => { const args = cfrEncodeArgs(["-i", "chunk.mp4"], {}, "30"); - expect(args[args.indexOf("-threads") + 1]).toBe(String(availableParallelism())); + expect(args[args.indexOf("-threads") + 1]).toBe(String(cpuBudget())); }); it("cfr re-encode keeps the keyframe interval and the peak cap", () => { diff --git a/packages/producer/src/services/distributed/renderChunk.ts b/packages/producer/src/services/distributed/renderChunk.ts index 016ff7dcdf..d39939da85 100644 --- a/packages/producer/src/services/distributed/renderChunk.ts +++ b/packages/producer/src/services/distributed/renderChunk.ts @@ -58,7 +58,7 @@ import { readWebGlVendorInfoFromCanvas, resolveConfig, type ShownBox, - usableCpuCount, + cpuBudget, } from "@hyperframes/engine"; import { defaultLogger } from "../../logger.js"; import { @@ -1043,10 +1043,10 @@ export async function renderChunk( const captureSession = session; session = null; verifyStarted = Date.now(); - overlap.current = canEncodeWhileCapturing(encodeInput, chunkWorkerCount, usableCpuCount()) + overlap.current = canEncodeWhileCapturing(encodeInput, chunkWorkerCount, cpuBudget()) ? encodeWhileCapturing(encodeInput, framesInChunk, { workerCount: chunkWorkerCount, - cpuCount: usableCpuCount(), + cpuCount: cpuBudget(), }) : null; await observeRenderStage( diff --git a/packages/producer/src/services/renderOrchestrator.audioWait.test.ts b/packages/producer/src/services/renderOrchestrator.audioWait.test.ts index c4c5a8071b..c6b6d493dc 100644 --- a/packages/producer/src/services/renderOrchestrator.audioWait.test.ts +++ b/packages/producer/src/services/renderOrchestrator.audioWait.test.ts @@ -15,7 +15,7 @@ const trace = vi.hoisted(() => ({ vi.mock("@hyperframes/engine", async (importOriginal) => ({ ...(await importOriginal()), - usableCpuCount: () => 8, + cpuBudget: () => 8, })); vi.mock("./render/shared.js", async (importOriginal) => ({ ...(await importOriginal()), diff --git a/packages/producer/src/services/renderOrchestrator.captureDuringAudio.test.ts b/packages/producer/src/services/renderOrchestrator.captureDuringAudio.test.ts index 7c098fedb1..2d4eeb404c 100644 --- a/packages/producer/src/services/renderOrchestrator.captureDuringAudio.test.ts +++ b/packages/producer/src/services/renderOrchestrator.captureDuringAudio.test.ts @@ -18,7 +18,7 @@ const trace = vi.hoisted(() => ({ vi.mock("@hyperframes/engine", async (importOriginal) => ({ ...(await importOriginal()), - usableCpuCount: () => trace.cpus, + cpuBudget: () => trace.cpus, })); vi.mock("./render/shared.js", async (importOriginal) => ({ diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts index 3e6342efe5..e7cc907718 100644 --- a/packages/producer/src/services/renderOrchestrator.ts +++ b/packages/producer/src/services/renderOrchestrator.ts @@ -1,5 +1,5 @@ import type { ExpectedOutputDimensions } from "./render/outputDimensions.js"; -import { audioFailureDiagnostics, usableCpuCount } from "@hyperframes/engine"; +import { audioFailureDiagnostics, cpuBudget } from "@hyperframes/engine"; // fallow-ignore-file unused-type circular-dependency code-duplication complexity /** * Render Orchestrator Service @@ -5005,7 +5005,7 @@ async function executeRenderPipeline(input: { audioFailed.abort(error); }); const mixedAudio = () => audioWait.wait(audioReady); - if (usableCpuCount() < MIN_CPUS_TO_CAPTURE_DURING_MIX) await mixedAudio(); + if (cpuBudget() < MIN_CPUS_TO_CAPTURE_DURING_MIX) await mixedAudio(); resetCaptureAttemptProgress(job); @@ -5610,10 +5610,10 @@ async function executeRenderPipeline(input: { const overlap = !cfg.useDrawElement && workerSizing !== undefined && - canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, workerSizing.cpuCount) + canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, cpuBudget()) ? encodeWhileCapturing(encodeInput, totalFrames, { workerCount: capturePlan.workerCount, - cpuCount: workerSizing.cpuCount, + cpuCount: cpuBudget(), }) : null; const captureFrameStart = Date.now();