GitNexus/gitnexus/test/unit/query-memory-guard.test.ts
glier 845c071add
fix(lbug): say when memory was already in use before the query the guard blames (#4071)
* fix(lbug): say when memory was already in use before the blamed query

The query memory guard said "while running a graph query" and listed only
the query labels, even when most of the memory had been allocated before
any of those queries started (for example by source scanning in the same
process). That sent investigations to the wrong place.

The breach now carries each running query's start memory and running
time. The message prints them per query, and when the oldest query
started with at least half of the breaching memory already in use, the
headline says that memory was allocated outside the listed queries.
Exit code, environment variables, budget and sampling are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(lbug): keep breach attribution in one unit and word it as fact

On macOS the breach value can be the physical footprint while each
query's start memory is RSS. The message subtracted one from the other,
so it could charge compressed pages that predate a query to that query.

The breach now carries which measurement passed the budget, and
`rssBytes` is renamed `memoryBytes` because it can hold a footprint.
The headline names the measurement. Per-query growth and the
pre-existing headline are computed only for an RSS breach; a footprint
breach lists each query's start RSS and running time and says that RSS
cannot show how much of the footprint predates the queries.

The pre-existing headline now uses the lowest start RSS over the running
queries, a floor for what was in use before each of them began, and
fires only when it is more than half of the breach value. It states that
fact and no longer guesses the cause. Running time is clamped at zero
if the clock steps back.

Exit code, environment variables, budget and sampling are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(lbug): update breach message consumers and keep rounded floors true

The previous commit changed the breach headline to "process memory (RSS)
reached" or "physical footprint reached", but the process-boundary
integration test and the runbook still used the old text. Both now use
the new forms. The runbook also explains the "not attributable to those
queries" headline.

That headline said "more than half of it" next to rounded numbers, so a
breach just above the threshold printed "8.0 GB or more" of "16.0 GB",
more than half. The phrase is gone, and the start floor is now rounded
down so that "or more" stays true.

The unit tests now assert the full breach payload, including the
measurement, for breaches found when a query begins or ends.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(lbug): report starting RSS without assigning allocation ownership

Process RSS can fall and rise during a query. Report what was measured at each query start and direct operators to investigate earlier and concurrent work. Exercise that sequence and verify the diagnostic at the pooled-read process boundary.

* fix(lbug): format signed RSS changes consistently

---------

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>
2026-11-25 05:47:04 +00:00

543 lines
19 KiB
TypeScript

/**
* #3696 — native-memory guard for read queries. Driven entirely through
* injected deps: no real timers, RSS, or process exit.
*/
import { describe, it, expect, vi } from 'vitest';
import {
createQueryMemoryGuard,
formatBreachMessage,
queryLabel,
parsePhysFootprintBytes,
resolveQueryRssBudgetBytes,
FOOTPRINT_INTERVAL_MS,
QUERY_MAX_RSS_ENV,
QUERY_MEMORY_LIMIT_EXIT_CODE,
QUERY_TRACE_ENV,
type QueryMemoryGuardDeps,
} from '../../src/core/lbug/query-memory-guard.js';
const MIB = 1024 * 1024;
const GIB = 1024 * MIB;
function harness(
env: Record<string, string> = {},
totalMem = 64 * GIB,
readFootprint?: () => Promise<number | null>,
) {
let rss = 500 * MIB;
let now = 1_000;
let tick: (() => void) | null = null;
const stop = vi.fn(() => {
tick = null;
});
const deps: QueryMemoryGuardDeps = {
readRss: () => rss,
...(readFootprint ? { readFootprint } : {}),
env: () => env,
totalMem: () => totalMem,
now: () => now,
writeStderr: vi.fn(),
onBreach: vi.fn(),
startSampler: vi.fn((t: () => void) => {
tick = t;
return stop;
}),
};
const guard = createQueryMemoryGuard(deps);
return {
guard,
deps,
stop,
setRss: (mb: number) => {
rss = mb * MIB;
},
advance: (ms: number) => {
now += ms;
},
tick: () => tick?.(),
samplerRunning: () => tick !== null,
};
}
describe('resolveQueryRssBudgetBytes', () => {
it('defaults to 25% of RAM', () => {
expect(resolveQueryRssBudgetBytes(undefined, 64 * GIB)).toBe(16 * GIB);
});
it('defaults to 8 GiB when 25% is smaller and the host has sufficient headroom', () => {
expect(resolveQueryRssBudgetBytes(undefined, 16 * GIB)).toBe(8 * GIB);
});
it('honours an explicit MiB value', () => {
expect(resolveQueryRssBudgetBytes('2048', 64 * GIB)).toBe(2 * GIB);
expect(resolveQueryRssBudgetBytes(' 1.5 ', 64 * GIB)).toBe(Math.floor(1.5 * MIB));
});
it('treats 0 as disabled', () => {
expect(resolveQueryRssBudgetBytes('0', 64 * GIB)).toBeNull();
});
it('falls back to the default for unparseable or negative values', () => {
for (const raw of ['', ' ', 'all', '10junk', '-5', 'NaN', 'Infinity']) {
expect(resolveQueryRssBudgetBytes(raw, 64 * GIB)).toBe(16 * GIB);
}
});
it('rejects overflowing and sub-byte budgets', () => {
for (const raw of ['1e308', '1e-20']) {
expect(resolveQueryRssBudgetBytes(raw, 64 * GIB)).toBe(16 * GIB);
}
});
it('leaves headroom on small hosts and constrained runtimes', () => {
expect(resolveQueryRssBudgetBytes(undefined, 8 * GIB)).toBe(6 * GIB);
expect(resolveQueryRssBudgetBytes(undefined, 2 * GIB)).toBe(1.5 * GIB);
});
});
describe('queryLabel', () => {
it('flattens whitespace and bounds length', () => {
expect(queryLabel('MATCH (n)\n WHERE n.id = $id\n RETURN n')).toBe(
'MATCH (n) WHERE n.id = $id RETURN n',
);
const long = queryLabel(`MATCH ${'x'.repeat(500)}`);
expect(long.length).toBe(201);
expect(long.endsWith('…')).toBe(true);
});
});
describe('createQueryMemoryGuard', () => {
it('checks the budget before starting even a short query', () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' });
h.setRss(1500);
h.guard.begin('RETURN 1');
expect(h.deps.onBreach).toHaveBeenCalledTimes(1);
expect(h.deps.onBreach).toHaveBeenCalledWith({
memoryBytes: 1500 * MIB,
measurement: 'rss',
budgetBytes: 1000 * MIB,
activeQueries: [{ label: 'RETURN 1', startBytes: 1500 * MIB, runningMs: 0 }],
});
});
it('checks memory growth when a query ends between sampler ticks', () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' });
const t = h.guard.begin('RETURN 1');
h.setRss(1500);
h.guard.end(t, 1);
expect(h.deps.onBreach).toHaveBeenCalledTimes(1);
expect(h.deps.onBreach).toHaveBeenCalledWith({
memoryBytes: 1500 * MIB,
measurement: 'rss',
budgetBytes: 1000 * MIB,
activeQueries: [{ label: 'RETURN 1', startBytes: 500 * MIB, runningMs: 0 }],
});
});
it('reports a breach with every running query once RSS passes the budget', () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' });
h.guard.begin('MATCH (caller)-[r]->(n) RETURN caller');
h.guard.begin('MATCH (s)-[r]->(p:Process) RETURN p');
expect(h.samplerRunning()).toBe(true);
h.setRss(900);
h.tick();
expect(h.deps.onBreach).not.toHaveBeenCalled();
h.setRss(1500);
h.tick();
expect(h.deps.onBreach).toHaveBeenCalledTimes(1);
expect(h.deps.onBreach).toHaveBeenCalledWith({
memoryBytes: 1500 * MIB,
measurement: 'rss',
budgetBytes: 1000 * MIB,
activeQueries: [
{ label: 'MATCH (caller)-[r]->(n) RETURN caller', startBytes: 500 * MIB, runningMs: 0 },
{ label: 'MATCH (s)-[r]->(p:Process) RETURN p', startBytes: 500 * MIB, runningMs: 0 },
],
});
// Only once, even if the exit is slow to take effect.
h.tick();
expect(h.deps.onBreach).toHaveBeenCalledTimes(1);
});
it('reports the starting RSS even when memory is freed and allocated again during the query', () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' });
// Memory allocated outside any query: the guard does not sample then.
h.setRss(900);
h.guard.begin('MATCH (n) RETURN n');
h.setRss(100);
h.tick();
h.advance(2_500);
h.setRss(1100);
h.tick();
h.tick();
expect(h.deps.onBreach).toHaveBeenCalledTimes(1);
expect(h.deps.onBreach).toHaveBeenCalledWith({
memoryBytes: 1100 * MIB,
measurement: 'rss',
budgetBytes: 1000 * MIB,
activeQueries: [{ label: 'MATCH (n) RETURN n', startBytes: 900 * MIB, runningMs: 2_500 }],
});
const message = formatBreachMessage(vi.mocked(h.deps.onBreach).mock.calls[0][0]);
expect(message).toContain('RSS was already 0.8 GB or more');
expect(message).toContain('+0.2 GB since start');
expect(message).not.toContain('not attributable');
expect(QUERY_MEMORY_LIMIT_EXIT_CODE).toBe(70);
});
it("keeps each running query's own start memory and running time", () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' });
h.guard.begin('A');
h.advance(1_500);
h.setRss(800);
h.guard.begin('B');
h.advance(700);
h.setRss(1100);
h.tick();
expect(h.deps.onBreach).toHaveBeenCalledWith({
memoryBytes: 1100 * MIB,
measurement: 'rss',
budgetBytes: 1000 * MIB,
activeQueries: [
{ label: 'A', startBytes: 500 * MIB, runningMs: 2_200 },
{ label: 'B', startBytes: 800 * MIB, runningMs: 700 },
],
});
const msg = formatBreachMessage(vi.mocked(h.deps.onBreach).mock.calls[0][0]);
expect(msg).toContain(' - A (RSS at start 0.5 GB, +0.6 GB since start, running 2.2 s)');
expect(msg).toContain(' - B (RSS at start 0.8 GB, +0.3 GB since start, running 0.7 s)');
});
it('never reports a negative running time when the clock steps back', () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' });
h.guard.begin('Q');
h.advance(-400);
h.setRss(1100);
h.tick();
expect(vi.mocked(h.deps.onBreach).mock.calls[0][0].activeQueries).toEqual([
{ label: 'Q', startBytes: 500 * MIB, runningMs: 0 },
]);
});
it('does not sample between queries', () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' });
const t = h.guard.begin('RETURN 1');
h.guard.end(t, 1);
expect(h.stop).toHaveBeenCalledTimes(1);
expect(h.samplerRunning()).toBe(false);
// RSS held by something else while no query runs is not this guard's call.
h.setRss(5000);
h.guard.sample();
expect(h.deps.onBreach).not.toHaveBeenCalled();
});
it('keeps sampling until the last concurrent query ends', () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' });
const a = h.guard.begin('A');
const b = h.guard.begin('B');
expect(h.deps.startSampler).toHaveBeenCalledTimes(1);
h.guard.end(a);
expect(h.samplerRunning()).toBe(true);
h.guard.end(b);
expect(h.samplerRunning()).toBe(false);
});
it('starts no sampler when disabled and not tracing', () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '0' });
const t = h.guard.begin('RETURN 1');
expect(h.deps.startSampler).not.toHaveBeenCalled();
h.setRss(100_000);
h.guard.sample();
h.guard.end(t);
expect(h.deps.onBreach).not.toHaveBeenCalled();
expect(h.deps.writeStderr).not.toHaveBeenCalled();
});
it('is on by default with no environment set', () => {
const h = harness({}, 16 * GIB);
h.guard.begin('RETURN 1');
h.setRss(8 * 1024);
h.tick();
expect(h.deps.onBreach).not.toHaveBeenCalled();
h.setRss(8 * 1024 + 1);
h.tick();
expect(h.deps.onBreach).toHaveBeenCalledTimes(1);
});
it('writes one trace line per query with start, peak and end RSS', () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '0', [QUERY_TRACE_ENV]: '1' });
const t = h.guard.begin('MATCH (n)\n RETURN n');
expect(h.samplerRunning()).toBe(true);
h.setRss(2000);
h.tick();
h.setRss(700);
h.advance(42);
h.guard.end(t, 7);
expect(h.deps.writeStderr).toHaveBeenCalledWith(
'[query-trace] ms=42 rows=7 memStartMB=500 memPeakMB=2000 rssEndMB=700 active=0 q="MATCH (n) RETURN n"\n',
);
});
it('ignores an unknown or already-ended token', () => {
const h = harness({ [QUERY_TRACE_ENV]: '1' });
const t = h.guard.begin('RETURN 1');
h.guard.end(t);
h.guard.end(t);
h.guard.end({});
expect(h.deps.writeStderr).toHaveBeenCalledTimes(1);
});
});
describe('createQueryMemoryGuard: physical footprint (macOS)', () => {
const flush = () => new Promise((r) => setImmediate(r));
it('never reads the footprint for a short query', async () => {
const readFootprint = vi.fn(async () => 50 * GIB);
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' }, 64 * GIB, readFootprint);
const t = h.guard.begin('RETURN 1');
h.advance(FOOTPRINT_INTERVAL_MS - 1);
h.tick();
h.guard.end(t);
await flush();
expect(readFootprint).not.toHaveBeenCalled();
expect(h.deps.onBreach).not.toHaveBeenCalled();
});
it('breaches on the footprint while RSS stays low (compressed pages)', async () => {
const readFootprint = vi.fn(async () => 3 * GIB);
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' }, 64 * GIB, readFootprint);
h.guard.begin('MATCH (a), (b) RETURN a, b');
h.setRss(300);
h.advance(FOOTPRINT_INTERVAL_MS);
h.tick();
expect(readFootprint).toHaveBeenCalledTimes(1);
await flush();
expect(h.deps.onBreach).toHaveBeenCalledWith({
memoryBytes: 3 * GIB,
measurement: 'footprint',
budgetBytes: 1000 * MIB,
activeQueries: [
{
label: 'MATCH (a), (b) RETURN a, b',
startBytes: 500 * MIB,
runningMs: FOOTPRINT_INTERVAL_MS,
},
],
});
});
it('names the footprint in the message and does not mix it with RSS', async () => {
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' }, 64 * GIB, async () => 3 * GIB);
h.guard.begin('Q');
h.setRss(300);
h.advance(FOOTPRINT_INTERVAL_MS);
h.tick();
await flush();
const msg = formatBreachMessage(vi.mocked(h.deps.onBreach).mock.calls[0][0]);
expect(msg).toContain('physical footprint reached 3.0 GB, over the 1.0 GB limit');
expect(msg).toContain(' - Q (RSS at start 0.5 GB, running 1.0 s)');
expect(msg).not.toContain('since start');
});
it('reads at most once per interval and never overlaps reads', async () => {
let release: (v: number) => void = () => {};
const readFootprint = vi.fn(
() => new Promise<number | null>((r) => (release = r as (v: number) => void)),
);
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' }, 64 * GIB, readFootprint);
h.guard.begin('Q');
h.advance(FOOTPRINT_INTERVAL_MS);
h.tick();
expect(readFootprint).toHaveBeenCalledTimes(1);
release(600 * MIB);
await flush();
// Interval: measured from the start of the previous read.
h.advance(FOOTPRINT_INTERVAL_MS - 1);
h.tick();
expect(readFootprint).toHaveBeenCalledTimes(1);
h.advance(1);
h.tick();
expect(readFootprint).toHaveBeenCalledTimes(2);
// Overlap: a read still in flight blocks the next one, however long it takes.
h.advance(5 * FOOTPRINT_INTERVAL_MS);
h.tick();
expect(readFootprint).toHaveBeenCalledTimes(2);
release(600 * MIB);
await flush();
h.tick();
expect(readFootprint).toHaveBeenCalledTimes(3);
});
it('ignores a footprint that resolves after the query ended', async () => {
let release: (v: number) => void = () => {};
const readFootprint = vi.fn(
() => new Promise<number | null>((r) => (release = r as (v: number) => void)),
);
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' }, 64 * GIB, readFootprint);
const t = h.guard.begin('Q');
h.advance(FOOTPRINT_INTERVAL_MS);
h.tick();
h.guard.end(t);
release(50 * GIB);
await flush();
expect(h.deps.onBreach).not.toHaveBeenCalled();
});
it('does not charge a stale footprint to a later query', async () => {
let release!: (bytes: number | null) => void;
const pending = new Promise<number | null>((resolve) => {
release = resolve;
});
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' }, 64 * GIB, () => pending);
const old = h.guard.begin('old');
h.advance(FOOTPRINT_INTERVAL_MS);
h.tick();
h.guard.end(old);
const next = h.guard.begin('next');
release(50 * GIB);
await flush();
expect(h.deps.onBreach).not.toHaveBeenCalled();
h.guard.end(next);
});
it('retains a footprint while a query present at sampling still runs', async () => {
let release!: (bytes: number | null) => void;
const pending = new Promise<number | null>((resolve) => {
release = resolve;
});
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' }, 64 * GIB, () => pending);
const first = h.guard.begin('first');
const second = h.guard.begin('second');
h.advance(FOOTPRINT_INTERVAL_MS);
h.tick();
h.guard.end(first);
release(50 * GIB);
await flush();
expect(h.deps.onBreach).toHaveBeenCalledTimes(1);
h.guard.end(second);
});
it('treats an unavailable footprint as no signal', async () => {
const readFootprint = vi.fn(async () => null);
const h = harness({ [QUERY_MAX_RSS_ENV]: '1000' }, 64 * GIB, readFootprint);
h.guard.begin('Q');
h.advance(FOOTPRINT_INTERVAL_MS);
h.tick();
await flush();
expect(h.deps.onBreach).not.toHaveBeenCalled();
});
});
describe('parsePhysFootprintBytes', () => {
it('reads the byte count from `footprint -f bytes` output', () => {
const out =
'node [123]: 64-bit Footprint: 2474344 B (16384 bytes per page)\n' +
' phys_footprint: 2474344 B\n phys_footprint_peak: 9000000 B\n';
expect(parsePhysFootprintBytes(out)).toBe(2474344);
});
it('returns null for unexpected output', () => {
expect(parsePhysFootprintBytes('')).toBeNull();
expect(parsePhysFootprintBytes('phys_footprint: 11 MB')).toBeNull();
});
});
describe('formatBreachMessage', () => {
const rssBreach = (memoryBytes: number, starts: number[]) =>
formatBreachMessage({
memoryBytes,
measurement: 'rss',
budgetBytes: 16 * GIB,
activeQueries: starts.map((startBytes, i) => ({
label: `Q${i}`,
startBytes,
runningMs: 1_000,
})),
});
it('names the limit, the running queries and how to change it', () => {
const msg = formatBreachMessage({
memoryBytes: 17 * GIB,
measurement: 'rss',
budgetBytes: 16 * GIB,
activeQueries: [{ label: 'MATCH (a) RETURN a', startBytes: 1 * GIB, runningMs: 3_000 }],
});
expect(msg).toContain('process memory (RSS) reached 17.0 GB, over the 16.0 GB limit');
expect(msg).toContain('while running a graph query');
expect(msg).toContain(
' - MATCH (a) RETURN a (RSS at start 1.0 GB, +16.0 GB since start, running 3.0 s)',
);
expect(msg).toContain('cannot cancel a running query');
expect(msg).toContain(`${QUERY_MAX_RSS_ENV}=<MiB>`);
expect(msg).toContain('#3696');
});
it('says when every query started with more than half of the memory in use', () => {
const msg = rssBreach(17 * GIB, [15 * GIB, 16 * GIB]);
expect(msg).toContain('RSS was already 15.0 GB or more when each query listed below started.');
expect(msg).not.toContain('while running a graph query');
expect(msg).toContain(' - Q0 (RSS at start 15.0 GB, +2.0 GB since start, running 1.0 s)');
expect(msg).toContain(' - Q1 (RSS at start 16.0 GB, +1.0 GB since start, running 1.0 s)');
expect(msg).toContain('cannot cancel a running query');
expect(msg).toContain(`${QUERY_MAX_RSS_ENV}=<MiB>`);
expect(msg).toContain('#3696');
});
it('reports the starting RSS in the headline only above half', () => {
expect(rssBreach(16 * GIB, [8 * GIB])).toContain('while running a graph query');
const above = rssBreach(16 * GIB, [8 * GIB + MIB]);
expect(above).not.toContain('while running a graph query');
// Rounded, the floor equals half of the reached value; the text must not
// claim more than the printed numbers show.
expect(above).toContain('reached 16.0 GB');
expect(above).toContain('RSS was already 8.0 GB or more');
expect(above).not.toContain('more than half');
});
it('rounds the start floor down so "or more" stays true', () => {
const msg = rssBreach(16.5 * GIB, [8.29 * GIB]);
expect(msg).toContain('RSS was already 8.2 GB or more');
});
it('prints a single minus sign when the reported RSS is below the starting value', () => {
const msg = rssBreach(17 * GIB, [17.5 * GIB]);
expect(msg).toContain('RSS at start 17.5 GB, -0.5 GB since start');
});
it('uses the lowest start memory, not the oldest query', () => {
// The oldest query started at a peak that was later released; the newer
// one started low and grew 13.5 GB.
const msg = rssBreach(16.5 * GIB, [12 * GIB, 3 * GIB]);
expect(msg).toContain('while running a graph query');
expect(msg).not.toContain('RSS was already');
expect(msg).toContain('process memory (RSS) reached 16.5 GB');
});
it('omits the starting RSS when no queries are listed', () => {
const msg = rssBreach(17 * GIB, []);
expect(msg).not.toMatch(/NaN|Infinity/);
expect(msg).toContain('process memory (RSS) reached 17.0 GB, over the 16.0 GB limit, while');
});
it('computes no growth or share across RSS and the footprint', () => {
for (const startBytes of [1 * GIB, 12 * GIB]) {
const msg = formatBreachMessage({
memoryBytes: 16.5 * GIB,
measurement: 'footprint',
budgetBytes: 16 * GIB,
activeQueries: [{ label: 'Q', startBytes, runningMs: 1_000 }],
});
expect(msg).toContain('physical footprint reached 16.5 GB, over the 16.0 GB limit');
expect(msg).toContain('excludes compressed and swapped pages');
expect(msg).toContain(` - Q (RSS at start ${startBytes / GIB}.0 GB, running 1.0 s)`);
expect(msg).not.toContain('since start');
expect(msg).not.toContain('RSS was already');
expect(msg).not.toContain('process memory');
}
});
});