GitNexus/gitnexus/test/unit/scenario-map/report-json.test.ts
Gergő Magyar bd9586e008
fix: recover duplicate candidates and expose test inventory gaps (#3743)
* fix: recover missed test scenarios

Run the full core test inventory and retrieve identical callback bodies
across setup contexts. Separate assertion evidence from context and
retain conservative input, path and runtime provenance checks.

Restore prepared test inputs and report missing runtime collection.
Add the audited recall corpus and inventory regressions.

* Address PR review feedback (#3743)

Correct counted nouns in the inventory report, document fully skipped modules, and include unhandled runner errors in the incomplete-collection warning.

* Address PR review feedback (#3743)

Force-stage explicit temporary fixtures despite inherited Git ignores, and isolate recorded-file collection-error accounting in the inventory tests.

* fix(review): simplify selection and guard mixed artifacts

* feat(test): detect fixture consolidation opportunities

Capture source inputs used by integration tests and compare fixture clones,
executed blocks, and assertion subjects and values. Report partial overlaps
with the unique checks and fixture spans that consolidation must preserve.
Keep cross-language structural suggestions separate from observed equality.

Use pinned jscpd with direct pair verification when longer representatives
hide partial clones. Retain capture gaps and native/worker limitations.

Validate with 1,245 detector regressions, 28 pipeline pair controls, and 12
manually labeled comparisons. Scan 30,698 core cases and find 3,111 opportunity
groups; exclude the capture's 103 failed and 89 skipped cases.

* Fix scenario-map review findings (#3743)

Resolve assertion aliases by lexical binding and normalize duplicate static object keys. Capture fixture files through checked descriptors with bounded reads and guaranteed cleanup.

* fix: address test duplicate audit false signals

* refactor(test): reuse assertion binding analysis

Reuse lexical bindings within each evidence extraction while retaining
assertion-specific offsets and expansion limits. Deduplicate fixture
coverage endpoints numerically without string conversion.

Preserve complete assertion evidence across 29,286 static instances and
weighted coverage across 10,000 generated interval cases.

* Fix scenario-map review findings (#3743)

Bind consolidation evidence to the assertion call accepted by the check
extractor, so unsupported same-line calls cannot supply incorrect subjects
or expectations. Keep source provenance private and serialized checks intact.

Exercise omitted plugins alongside instrumented Vitest runs.

* fix: retain input-shaped scenario controls (#3743)

Compare assertion subject structure separately from exact input-bearing
assertion keys, so changing literal inputs retains table-row and boundary
classification. Preserve selectors, callee identity and regex values.

Keep the control expectations unchanged. Add regressions for literal
inputs, queried subjects and nested regex arguments; bump the fingerprint
engine version so reclassified findings resurface.

* test: give scenario cases unique titles

Include the parameterized case index so repeated input expressions and truncated audit paths cannot collide in the CI execution inventory.

* fix: scope assertion subjects to their bindings

Prevent same-named declarations in different files or scopes from
becoming exact assertion matches. Preserve same-binding consolidation
and advance the fingerprint engine to version 5.

* fix: raise full-suite planning heap budget

The 30,953-case replay aborts at the default 4 GiB heap. Give only
the Plan step 8 GiB and document the same local invocation.

The identical four coverage slices complete in 4m34s at 8.2 GiB
peak RSS, retaining all 116,409 candidate pairs.

* fix: stream full-suite scenario reports

The full inventory produces a 663 MiB report, exceeding V8's
single-string limit. Write records incrementally and stream only
required fields when reading baselines and publishing issue updates.

Replay preserves all 116,398 pairs from 30,953 collected cases.
The report remains partial when the trace run fails.

* fix: preserve test lifecycles during capture

Forced test repeats changed cache and file state. Capture ordinary runs,
retain runnable siblings during tracing, and keep retry-bearing files
inconclusive. Preserve failure details and mark failed captures partial.

Use the original JSON serializer so test mocks cannot break fixture reads.

* fix: limit trace capture to candidates

Keep sibling tests in both passes for suite state, while recording only candidate task IDs. This prevents unrelated timing checks and large corpus tests from failing under tracing.

* ci: budget full-suite trace collection

* fix: address scenario-map feedback (#3743)

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-10-30 21:06:08 +00:00

124 lines
5.3 KiB
TypeScript

/** Full-suite reports exceed V8's string limit; each record must survive streamed I/O. */
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { compareWithBaseline } from '../../../tools/scenario-map/report/baseline.js';
import { readReportFields, writeReportJson } from '../../../tools/scenario-map/report/json.js';
import { buildReport } from '../../../tools/scenario-map/report/report.js';
import { reportInput } from './report-fixtures.js';
const directories: string[] = [];
function output(): string {
const directory = mkdtempSync(path.join(os.tmpdir(), 'scenario-report-json-'));
directories.push(directory);
return path.join(directory, 'report.json');
}
afterEach(() => {
vi.restoreAllMocks();
for (const directory of directories.splice(0))
rmSync(directory, { recursive: true, force: true });
});
describe('report JSON', () => {
it('preserves every field and record without serializing a whole collection', async () => {
const report = buildReport(reportInput());
const pair = report.fingerprint.pairs[0];
report.fingerprint.pairs = Array.from({ length: 100 }, (_, i) => ({
...pair,
a: `test-${i}`,
details: ['escaped \"quote\", \\slash, \nnewline and unicode 🧪'],
}));
report.fingerprint.kept = report.fingerprint.pairs.map((entry) => ({
...entry,
keep: [{ test: entry.a, reason: 'intentional control' }],
}));
report.fingerprint.pairs[0].details = Array(1_000).fill('nested record detail');
const file = output();
const stringify = JSON.stringify;
// Model the V8 cap at a small scale, including a collection nested inside one record.
const limit = 16_384;
expect(stringify(report.fingerprint.pairs).length).toBeGreaterThan(limit);
expect(stringify(report.fingerprint.kept).length).toBeGreaterThan(limit);
expect(stringify(report.fingerprint.pairs[0]).length).toBeGreaterThan(limit);
const capped = vi.spyOn(JSON, 'stringify').mockImplementation((value, replacer, space) => {
const text = stringify(value, replacer, space);
if (text !== undefined && text.length > limit) throw new RangeError('Invalid string length');
return text;
});
await writeReportJson(file, report);
capped.mockRestore();
expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual(report);
expect(readdirSync(path.dirname(file))).toEqual(['report.json']);
});
it('leaves the prior report intact and removes the temporary file on serialization failure', async () => {
const report = buildReport(reportInput());
const file = output();
writeFileSync(file, '{"previous":true}');
vi.spyOn(JSON, 'stringify').mockImplementation(() => {
throw new Error('cannot serialize');
});
await expect(writeReportJson(file, report)).rejects.toThrow('cannot serialize');
expect(readFileSync(file, 'utf8')).toBe('{"previous":true}');
expect(readdirSync(path.dirname(file))).toEqual(['report.json']);
});
it('propagates filesystem errors', async () => {
const file = output();
await expect(writeReportJson(path.dirname(file), buildReport(reportInput()))).rejects.toThrow();
expect(readdirSync(path.dirname(file))).toEqual([]);
});
it.each(['streamed', 'legacy'] as const)(
'reads a %s baseline without retaining findings',
async (format) => {
const report = buildReport(reportInput());
const file = output();
if (format === 'streamed') await writeReportJson(file, report);
else writeFileSync(file, JSON.stringify(report, null, 2));
const baseline = await readReportFields(file, ['schemaVersion', 'run', 'continuity']);
expect(baseline).toEqual({
schemaVersion: report.schemaVersion,
run: report.run,
continuity: report.continuity,
});
expect(compareWithBaseline(report.continuity, baseline)).toEqual(
compareWithBaseline(report.continuity, report),
);
expect(await readReportFields(file, ['run', 'completeness'])).toEqual({
run: report.run,
completeness: report.completeness,
});
},
);
it('preserves UTF-8 and escapes across input chunks while skipping large unselected fields', async () => {
const file = output();
const run = { id: '🧪\n"\\é'.repeat(30_000) };
writeFileSync(file, JSON.stringify({ ignored: Array(100).fill(run), run, completeness: null }));
expect(await readReportFields(file, ['run', 'completeness'])).toEqual({
run,
completeness: null,
});
});
it.each([
['empty', ''],
['whitespace', ' \n\t'],
['truncated selected field', '{"run":{"id":"1"}'],
['truncated ignored field', '{"run":{"id":"1"},"ignored":[1,'],
['invalid ignored field', '{"run":{"id":"1"},"ignored":!}'],
['trailing garbage', '{"run":{"id":"1"}} invalid'],
['second document', '{"run":{"id":"1"}} {}'],
])('rejects %s instead of trusting metadata parsed before the error', async (_name, source) => {
const file = output();
writeFileSync(file, source);
await expect(readReportFields(file, ['run'])).rejects.toThrow();
});
it('propagates a missing file so merge can mark the baseline unreadable', async () => {
await expect(readReportFields(output(), ['run'])).rejects.toThrow(/ENOENT/);
});
});