mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
Some checks are pending
Gitleaks / gitleaks (push) Waiting to run
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
* fix(analyze): enforce parse-worker heap caps under an inherited heap flag
V8 reads --max-old-space-size and --max-semi-space-size when it creates
an isolate, and the process-wide values override a Worker's
resourceLimits. Under the analyze respawn's flags every parser worker
therefore ran with the main heap limit instead of its own cap, and with
a 384 MiB young generation.
The default parser-worker factory now spawns through a process-wide
lease that clears both flags while workers start and restores them when
the last starting worker reports online, posts its first message, or
exits. A synchronous restore right after new Worker() races the isolate
creation on the worker thread, so the lease waits for those events.
Initial spawns, startup retries and replacements all use this factory.
The plan cleared only the old-space flag; measuring showed the
semi-space flag also overrides the worker's young generation (a 512 MiB
worker reported 896 MiB instead of 560 MiB), so the lease clears both.
Admission is unchanged here and still reserves at least the main heap
per worker, which over-reserves safely; the next commit charges each
worker its own cap.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): charge each parse worker its own heap cap in resource admission
Admission assumed every parser worker inherits the main heap limit, so it
charged each worker max(mainHeap, workerHeap) + 128 MiB, divided the main
heap by (requiredWorkers + 1), and also capped it at 35% of the total. In
a 10 GiB / 4-CPU container that admitted a 2639 MiB main heap, and on a
4-CPU host it admitted one parse worker at every size from 4 to 32 GiB.
The parser pool now enforces each worker's cap (previous commit), so a
worker is charged its own heap plus the 128 MiB native allowance. The
main heap holds the analysis peak and is sized first: it takes what the
pools, headroom and required workers leave, capped at 16384 MiB and at
an unpinned runtime limit. Automatic workers fill the remainder up to
the CPU count. The rejection minimum uses the same inequality.
4 CPUs, 200 MiB supervisor, no model (main / workers / worker heap):
4 GiB: 957 / 1 / 958 -> 1403 / 1 / 512
10 GiB: 2639 / 1 / 2639 -> 4206 / 1 / 1072
16 GiB: 4300 / 1 / 4300 -> 6850 / 3 / 512
A sweep over RAM, CPUs, explicit totals, heaps, workers, models and
supervisor sizes finds no newly rejected request, no smaller main heap
and no reservation above the total. isConstrainedPdgBuild is unchanged;
the measured 6 GiB / one-worker PDG envelope stays constrained.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): key the constrained PDG write guard on requested workers
isConstrainedPdgBuild serializes LadybugDB COPY/FTS and limits malloc
arenas for the measured 6 GiB, single-worker PDG configuration. It read
the admitted parser worker count. Since admission now charges workers
their own cap, an explicit small budget such as
--pdg --resource-budget 6144 --memory-budget 2048 on 4 CPUs fits three
workers and silently dropped the guard, although the graph write it
protects runs after the parser workers exit and its memory is the same.
The budget now carries the worker count the operator requested (the
explicit --workers value, or 1 when automatic) and the guard reads it.
Predicate sweep over 544,320 requests (158,826 admitted by every
version), pdg on, against upstream/main: 0 configurations lose the
guard; 1,920 gain it (explicit budgets where upstream/main fitted more
than one automatic worker), which only makes their COPY serial. The 416
configurations the previous commit had turned off are all constrained
again. Explicit --workers N > 1 stays unconstrained.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(analyze): describe enforced parser-worker heap caps
Parser workers used to run with the main heap limit by accident; they now
run at their admitted cap, 512 MiB on common hosts. Say so in MIGRATION.md
and next to --max-file-size in the README: files above roughly 2 MB or
large explicit sub-batches can exceed the cap, the file is quarantined,
and GITNEXUS_WORKER_HEAP_MB raises it.
Also fix two stale sentences: the RUNBOOK still said each worker reserves
at least the --memory-budget allocation, and the README named one heap
flag where the pool clears both --max-old-space-size and
--max-semi-space-size.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): cover a parser worker dying at its enforced heap cap
With caps now enforced, an oversized job ending in
ERR_WORKER_OUT_OF_MEMORY is an expected outcome, and no test drove a
worker past its cap. The new case runs a pool of one 512 MiB worker
under --max-old-space-size=3000 and has it allocate up to 1 GiB on one
file. It asserts that dispatch resolves, the log names the cap and
GITNEXUS_WORKER_HEAP_MB, the file is quarantined and counted in stats,
the slot respawns, and the files around it are still parsed.
On upstream/main the worker inherits the main limit, so the same file
parses, nothing is quarantined and the case fails on the missing hint.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): derive the respawned main heap from the mocked host
Three heap-respawn tests pinned the main heap the old admission rule
gave the mocked 16 GiB host (4300 MiB, respawned as
--max-old-space-size=3916). Admission now sizes the main heap first:
75% of RAM (12288 MiB) minus headroom, supervisor, graph pool, vector
pool and embedding queues, which gives 6858 MiB and an old space of
6858 - 3 x 128 = 6474 MiB.
The tests now compute that value from the same host constants instead
of a literal, and pin the supervisor's RSS below its 192 MiB floor: the
main heap now depends on the measured supervisor reservation, which
otherwise varies with the test process.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* perf(analyze): start community workers through the heap lease
Node shares one built-in code cache between a process's isolates and
accepts an entry only under the V8 flag hash it was compiled with. The
parser-worker heap lease clears the inherited heap flags while a worker
starts, so that worker recompiles the built-ins its startup needs and
stores them under the cleared hash. The Leiden worker, created after
the flags were restored, then rejected those entries and recompiled
again: about 14 ms on the analyze-resume incremental scenario, where
the CI benchmark measured a ~0.7% slowdown.
The graphology and icebug workers now start through the same lease, so
their startup reuses the parser worker's entries and their later loads
the main isolate's. They pass inheritedWorkerResourceLimits(), the old
space and three semi-spaces the inherited flags give, so their heap is
unchanged.
CPU profiles of three incremental pairs (16 GiB / 4 CPUs simulated),
built-in compile time added per worker vs the base revision: Leiden
+13.8 ms before, +0.1 ms after; the parser worker's startup recompile
(+11 ms) remains. Clearing the flags once without restoring was also
measured and moved the cost into the parser worker instead (+24.7 ms).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* Keep allocator defaults for multi-worker PDG parsing (#4045)
Apply the two-arena default only for a single admitted parser worker. Keep each worker's young generation inside its reservation, reuse its startup options, and share quoted numeric heap-flag parsing with CLI admission.
Cover allocator selection, real worker caps and reentrant startup events. Document community and loader heaps outside admission.
Validation: six incremental-index tests failed during a full run stopped early. All six passed in isolated reruns on the original and updated revisions.
* perf(analyze): lease community workers only after a parser worker did
Starting a worker under the cleared heap flags pays a one-time
recompile of the built-ins its startup needs, because Node's shared
built-in code cache is keyed by the V8 flag hash. Routing the community
workers through the lease saves that cost only when a parser worker has
already started under the cleared flags. With a warm parse cache, as in
`analyze --force` on an unchanged repository, no parser worker starts,
so the leased Leiden worker became the first to recompile: 6-file
repository, 20 runs each, Leiden spawn to result median 47.5 ms on the
base revision, 71.0 ms with the lease, 49.0 ms with this change.
spawnWithInheritedHeap() now takes the lease, with
inheritedWorkerResourceLimits(), only after a parser worker has used
the cleared flags in this process, and otherwise spawns plainly under
the inherited flags as before. The parser-worker path is unchanged.
Also restore the caveat that a Worker created in the analysis process
without these helpers while a lease is open gets V8's default heap.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): keep two allocator arenas when several PDG parser workers fit
The constrained PDG guard starts the first analyze child, which runs the
parser pool and then the graph writer, with MALLOC_ARENA_MAX=2 on Linux
with glibc. a7691f8cd limited that to one admitted parser worker. Two
measurements disagree only on what they measured: four workers on 210
TypeScript files parsed in 14.36-17.90 s with allocator defaults and
19.44-20.15 s with two arenas (parse time only); three workers on a Kotlin
repository of 2,448 files in an 8 GiB, 4-CPU container parsed in 30-34 s at
a ~3,050 MiB cgroup peak with two arenas, and in ~27 s at ~3,530 MiB with
defaults. The guard exists for the memory, so two arenas apply again
whenever it does. An operator's MALLOC_ARENA_MAX or glibc.malloc.arena_max
still wins.
The respawn test now runs the Linux branch on every host and covers an
automatic multi-worker admission, --workers 1, and an operator override.
The benchmark note carries both measurement sets.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): read every heap-flag spelling V8 and Node accept in the shared reader
lib/node-size-flag.ts is the one reader for heap flags in CLI admission and
the worker lease. It only knew `--name`, so `-max-old-space-size=3000` (V8
accepts one leading dash) pinned the heap unseen, and a signed or
space-padded size (`=+3000`, `= 3000`) was skipped although V8 applies it.
The reader now accepts one or two leading dashes, reads sizes like strtoull,
ignores a value V8 rejects as out of bounds (V8 keeps the earlier one), and
reports a value V8 accepts but JavaScript cannot hold exactly as NaN. New
helpers read an option's raw value (for the percentage flag) and a V8
boolean flag with both `--no-` and `--no` negation (for frozen flags), all
by argument so an `--eval` source or a `--title` value is never a flag, plus
process-level variants in which a command-line value wins over NODE_OPTIONS
even when it is zero.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): derive inherited worker heaps from the live main heap, by argument
The lease read heap flags from `process.execArgv.join(' ')` and treated a
command-line zero as absent, and it restored the main isolate's whole limit
as old space under the percentage flag. On Node 22 that let an `--eval`
source naming the percentage flag grow a later worker from 1,072 to
1,120 MiB, a valid title `--title 'worker --max-old-space-size=2000'` shrink
it from 4,144 to 2,048 MiB, command-line zeros over NODE_OPTIONS 2000/64
leave it at 2,192 instead of 4,144 MiB, and a 12.5% pin with a 64 MiB
semi-space change an ordinary worker's heap between before and after
parsing. `--max-heap-size` was never cleared, so a capped worker kept it, and
under `--freeze-flags-after-init` the first flag write aborted V8.
`inheritedHeap()` now reads the flags argument by argument through the
shared reader (command line over NODE_OPTIONS, zero included) and checks them
against the main isolate's live `heap_size_limit`, which is old space plus a
three-semi-space young generation. When they agree, the lease clears and
restores old space, semi-space and `--max-heap-size` as read, and
community-style workers get the main isolate's old space and young
generation from the live limit. When they disagree, or a heap flag is set
under frozen flags, the lease is skipped before any flag write and admission
charges every parser worker the main heap (`workerHeapCapEnforced: false`).
The percentage's old space follows Node's own formula, checked by the live
limit. The released-once guard for reentrant startup events is kept.
Subprocess tests in test/integration/worker-heap-flags.test.ts reproduce
each case with real flags from execArgv and NODE_OPTIONS, including that a
fresh ordinary worker gets the same heap before and after parsing.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): pin the host-resources wiring of worker-cap enforceability
Replacing `workerHeapCapEnforceable()` with `true` in
`resolveHostAnalysisResources` left every unit test green; only a
subprocess test against a built dist caught it. A unit test now drives the
predicate both ways and checks that an unenforced cap charges each worker
the main heap, and that an explicit `workerHeapCapEnforced` still wins.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): let a command-line zero hide a NODE_OPTIONS heap pin in the CLI
Node applies the command line after NODE_OPTIONS, so
`node --max-old-space-size=0` runs at V8's default even when NODE_OPTIONS
pins a size. Manual admission and the budget decision already read the
process value with the command line first; the manual-heap check and
ensureHeap's ambient pin did not: under `--max-old-space-size=0` with a
large NODE_OPTIONS pin, analyze took the heap as pinned by the operator and
skipped its own sizing, or warned about a pin that was not in effect.
Both now take a NODE_OPTIONS pin only when the command line sets no
`--max-old-space-size` of its own.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(analyze): name the heap-flag changes the worker-cap lease cannot see
A preload can change heap flags after startup without leaving anything the
live-limit check contradicts (`v8.setFlagsFromString`, or deleting
NODE_OPTIONS), and a module-hooks thread that a preload's `module.register()`
starts in a leased worker gets V8's default heap: Node takes no
`resourceLimits` for it. Neither is fixable from the lease; the module doc
and the README worker-cap paragraph now say so in one sentence each.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): restore process.platform without a non-null assertion
The arena test added a no-non-null-assertion lint warning when it saved the
platform descriptor; fall back to an empty descriptor instead.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): verify worker heap defaults across host sizes (#4045)
Compare ignored and reset heap flags against a clean Node subprocess. Pin the page-size input in the respawn fixture and exercise a real process title whose value starts with a dash.
* test: clarify heap reset and worker recovery coverage
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
526 lines
18 KiB
TypeScript
526 lines
18 KiB
TypeScript
import { EventEmitter } from 'node:events';
|
|
import type { Worker } from 'node:worker_threads';
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
|
|
// V8 flags are process-wide: record the lease's flag writes instead of
|
|
// applying them to the test process.
|
|
// The main isolate's live heap limit is stubbed too, so each case can state
|
|
// the limit its flags give.
|
|
const setFlags = vi.hoisted(() => vi.fn<(flags: string) => void>());
|
|
const mainHeap = vi.hoisted(() => ({ limitMb: 3048 }));
|
|
vi.mock('node:v8', async () => {
|
|
const actual = await vi.importActual<typeof import('node:v8')>('node:v8');
|
|
const mocked = {
|
|
...actual,
|
|
setFlagsFromString: setFlags,
|
|
getHeapStatistics: () => ({
|
|
...actual.getHeapStatistics(),
|
|
heap_size_limit: mainHeap.limitMb * 1024 * 1024,
|
|
}),
|
|
};
|
|
return { ...mocked, default: mocked };
|
|
});
|
|
|
|
import {
|
|
inheritedHeap,
|
|
percentageOldSpaceMb,
|
|
spawnWithOwnHeapLimit,
|
|
workerHeapCapEnforceable,
|
|
} from '../../src/core/ingestion/workers/worker-heap-limit.js';
|
|
|
|
const MIB = 1024 * 1024;
|
|
const fakeWorker = (): Worker => new EventEmitter() as unknown as Worker;
|
|
|
|
describe('inheritedHeap', () => {
|
|
const heap = (execArgv: string[], nodeOptions: string, limitMb: number) =>
|
|
inheritedHeap(execArgv, nodeOptions, limitMb * MIB, 49_152 * MIB, 0);
|
|
|
|
it.each([
|
|
[
|
|
'an execArgv size',
|
|
['--max-old-space-size=3000'],
|
|
'',
|
|
3048,
|
|
['--max-old-space-size=3000'],
|
|
{ maxOldGenerationSizeMb: 3000, maxYoungGenerationSizeMb: 48 },
|
|
],
|
|
[
|
|
'execArgv over NODE_OPTIONS',
|
|
['--max-old-space-size=3000'],
|
|
'--max-old-space-size=2000',
|
|
3096,
|
|
['--max-old-space-size=3000'],
|
|
{ maxOldGenerationSizeMb: 3000, maxYoungGenerationSizeMb: 96 },
|
|
],
|
|
[
|
|
'old and semi-space flags',
|
|
['--max-old-space-size=3000', '--max-semi-space-size=128'],
|
|
'',
|
|
3384,
|
|
['--max-old-space-size=3000', '--max-semi-space-size=128'],
|
|
{ maxOldGenerationSizeMb: 3000, maxYoungGenerationSizeMb: 384 },
|
|
],
|
|
[
|
|
'a semi-space flag V8 rounds up to a power of two',
|
|
[],
|
|
'--max-old-space-size=3000 --max-semi-space-size=10',
|
|
3048,
|
|
['--max-old-space-size=3000', '--max-semi-space-size=10'],
|
|
{ maxOldGenerationSizeMb: 3000, maxYoungGenerationSizeMb: 48 },
|
|
],
|
|
[
|
|
'a semi-space flag alone, over the default old space',
|
|
['--max-semi-space-size=64'],
|
|
'',
|
|
4288,
|
|
['--max-semi-space-size=64'],
|
|
{ maxOldGenerationSizeMb: 4096, maxYoungGenerationSizeMb: 192 },
|
|
],
|
|
[
|
|
'--max-heap-size with a smaller old space, whose young generation fills the rest',
|
|
['--max-heap-size=3000', '--max-old-space-size=1000'],
|
|
'',
|
|
4072,
|
|
['--max-old-space-size=1000', '--max-heap-size=3000'],
|
|
{ maxOldGenerationSizeMb: 1000, maxYoungGenerationSizeMb: 3072 },
|
|
],
|
|
[
|
|
'--max-heap-size with a larger old space',
|
|
['--max-heap-size=3000', '--max-old-space-size=5000'],
|
|
'',
|
|
5001.5,
|
|
['--max-old-space-size=5000', '--max-heap-size=3000'],
|
|
{ maxOldGenerationSizeMb: 5000, maxYoungGenerationSizeMb: 1.5 },
|
|
],
|
|
[
|
|
'--max-heap-size and a semi-space flag',
|
|
['--max-heap-size=3000', '--max-semi-space-size=64'],
|
|
'',
|
|
3000,
|
|
['--max-semi-space-size=64', '--max-heap-size=3000'],
|
|
{ maxOldGenerationSizeMb: 2808, maxYoungGenerationSizeMb: 192 },
|
|
],
|
|
[
|
|
'--max-heap-size alone, as the whole limit in old space',
|
|
['--max-heap-size=3072'],
|
|
'',
|
|
3072,
|
|
['--max-heap-size=3072'],
|
|
{ maxOldGenerationSizeMb: 3072 },
|
|
],
|
|
['no flag', [], '', 4144, [], undefined],
|
|
// V8 ignores a value out of its bounds, so it is no flag at all.
|
|
[
|
|
'an out-of-bounds size V8 ignored',
|
|
['--max-old-space-size=100000000000000000000'],
|
|
'',
|
|
4144,
|
|
[],
|
|
undefined,
|
|
],
|
|
[
|
|
'an out-of-bounds --max-heap-size beside a size the limit confirms',
|
|
['--max-old-space-size=3000', '--max-heap-size=100000000000000000000'],
|
|
'',
|
|
3048,
|
|
['--max-old-space-size=3000'],
|
|
{ maxOldGenerationSizeMb: 3000, maxYoungGenerationSizeMb: 48 },
|
|
],
|
|
[
|
|
'an explicit zero over NODE_OPTIONS',
|
|
['--max-old-space-size=0'],
|
|
'--max-old-space-size=800',
|
|
4144,
|
|
[],
|
|
undefined,
|
|
],
|
|
])('reads %s', (_label, execArgv, nodeOptions, limitMb, flags, limits) => {
|
|
expect(heap(execArgv, nodeOptions, limitMb)).toEqual({ flags, limits, consistent: true });
|
|
});
|
|
|
|
it.each([
|
|
[
|
|
'a size V8 accepts but JavaScript cannot hold exactly',
|
|
['--max-old-space-size=9007199254740993'],
|
|
'',
|
|
4144,
|
|
],
|
|
['a size that leaves no young generation', ['--max-old-space-size=4144'], '', 4144],
|
|
['a size the live limit contradicts', [], '--max-old-space-size=2000', 3048],
|
|
[
|
|
'a semi-space flag the live limit contradicts',
|
|
['--max-old-space-size=3000', '--max-semi-space-size=64'],
|
|
'',
|
|
3048,
|
|
],
|
|
['a --max-heap-size the live limit contradicts', ['--max-heap-size=3072'], '', 4144],
|
|
[
|
|
'an inexact --max-heap-size beside a size the limit confirms',
|
|
['--max-old-space-size=3000', '--max-heap-size=9007199254740993'],
|
|
'',
|
|
3048,
|
|
],
|
|
])('is not consistent with %s', (_label, execArgv, nodeOptions, limitMb) => {
|
|
expect(heap(execArgv, nodeOptions, limitMb)).toEqual({
|
|
flags: [],
|
|
limits: undefined,
|
|
consistent: false,
|
|
});
|
|
});
|
|
|
|
it("restores the old space Node's percentage formula gives, checked against the live limit", () => {
|
|
// 25% of the cgroup limit whenever Node reports one, even above physical RAM.
|
|
const percentage = (limitMb: number, totalMb: number, constrainedMb: number) =>
|
|
inheritedHeap(
|
|
['--max-old-space-size=3000'],
|
|
'--max-old-space-size-percentage=25',
|
|
limitMb * MIB,
|
|
totalMb * MIB,
|
|
constrainedMb * MIB,
|
|
);
|
|
expect(percentage(12_336, 49_152, 0).flags).toEqual(['--max-old-space-size=12288']);
|
|
expect(percentage(2096, 49_152, 8192).flags).toEqual(['--max-old-space-size=2048']);
|
|
expect(percentage(15_408, 34_304, 61_440)).toEqual({
|
|
flags: ['--max-old-space-size=15360'],
|
|
limits: { maxOldGenerationSizeMb: 15_360, maxYoungGenerationSizeMb: 48 },
|
|
consistent: true,
|
|
});
|
|
// A limit the formula does not explain leaves the flags unread.
|
|
expect(percentage(12_400, 49_152, 0).consistent).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe('spawnWithOwnHeapLimit', () => {
|
|
let execArgv: string[];
|
|
let nodeOptions: string | undefined;
|
|
|
|
beforeEach(() => {
|
|
setFlags.mockClear();
|
|
execArgv = process.execArgv;
|
|
nodeOptions = process.env.NODE_OPTIONS;
|
|
process.execArgv = ['--max-old-space-size=3000'];
|
|
delete process.env.NODE_OPTIONS;
|
|
mainHeap.limitMb = 3048;
|
|
});
|
|
|
|
afterEach(() => {
|
|
process.execArgv = execArgv;
|
|
if (nodeOptions === undefined) delete process.env.NODE_OPTIONS;
|
|
else process.env.NODE_OPTIONS = nodeOptions;
|
|
});
|
|
|
|
it('clears the flag once for concurrent spawns and restores it after the last is online', () => {
|
|
const workers = [fakeWorker(), fakeWorker(), fakeWorker()];
|
|
for (const worker of workers) expect(spawnWithOwnHeapLimit(() => worker)).toBe(worker);
|
|
expect(setFlags.mock.calls).toEqual([['--max-old-space-size=0']]);
|
|
|
|
workers[0].emit('online');
|
|
workers[1].emit('online');
|
|
expect(setFlags).toHaveBeenCalledTimes(1);
|
|
workers[2].emit('online');
|
|
expect(setFlags.mock.calls).toEqual([
|
|
['--max-old-space-size=0'],
|
|
['--max-old-space-size=3000'],
|
|
]);
|
|
|
|
// Later events from the same workers never release the lease twice.
|
|
workers[0].emit('message', { type: 'ready' });
|
|
workers[2].emit('exit', 0);
|
|
expect(setFlags).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it.each([
|
|
['its first message', (worker: Worker) => worker.emit('message', { type: 'ready' })],
|
|
['exit', (worker: Worker) => worker.emit('exit', 1)],
|
|
])('releases the lease on %s', (_label, settle) => {
|
|
const worker = spawnWithOwnHeapLimit(fakeWorker);
|
|
settle(worker);
|
|
expect(setFlags.mock.calls).toEqual([
|
|
['--max-old-space-size=0'],
|
|
['--max-old-space-size=3000'],
|
|
]);
|
|
});
|
|
|
|
it('keeps the second worker leased when the first reports a message during online', () => {
|
|
const first = spawnWithOwnHeapLimit(fakeWorker);
|
|
const second = spawnWithOwnHeapLimit(fakeWorker);
|
|
// EventEmitter already captured the online listeners when this emits message.
|
|
first.prependOnceListener('online', () => first.emit('message', { type: 'ready' }));
|
|
first.emit('online');
|
|
expect(setFlags.mock.calls).toEqual([['--max-old-space-size=0']]);
|
|
second.emit('online');
|
|
expect(setFlags).toHaveBeenLastCalledWith('--max-old-space-size=3000');
|
|
});
|
|
|
|
it('releases the lease when the spawn throws', () => {
|
|
expect(() =>
|
|
spawnWithOwnHeapLimit(() => {
|
|
throw new Error('spawn failed');
|
|
}),
|
|
).toThrow('spawn failed');
|
|
expect(setFlags.mock.calls).toEqual([
|
|
['--max-old-space-size=0'],
|
|
['--max-old-space-size=3000'],
|
|
]);
|
|
|
|
// The released lease opens again for the next spawn.
|
|
const worker = spawnWithOwnHeapLimit(fakeWorker);
|
|
worker.emit('online');
|
|
expect(setFlags).toHaveBeenCalledTimes(4);
|
|
});
|
|
|
|
it('leaves no error listener, so an unhandled worker error still surfaces', () => {
|
|
const worker = spawnWithOwnHeapLimit(fakeWorker);
|
|
expect(worker.listenerCount('error')).toBe(0);
|
|
worker.emit('online');
|
|
expect(worker.listenerCount('online')).toBe(0);
|
|
expect(worker.listenerCount('message')).toBe(0);
|
|
expect(worker.listenerCount('exit')).toBe(0);
|
|
});
|
|
|
|
it('clears and restores the semi-space flag with the old-space flag', () => {
|
|
process.execArgv = ['--max-old-space-size=3000'];
|
|
process.env.NODE_OPTIONS = '--max-semi-space-size=128';
|
|
mainHeap.limitMb = 3000 + 3 * 128;
|
|
const worker = spawnWithOwnHeapLimit(fakeWorker);
|
|
expect(setFlags.mock.calls).toEqual([['--max-old-space-size=0'], ['--max-semi-space-size=0']]);
|
|
worker.emit('online');
|
|
expect(setFlags.mock.calls.slice(2)).toEqual([
|
|
['--max-old-space-size=3000'],
|
|
['--max-semi-space-size=128'],
|
|
]);
|
|
});
|
|
|
|
it('clears a semi-space flag set without an old-space flag', () => {
|
|
process.execArgv = ['--max-semi-space-size=64'];
|
|
spawnWithOwnHeapLimit(fakeWorker).emit('exit', 0);
|
|
expect(setFlags.mock.calls).toEqual([
|
|
['--max-semi-space-size=0'],
|
|
['--max-semi-space-size=64'],
|
|
]);
|
|
});
|
|
|
|
it('does not touch V8 flags when the process set no heap flag', () => {
|
|
process.execArgv = [];
|
|
const worker = spawnWithOwnHeapLimit(fakeWorker);
|
|
worker.emit('online');
|
|
expect(setFlags).not.toHaveBeenCalled();
|
|
expect(worker.listenerCount('online')).toBe(0);
|
|
});
|
|
|
|
it.each([
|
|
[
|
|
'a quoted NODE_OPTIONS value',
|
|
[],
|
|
'--max-old-space-size="3000"',
|
|
3048,
|
|
['--max-old-space-size=0'],
|
|
['--max-old-space-size=3000'],
|
|
],
|
|
[
|
|
'--max-heap-size',
|
|
['--max-heap-size=3072'],
|
|
'',
|
|
3072,
|
|
['--max-heap-size=0'],
|
|
['--max-heap-size=3072'],
|
|
],
|
|
[
|
|
'--max-heap-size with a smaller old space',
|
|
['--max-heap-size=3000', '--max-old-space-size=1000'],
|
|
'',
|
|
4072,
|
|
['--max-old-space-size=0', '--max-heap-size=0'],
|
|
['--max-old-space-size=1000', '--max-heap-size=3000'],
|
|
],
|
|
])('clears and restores %s', (_label, argv, options, limitMb, cleared, restored) => {
|
|
process.execArgv = argv;
|
|
process.env.NODE_OPTIONS = options;
|
|
mainHeap.limitMb = limitMb;
|
|
const worker = spawnWithOwnHeapLimit(fakeWorker);
|
|
expect(setFlags.mock.calls.map(([flags]) => flags)).toEqual(cleared);
|
|
worker.emit('online');
|
|
expect(setFlags.mock.calls.map(([flags]) => flags)).toEqual([...cleared, ...restored]);
|
|
});
|
|
|
|
it('does not restore a NODE_OPTIONS heap that an explicit command-line zero overrides', () => {
|
|
process.execArgv = ['--max-old-space-size=0'];
|
|
process.env.NODE_OPTIONS = '--max-old-space-size=800';
|
|
spawnWithOwnHeapLimit(fakeWorker).emit('online');
|
|
expect(setFlags).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('releases each worker once, whichever of online, message and exit comes first', () => {
|
|
const [first, second] = [fakeWorker(), fakeWorker()];
|
|
spawnWithOwnHeapLimit(() => first);
|
|
spawnWithOwnHeapLimit(() => second);
|
|
// All three settle events from one worker count once: the other worker is
|
|
// still starting, so the flags stay cleared.
|
|
first.emit('online');
|
|
first.emit('message', { type: 'ready' });
|
|
first.emit('exit', 0);
|
|
expect(setFlags.mock.calls).toEqual([['--max-old-space-size=0']]);
|
|
second.emit('online');
|
|
expect(setFlags.mock.calls).toEqual([
|
|
['--max-old-space-size=0'],
|
|
['--max-old-space-size=3000'],
|
|
]);
|
|
});
|
|
|
|
it('skips the lease when V8 flags are frozen, since any flag write would abort', () => {
|
|
process.execArgv = ['--freeze-flags-after-init', '--max-old-space-size=3000'];
|
|
const worker = spawnWithOwnHeapLimit(fakeWorker);
|
|
worker.emit('online');
|
|
expect(setFlags).not.toHaveBeenCalled();
|
|
expect(worker.listenerCount('online')).toBe(0);
|
|
});
|
|
|
|
it('skips the lease when the flags it reads do not explain the main heap', () => {
|
|
// NODE_OPTIONS says 2000, but the main isolate runs with 3000 + 48.
|
|
process.execArgv = [];
|
|
process.env.NODE_OPTIONS = '--max-old-space-size=2000';
|
|
const worker = spawnWithOwnHeapLimit(fakeWorker);
|
|
worker.emit('online');
|
|
expect(setFlags).not.toHaveBeenCalled();
|
|
expect(worker.listenerCount('online')).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe('workerHeapCapEnforceable', () => {
|
|
it.each([
|
|
['no flags', [], '', 4144, true],
|
|
[
|
|
'frozen flags with no heap flag, which leave nothing to clear',
|
|
['--freeze-flags-after-init'],
|
|
'',
|
|
4144,
|
|
true,
|
|
],
|
|
[
|
|
'frozen flags with a heap flag',
|
|
['--freeze-flags-after-init', '--max-old-space-size=3000'],
|
|
'',
|
|
3048,
|
|
false,
|
|
],
|
|
[
|
|
'frozen flags with a NODE_OPTIONS heap flag',
|
|
['--freeze-flags-after-init'],
|
|
'--max-old-space-size=3000',
|
|
3048,
|
|
false,
|
|
],
|
|
[
|
|
'frozen, then unfrozen',
|
|
['--freeze-flags-after-init', '--no-freeze-flags-after-init', '--max-old-space-size=3000'],
|
|
'',
|
|
3048,
|
|
true,
|
|
],
|
|
['a heap flag the live limit confirms', ['--max-old-space-size=3000'], '', 3048, true],
|
|
['a heap flag the live limit contradicts', ['--max-old-space-size=3000'], '', 4144, false],
|
|
])('is %s -> %s', (_label, argv, nodeOptions, limitMb, expected) => {
|
|
expect(workerHeapCapEnforceable(argv, nodeOptions, limitMb * MIB)).toBe(expected);
|
|
});
|
|
});
|
|
|
|
describe('spawnWithInheritedHeap', () => {
|
|
let execArgv: string[];
|
|
let nodeOptions: string | undefined;
|
|
|
|
// Whether a worker already started under the cleared flags is process state,
|
|
// so each case loads a fresh module.
|
|
const freshModule = async () => {
|
|
vi.resetModules();
|
|
return import('../../src/core/ingestion/workers/worker-heap-limit.js');
|
|
};
|
|
|
|
beforeEach(() => {
|
|
setFlags.mockClear();
|
|
execArgv = process.execArgv;
|
|
nodeOptions = process.env.NODE_OPTIONS;
|
|
process.execArgv = ['--max-old-space-size=3000', '--max-semi-space-size=64'];
|
|
delete process.env.NODE_OPTIONS;
|
|
mainHeap.limitMb = 3000 + 3 * 64;
|
|
});
|
|
|
|
afterEach(() => {
|
|
process.execArgv = execArgv;
|
|
if (nodeOptions === undefined) delete process.env.NODE_OPTIONS;
|
|
else process.env.NODE_OPTIONS = nodeOptions;
|
|
});
|
|
|
|
it('spawns plainly under the inherited flags when no worker has used the cleared ones', async () => {
|
|
const { spawnWithInheritedHeap } = await freshModule();
|
|
const limits: unknown[] = [];
|
|
const worker = spawnWithInheritedHeap((resourceLimits) => {
|
|
limits.push(resourceLimits);
|
|
return fakeWorker();
|
|
});
|
|
worker.emit('online');
|
|
expect(limits).toEqual([undefined]);
|
|
expect(setFlags).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('takes the lease with the inherited limits once a parser worker has used it', async () => {
|
|
const { spawnWithInheritedHeap, spawnWithOwnHeapLimit } = await freshModule();
|
|
spawnWithOwnHeapLimit(fakeWorker).emit('online');
|
|
setFlags.mockClear();
|
|
|
|
const writesAtSpawn: string[][] = [];
|
|
const limits: unknown[] = [];
|
|
const worker = spawnWithInheritedHeap((resourceLimits) => {
|
|
limits.push(resourceLimits);
|
|
writesAtSpawn.push(setFlags.mock.calls.map(([flags]) => flags));
|
|
return fakeWorker();
|
|
});
|
|
worker.emit('online');
|
|
|
|
const cleared = ['--max-old-space-size=0', '--max-semi-space-size=0'];
|
|
expect(limits).toEqual([{ maxOldGenerationSizeMb: 3000, maxYoungGenerationSizeMb: 192 }]);
|
|
expect(writesAtSpawn).toEqual([cleared]);
|
|
expect(setFlags.mock.calls.map(([flags]) => flags)).toEqual([
|
|
...cleared,
|
|
'--max-old-space-size=3000',
|
|
'--max-semi-space-size=64',
|
|
]);
|
|
});
|
|
|
|
it('spawns plainly without heap flags, even after a parser worker started', async () => {
|
|
process.execArgv = [];
|
|
const { spawnWithInheritedHeap, spawnWithOwnHeapLimit } = await freshModule();
|
|
spawnWithOwnHeapLimit(fakeWorker).emit('online');
|
|
const limits: unknown[] = [];
|
|
spawnWithInheritedHeap((resourceLimits) => {
|
|
limits.push(resourceLimits);
|
|
return fakeWorker();
|
|
}).emit('online');
|
|
expect(limits).toEqual([undefined]);
|
|
expect(setFlags).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('percentageOldSpaceMb', () => {
|
|
it('applies the percentage to physical RAM, or to the cgroup limit', () => {
|
|
const total = 32_768 * MIB;
|
|
expect(percentageOldSpaceMb(['--max-old-space-size-percentage=25'], '', total, 0)).toBe(8192);
|
|
expect(percentageOldSpaceMb([], '--max-old-space-size-percentage=12.5', total, 0)).toBe(4096);
|
|
expect(
|
|
percentageOldSpaceMb(['--max-old-space-size-percentage=50'], '', total, 8192 * MIB),
|
|
).toBe(4096);
|
|
expect(percentageOldSpaceMb(['--max-old-space-size=3000'], '', total, 0)).toBeUndefined();
|
|
// Node takes a cgroup limit even above physical RAM, but not UINT64_MAX.
|
|
expect(
|
|
percentageOldSpaceMb(['--max-old-space-size-percentage=25'], '', total, 61_440 * MIB),
|
|
).toBe(15_360);
|
|
expect(percentageOldSpaceMb(['--max-old-space-size-percentage=25'], '', total, 2 ** 64)).toBe(
|
|
8192,
|
|
);
|
|
// Whole MB first, as Node does: 60% of 1.9 MiB is 60% of 1 MB, so 0.
|
|
expect(percentageOldSpaceMb(['--max-old-space-size-percentage=60'], '', 1.9 * MIB, 0)).toBe(0);
|
|
// Read by argument: the name inside an --eval source is not the flag.
|
|
expect(
|
|
percentageOldSpaceMb(['--eval', 'f("--max-old-space-size-percentage=50")'], '', total, 0),
|
|
).toBeUndefined();
|
|
});
|
|
});
|