mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(engine): renders under a CPU quota get their workers back (#8262)
* fix(engine): renders under a CPU quota get their workers back * fix(engine): the usable CPU count stays within the host's online CPUs
This commit is contained in:
@@ -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<void> {
|
||||
|
||||
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(
|
||||
|
||||
@@ -88,6 +88,7 @@ export {
|
||||
getSystemTotalMb,
|
||||
hostCpuCount,
|
||||
usableCpuCount,
|
||||
cpuBudget,
|
||||
isLowMemorySystem,
|
||||
LOW_MEMORY_TOTAL_MB_THRESHOLD,
|
||||
} from "./services/systemMemory.js";
|
||||
|
||||
@@ -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)))));
|
||||
|
||||
@@ -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<string, string>;
|
||||
hostTotalMb?: number;
|
||||
platform?: NodeJS.Platform;
|
||||
@@ -43,6 +45,8 @@ async function withSystemMemoryMocks(
|
||||
run: (systemMemory: SystemMemoryModule) => void | Promise<void>,
|
||||
): Promise<void> {
|
||||
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(
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -15,7 +15,7 @@ const trace = vi.hoisted(() => ({
|
||||
|
||||
vi.mock("@hyperframes/engine", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@hyperframes/engine")>()),
|
||||
usableCpuCount: () => 8,
|
||||
cpuBudget: () => 8,
|
||||
}));
|
||||
vi.mock("./render/shared.js", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("./render/shared.js")>()),
|
||||
|
||||
@@ -18,7 +18,7 @@ const trace = vi.hoisted(() => ({
|
||||
|
||||
vi.mock("@hyperframes/engine", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@hyperframes/engine")>()),
|
||||
usableCpuCount: () => trace.cpus,
|
||||
cpuBudget: () => trace.cpus,
|
||||
}));
|
||||
|
||||
vi.mock("./render/shared.js", async (importOriginal) => ({
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user