GitNexus/gitnexus/test/unit/stream-graph-emit-force-ordering.test.ts
Gergő Magyar 0261982d9a
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (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): make --memory-budget set the real heap and report rebuild reasons once (#3386)
* feat(analyze): --memory-budget flag with heap-limit override and worker-pool degradation (#3137)

Adds an explicit `--memory-budget <mb>` CLI flag that overrides the
RAM/cgroup auto-sized main-thread heap ceiling for the parse phase:

- CLI validation (integer >= 200 MB) before bar.start(), matching the
  --workers pattern
- Threaded CLI → runFullAnalysis → PipelineOptions → parse-impl as
  memoryBudgetBytes
- parse-impl resolves the heap limit as budget ?? v8.heap_size_limit, so
  both the preflight projection warning and the #2649 mid-loop abort
  probe honor the budget
- Graceful degradation: when the projected heap need exceeds the budget
  at the computed pool size, the pool shrinks (never below 1, never
  above the operator's --workers) before sub-batch math and pool
  construction, so all downstream consumers see the degraded size

Omitting the flag keeps the auto-sizer path byte-identical.

Refs #3137

* feat(analyze): collapse rebuild-gate log into one summary + persist needsFullRebuild verdict (#3137)

The nine meta-mismatch rebuild gates (pdg mode, content retention,
schema fingerprint, graph-write collapse, analysis features, Spring
vendor prefixes, runner identity, FTS CJK mode, embedding dims) each
logged individually and set force:true independently. An upgrade that
trips several at once printed a scattered wall of near-identical
warnings.

- Gates now collect into rebuildReasons[]; a single summary block
  prints them (inline for one, numbered for many) and sets force once.
  Per-gate Tip text is preserved verbatim inside the entries.
- The verdict persists to meta (needsFullRebuild: {reasons, recordedAt})
  BEFORE the rebuild starts. If the rebuild is interrupted, the next
  run announces the recorded reasons up front instead of quietly
  attempting an incremental write on a half-rebuilt index — the gates
  may not all re-fire against a wiped DB.
- The verdict is cleared on the next successful completion (the final
  meta does not carry the field forward).

Semantics unchanged: every gate was already evaluated (none
early-returns), force is idempotent, and a rebuild happens iff at
least one reason fired.

Refs #3137

* refactor(cli): share one integer flag parser across analyze, watch, and wiki

Replace the duplicated Number.isInteger checks for --workers, --embeddings,
the positive env-backed analyze flags, the watch interval flags, and wiki's
--timeout/--retries with parseIntegerOption (per-flag minimum, optional
scale for the safe-integer bound). User-facing messages are unchanged.

* fix(analyze): make --memory-budget set the real V8 heap through the respawn

The budget now drives ensureHeap's existing respawn instead of a parse-phase
override, so the #2649 preflight, mid-loop abort, remedy text, and GC pacing
all see one heap limit. The respawn sizes old space plus three semi-spaces to
equal the budget, the child resolves as already at the budget (no second
respawn), and GITNEXUS_HEAP_LIMIT_SOURCE drives budget-aware OOM advice.
Budget validation moves to the preAction hook so analyze and watch reject a
bad value before any respawn. Removes the pool-shrink block and the
memoryBudgetBytes plumbing through PipelineOptions and run-analyze.

* docs(analyze): describe --memory-budget accurately and translate its help

The help text claimed graceful worker-pool degradation, which no longer
exists; it now says the flag sets the main-thread V8 heap and that parse
workers keep their own caps. Wires the option through the help i18n map
with en and zh-CN strings, and documents it in both READMEs and the
out-of-memory troubleshooting section.

* feat(analyze): add a pure rebuild-reason collector

One collector per run holds keyed rebuild reasons, merges by key, flattens
reasons stored by an interrupted rebuild into one recovery entry, validates
stored reasons on read, and formats the single up-front summary plus one
follow-up line for reasons added after the pipeline.

* fix(analyze): route every forced rebuild through one reason collector

Every path that forces a full rebuild (the nine meta gates, --force,
--skills, --no-parse-cache, --drop-embeddings, --repair-fts retention,
Spring Actuator, AsyncAPI, shared-store graph gaps, dirty-flag recovery,
the post-pipeline capability gate, and the #2409 escalation) now adds a
keyed reason to one collector. The rebuild decision is applied from the
collector at fixed checkpoints, one summary prints right before the
pipeline, and late reasons print one follow-up line. The escalation stays
non-forcing. runFullAnalysis returns the collected keys, which replaces the
runner-identity source-regex test with a behavior test. Removes the separate
needsFullRebuild field and its announcement, and stops folding --skills and
--no-parse-cache into --force.

* fix(analyze): persist rebuild reasons on the existing crash marker

Every incrementalInProgress writer (the full-rebuild stamp before the wipe,
the incremental pre-write, saveIncrementalDirtyState including the #2409
escalation, and buildFtsDirtyStamp) now carries the collected reasons into
the active slot's metaDir, so an interrupted rebuild explains itself on the
next run through one merged recovery entry. A successful run still clears
the marker and its reasons; the FTS-park recovery clears them without
forcing.

* test(analyze): cover every rebuild-reason key through runFullAnalysis

Add a coverage table that the typechecker keeps complete: every
RebuildReasonKey maps to a test file that drives it through
runFullAnalysis and asserts the returned key. Adds the missing
graph-write-collapse and drop-embeddings drivers, asserts the key in the
existing pdg-mode, spring-vendor-prefixes, cjk-segmentation, and
embedding-dims tests, and removes plan-local IDs from test names and
comments.

* fix(review): apply review findings

- A --max-old-space-size pin equal to --memory-budget no longer counts as
  the exact budget heap (V8 adds the young generation on top); only the
  budget-respawned child skips the respawn, so the limit really equals the
  budget.
- Snapshot the analyze env before ensureHeap and restore
  GITNEXUS_HEAP_LIMIT_SOURCE, so a kept process does not leak its heap
  source into a later programmatic analyzeCommand call.
- --skills and --no-parse-cache keep the forced storage requirements they
  had before force stopped being folded from them.
- Merge the duplicated follow-up announcement into one helper and fix a
  stale --drop-embeddings comment.
- The rebuild-reason coverage table no longer greps driver files for the
  key string; add tests for a programmatic invalid budget and the
  multi-cause interrupted-rebuild text.

* fix(review): don't announce the escalated write as a full rebuild

The #2409 escalation is a non-forcing reason, but its follow-up line used
the 'Full rebuild also required' lead. A follow-up that carries only
non-forcing reasons now leads with 'Write plan changed'.

* docs(analyze): document GITNEXUS_HEAP_LIMIT_SOURCE in the env table

CONTRIBUTING requires every new GITNEXUS_* variable to have a row; this one
is internal (set by analyze itself) and exists so OOM advice points at
--memory-budget.

* fix(review): address GitNexus review threads on #3386

- heapPressureRemedy measures pressure against the real auto-sized cap
  (heapCapMbFor) instead of a flat 0.75 x RAM, and no longer tells a
  GITNEXUS_MEMORY=off run with no pin to drop a pin that does not exist.
- toStored() persists the interrupted rebuild's reasons first, as documented.
- ensureHeap's doc names which paths leave GITNEXUS_HEAP_LIMIT_SOURCE unset.
- The heap-respawn suite restores the caller's GITNEXUS_MEMORY.
- The non-forcing follow-up test rejects any 'full rebuild' wording.

* fix(review): require both budget flags and check key coverage at runtime

- A budget-respawned child is recognized only when the inherited heap-source
  marker comes with both the budget's old-space and semi-space flags; the
  marker alone is an inherited env var, not proof. The old-space parser is
  generalized to any V8 size flag instead of copying its regex.
- REBUILD_REASON_KEYS is exported and RebuildReasonKey derives from it, so the
  coverage table is checked at runtime (CI does not type-check test files).

* fix(review): don't claim a full rebuild in a non-forcing summary

formatSummary and formatFollowUp now share one leadFor helper, so a block
of only non-forcing reasons reads 'Write plan changed' in both.

---------

Co-authored-by: ChunxueLi <mecoloud@users.noreply.gitee.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-09-26 18:14:36 +01:00

277 lines
10 KiB
TypeScript

/**
* Streamed structural emit must be resolved AFTER the guards that force a full
* rebuild (#2680 / PR #2793).
*
* `resolveStreamGraphEmit` gates on `options.force`, which several freshness
* guards rebind long after function entry — see the comment at the
* `resolveStreamGraphEmit` call in `run-analyze.ts` for the full list.
* Resolving at entry froze it `false` for every rebuild they trigger, so the
* pipeline took the in-memory emit path exactly when the #2649 memory relief
* matters most — and a schema bump makes EVERY existing index take that path on
* its next `analyze`.
*
* The seam: mock `runPipelineFromRepo` so it records the `PipelineOptions` the
* orchestrator actually built and then rejects. That asserts the real wiring
* (`streamGraphEmit` + `graphEmitCsvDir` as handed to the pipeline) rather than
* re-testing the pure resolver, which `stream-graph-emit-config.test.ts`
* already covers. Everything after the pipeline call is out of scope, so the
* mock's rejection is the intended end of the run.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import fsp from 'node:fs/promises';
import path from 'node:path';
import { getStoragePaths, saveMeta } from '../../src/storage/repo-manager.js';
import type { RepoMeta } from '../../src/storage/repo-meta.js';
import { RebuildReasonCollector, type RebuildReasonKey } from '../../src/core/rebuild-reasons.js';
import { createTempDir } from '../helpers/test-db.js';
type PipelineModule = typeof import('../../src/core/ingestion/pipeline.js');
type CapturedPipelineOptions = NonNullable<Parameters<PipelineModule['runPipelineFromRepo']>[2]>;
/** Sentinel: the pipeline was reached, and the run ends there by design. */
const PIPELINE_REACHED = 'stream-graph-emit-ordering: pipeline reached';
const captured = vi.hoisted(() => ({ options: [] as unknown[] }));
vi.mock('../../src/core/ingestion/pipeline.js', async (importOriginal) => {
const actual = await importOriginal<PipelineModule>();
return {
...actual,
runPipelineFromRepo: (
_repoPath: string,
_onProgress: unknown,
options: unknown,
): Promise<never> => {
captured.options.push(options);
return Promise.reject(new Error(PIPELINE_REACHED));
},
};
});
afterEach(() => {
captured.options.length = 0;
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
describe('streamGraphEmit is resolved after the force-mutating freshness guards', () => {
it('arms streaming for the rebuild a schema-fingerprint mismatch forces', async () => {
// Pin the escape hatch ON so the assertion cannot be moved by ambient env.
// Before the fix this changed nothing: `force` was still unset at the entry
// read, and the `force !== true` short-circuit precedes the env lookup.
vi.stubEnv('GITNEXUS_STREAM_GRAPH_EMIT', '1');
const tmpRepo = await createTempDir('gitnexus-stream-order-');
const repoPath = tmpRepo.dbPath;
try {
const { metaPath } = getStoragePaths(repoPath);
const metaDir = path.dirname(metaPath);
await fsp.mkdir(metaDir, { recursive: true });
// An index built from a DIFFERENT schema — what an already-indexed repo
// looks like on its first analyze after the DDL changes.
await saveMeta(metaDir, {
repoPath,
lastCommit: '',
indexedAt: new Date(0).toISOString(),
schemaFingerprint: 'a0b1c2d3e4f5',
fileHashes: { 'src/a.ts': 'stale-hash' },
});
const { runFullAnalysis } = await import('../../src/core/run-analyze.js');
const logs: string[] = [];
// NOTE: no `force` from the caller — the rebuild is entirely guard-driven,
// which is the whole point.
await expect(
runFullAnalysis(
repoPath,
{ skipAgentsMd: true },
{ onProgress: () => {}, onLog: (m: string) => logs.push(m) },
),
).rejects.toThrow(PIPELINE_REACHED);
// The schema-version guard is what supplied `force` on this run.
expect(logs.filter((m) => m.includes('index schema changed'))).toHaveLength(1);
expect(captured.options).toHaveLength(1);
const pipelineOptions = captured.options[0] as CapturedPipelineOptions;
// The regression: pre-fix this was `false` / `undefined`, and the run
// built the whole relationship set in memory.
expect(pipelineOptions).toMatchObject({ streamGraphEmit: true });
// The paired CSV dir must be armed with it — the two are resolved from one
// value precisely so they cannot disagree.
expect(typeof pipelineOptions.graphEmitCsvDir).toBe('string');
} finally {
await tmpRepo.cleanup();
}
}, 120_000);
});
/** What the collector held, and printed, at the pre-pipeline summary. */
interface SummaryCall {
keys: RebuildReasonKey[];
summary: string | undefined;
}
/**
* Record every pre-pipeline summary the real collector formats. The pipeline
* mock ends the run before `runFullAnalysis` can return its keys, so the
* summary checkpoint is the seam: what was collected, and the exact text it
* printed, without re-typing any reason.
*/
const recordSummaries = (): SummaryCall[] => {
const calls: SummaryCall[] = [];
const formatSummary = RebuildReasonCollector.prototype.formatSummary;
vi.spyOn(RebuildReasonCollector.prototype, 'formatSummary').mockImplementation(function (
this: RebuildReasonCollector,
) {
const keys = this.keys();
const summary = formatSummary.call(this);
calls.push({ keys, summary });
return summary;
});
return calls;
};
/** Run to the (mocked) pipeline and return the log lines. */
const runToPipeline = async (
repoPath: string,
options: {
useParseCache?: boolean;
skills?: boolean;
repairFts?: boolean;
dropEmbeddings?: boolean;
},
): Promise<string[]> => {
const { runFullAnalysis } = await import('../../src/core/run-analyze.js');
const logs: string[] = [];
await expect(
runFullAnalysis(
repoPath,
{ skipAgentsMd: true, ...options },
{ onProgress: () => {}, onLog: (m: string) => logs.push(m) },
),
).rejects.toThrow(PIPELINE_REACHED);
return logs;
};
const writeMeta = async (repoPath: string, meta: Omit<RepoMeta, 'repoPath'>): Promise<void> => {
const metaDir = path.dirname(getStoragePaths(repoPath).metaPath);
await fsp.mkdir(metaDir, { recursive: true });
await saveMeta(metaDir, { repoPath, ...meta });
};
describe('pre-pipeline rebuild reasons (#3137)', () => {
it.each([
{ flag: 'skills', options: { skills: true }, key: 'skills' },
{ flag: 'useParseCache: false', options: { useParseCache: false }, key: 'parse-cache-bypass' },
] as const)(
'$flag alone contributes only its own reason, once',
async ({ options, key }) => {
vi.stubEnv('GITNEXUS_STREAM_GRAPH_EMIT', '1');
const summaries = recordSummaries();
const tmpRepo = await createTempDir('gitnexus-rebuild-reason-flag-');
try {
const logs = await runToPipeline(tmpRepo.dbPath, options);
expect(summaries.map(({ keys }) => keys)).toEqual([[key]]);
const [{ summary }] = summaries;
expect(logs.filter((m) => m === summary)).toHaveLength(1);
// The flag no longer masquerades as --force: it forces the rebuild itself.
expect(captured.options[0]).toMatchObject({ streamGraphEmit: true });
} finally {
await tmpRepo.cleanup();
}
},
120_000,
);
it('--repair-fts after a retention change yields one content-retention entry', async () => {
const summaries = recordSummaries();
const tmpRepo = await createTempDir('gitnexus-rebuild-reason-retention-');
try {
// Built under a different retention than this run's default (`full`):
// both the --repair-fts conversion and the retention gate fire.
await writeMeta(tmpRepo.dbPath, {
lastCommit: '',
indexedAt: new Date(0).toISOString(),
schemaFingerprint: 'a0b1c2d3e4f5',
contentRetention: 'none',
});
await runToPipeline(tmpRepo.dbPath, { repairFts: true });
expect(summaries).toHaveLength(1);
expect(summaries[0].keys.filter((k) => k === 'content-retention')).toHaveLength(1);
// The repair was converted into the rebuild instead of returning early.
expect(captured.options).toHaveLength(1);
} finally {
await tmpRepo.cleanup();
}
}, 120_000);
it('--drop-embeddings over a stored embedding checkpoint contributes the drop-embeddings reason', async () => {
const summaries = recordSummaries();
const tmpRepo = await createTempDir('gitnexus-rebuild-reason-drop-embeddings-');
try {
// The reason is collected only where a checkpoint is being discarded.
await writeMeta(tmpRepo.dbPath, {
lastCommit: '',
indexedAt: new Date(0).toISOString(),
embeddingCheckpoint: {
at: new Date(0).toISOString(),
nodesProcessed: 0,
totalNodes: 1,
chunksProcessed: 0,
model: 'test-model',
dimensions: 384,
provider: 'local',
pendingNodeIds: [],
},
});
const logs = await runToPipeline(tmpRepo.dbPath, { dropEmbeddings: true });
expect(summaries).toHaveLength(1);
expect(summaries[0].keys).toContain('drop-embeddings');
expect(logs).toContain('Discarding the embedding checkpoint (--drop-embeddings).');
} finally {
await tmpRepo.cleanup();
}
}, 120_000);
it('a first-build claim retry names no schema or runner-identity change', async () => {
const summaries = recordSummaries();
const tmpRepo = await createTempDir('gitnexus-rebuild-reason-claim-');
try {
// Exactly what the slot claim writes before a first build that then crashed.
await writeMeta(tmpRepo.dbPath, {
storagePath: path.dirname(getStoragePaths(tmpRepo.dbPath).metaPath),
lastCommit: '',
indexedAt: new Date(0).toISOString(),
});
await runToPipeline(tmpRepo.dbPath, {});
expect(summaries).toEqual([{ keys: [], summary: undefined }]);
} finally {
await tmpRepo.cleanup();
}
}, 120_000);
it('a first build of a non-git folder rebuilds structurally with no summary', async () => {
vi.stubEnv('GITNEXUS_STREAM_GRAPH_EMIT', '1');
const summaries = recordSummaries();
const tmpRepo = await createTempDir('gitnexus-rebuild-reason-nongit-');
try {
await runToPipeline(tmpRepo.dbPath, {});
expect(summaries).toEqual([{ keys: [], summary: undefined }]);
// Structural, not collected: the pipeline sees no forced rebuild.
expect(captured.options[0]).toMatchObject({ streamGraphEmit: false });
} finally {
await tmpRepo.cleanup();
}
}, 120_000);
});