GitNexus/gitnexus/test/unit/cli-int-option.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

76 lines
2.6 KiB
TypeScript

/**
* Unit tests for the shared CLI integer flag parser (`src/cli/int-option.ts`).
*/
import { describe, it, expect } from 'vitest';
import { IntegerOptionError, parseIntegerOption } from '../../src/cli/int-option.js';
describe('parseIntegerOption', () => {
it.each([
['1', 1, 1],
['42', 1, 42],
[' 7 ', 1, 7],
['200', 200, 200],
['4096', 200, 4096],
['0', 0, 0],
['5', 0, 5],
])('parses %j with minimum %i to %i', (value, minimum, expected) => {
expect(parseIntegerOption(value, '--flag', { minimum })).toBe(expected);
});
it.each(['abc', '1.5', '-5', '', ' ', '1e3', '0x10', '01'])(
'rejects %j with the positive-integer message when the minimum is 1',
(value) => {
expect(() => parseIntegerOption(value, '--workers', { minimum: 1 })).toThrow(
new IntegerOptionError('--workers', 1, '--workers must be a positive integer'),
);
},
);
it('rejects 0 with the positive-integer message when the minimum is 1', () => {
expect(() => parseIntegerOption('0', '--retries', { minimum: 1 })).toThrow(
'--retries must be a positive integer',
);
});
it.each(['abc', '1.5', '-5', '', '199', '0'])(
'rejects %j with a message naming the flag and a minimum of 200',
(value) => {
expect(() => parseIntegerOption(value, '--memory-budget', { minimum: 200 })).toThrow(
'--memory-budget must be an integer >= 200',
);
},
);
it('rejects -1 with a message naming the flag and a minimum of 0', () => {
expect(() => parseIntegerOption('-1', '--embeddings', { minimum: 0 })).toThrow(
'--embeddings must be an integer >= 0',
);
});
it('throws an IntegerOptionError carrying the flag and minimum', () => {
const thrown = (() => {
try {
parseIntegerOption('abc', '--memory-budget', { minimum: 200 });
return undefined;
} catch (error) {
return error;
}
})();
expect(thrown).toBeInstanceOf(IntegerOptionError);
expect(thrown).toMatchObject({ flag: '--memory-budget', minimum: 200 });
});
it('rejects a value above the safe-integer bound divided by the scale', () => {
const bound = Math.floor(Number.MAX_SAFE_INTEGER / 1000);
expect(parseIntegerOption(String(bound), '--timeout', { minimum: 1, scale: 1000 })).toBe(bound);
expect(() =>
parseIntegerOption(String(bound + 1), '--timeout', { minimum: 1, scale: 1000 }),
).toThrow('--timeout is too large');
});
it('rejects a value above the safe-integer bound without a scale', () => {
expect(() => parseIntegerOption('9007199254740992', '--workers', { minimum: 1 })).toThrow(
'--workers is too large',
);
});
});