mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-10-03 02:21:44 +00:00
* fix: link object literal methods to exported bindings
* fix(ingestion): bridge object-literal value receivers in scope-resolution (PR #1718 review)
Addresses adversarial production-readiness review on PR #1718 / issue #1358:
- F1 (caller resolution) — setting `ownerId` on object-literal method symbols
alone is not sufficient; the scope-resolution receiver-bound resolver only
consults class-like or type-annotated bindings, so lowercase value receivers
(`export const fooService = {...}; fooService.getUser(...)`) never reach the
owner-indexed lookup. Adds a Case 5 value-receiver bridge in
receiver-bound-calls.ts that resolves the receiver name as a Const/Variable
binding, translates its def to the canonical graph node id, and emits the
CALLS edge via the owner-indexed method registry.
- F2 (boundary guard) — rewrites findObjectLiteralBindingInfo as an explicit
two-phase AST walk: Phase A tracks object-literal depth (returns null for
nested literals and pre-declarator function/class boundaries — IIFE
patterns); Phase B walks the declarator's ancestors and rejects function,
class, and block-statement containers (if / for / while / try / catch /
switch / etc.) before reaching program/export_statement. Prevents false
HAS_METHOD edges for locally-scoped or block-scoped object literals.
- F4 — drops the dead `ownerName` field from ObjectLiteralBindingInfo.
Constraint: TS/JS are scope-resolution migrated per RFC #909; the legacy
Call-Resolution DAG (call-processor.ts) is intentionally left untouched.
Tests:
- test/integration/ast-helpers-object-literal-binding.test.ts (13 cases) —
pins helper semantics: happy paths, function/arrow/class-ctor boundaries,
nested literals, block scope (if / for-of / try), IIFE, assignment
expressions without declarator.
- test/integration/object-literal-owner-resolution.test.ts (9 cases) —
drives the full pipeline against an on-disk fixture: sequential CALLS edge
emission (issue #1358 proof), worker-mode parity, negative local binding,
and nested-literal attribution boundary.
Full sweep: 2958/2958 integration + 6056/6056 unit tests pass.
* refactor(ingestion): address code-review findings on object-literal owner resolution
Multi-agent code review on the prior commit surfaced 7 actionable findings,
all walked through and applied here. None change observable behavior for
issue #1358's fix; all harden correctness, predicate stability, and test
signal.
- #1 (P1 / 3-reviewer corroboration): Case 5 in receiver-bound-calls.ts no
longer hand-builds graph.addRelationship + a dedup key. New
tryEmitEdgeWithExplicitTargetId in edges.ts takes a pre-resolved target
id (the canonical Method nodeId from the parser) and reuses every
invariant of tryEmitEdge: dedup-key format, collapse-flag honoring,
caller-id resolution, rel-id shape, mapReferenceKindToEdgeType for
read/write ACCESSES. This also lands the adversarial reviewer's "F2"
follow-up (hardcoded type: 'CALLS' for non-call sites) for free.
- #2 (P2 cross-reviewer): findValueBindingInScope's predicate inverted
from denylist ("not class-like and not callable") to explicit allowlist
matching reconcileOwnership's registration set:
Const | Variable | Property | Static. Extracted as isOwnableValueLabel
so future NodeLabel additions require an explicit opt-in.
- #6 (P2): walkScopeChain<T>() extracted; both findClassBindingInScope
and findValueBindingInScope now route through it. Local scope.bindings
are exhausted BEFORE lookupBindingsAt (imported/augmented) at every
scope level — preserves JavaScript lexical scoping where a local const
shadows an imported binding of the same name. Behavior was already
correct in findClassBindingInScope but was implicit; now it is the
walker's explicit, documented contract.
- #7 (P2): scope-walker duplication closed. findClassBindingInScope and
findValueBindingInScope reduce to thin wrappers over walkScopeChain
with their respective predicate. findClassBindingInScope keeps its
qualifiedNames + dotted-name fallback tail.
- #3 (P2): parse-worker.ts hoists `const ownerId = enclosingClassId ??
objectLiteralOwnerInfo?.ownerId` once before the symbol push, dropping
the duplicated coalesce + `as string` cast. Matches the cast-free
pattern at parsing-processor.ts:793. HAS_METHOD emit site reuses the
same hoisted local.
- #4 (P2): object-literal-owner-resolution.test.ts Test A's CALLS-edge
assertion no longer matches by name alone. .toEqual now pins the
canonical target id (Method:src/service.ts:getUser#1 via generateId),
confidence (0.85), and reason ('import-resolved'). A regression that
emits the edge at confidence=0, with the wrong reason, or against a
phantom Method node now fails the test.
- #5 (P2): worker-parity test adds a CI tripwire — when CI=1 and
dist/parse-worker.js is missing, throw at module top with a clear
message. Locally, skipIf(!hasDistWorker) keeps the fast-iteration
experience; CI cannot pass with U3 (worker-path ownerId) unverified.
Verification: tsc --noEmit clean. Targeted regression sweep on
ast-helpers-object-literal-binding (13), object-literal-owner-resolution
(9), has-method (60), cross-file-binding (40) — 122/122 pass. Full unit
sweep: 6056/6056. Integration suite: 1 pre-existing Windows-flake in
worker-pool.test.ts (passes 28/28 in isolation) unrelated to this diff.
* refactor(scope-resolution): align Const label emission with legacy DAG (PR #1718 review F1)
Eliminates the architectural fragility surfaced by PR #1718's adversarial review
Finding 1. Previously, normalizeNodeLabel('const') returned 'Variable' while
the legacy DAG parse phase emits 'Const' graph nodes (via @definition.const
capture for lexical_declaration). PR #1718's Case 5 value-receiver bridge
resolved correctly only because resolveDefGraphId happened to fall back to
simpleKey after the qualified-key miss — accidental correctness.
After this change, scope-resolution defs for `const x = ...` declarations
report def.type === 'Const', matching the graph node label. resolveDefGraphId's
qualified-key path now hits on the first try; the simple-key fallback is no
longer load-bearing for value receivers and can be tightened in future without
silently breaking Case 5.
Audit completeness verification:
- Grep `\bVariable\b` across src/core/ingestion/scope-resolution/ surfaced two
consumer sites that already accept both labels: reconcile-ownership.ts:101+168
(`def.type === 'Variable' || def.type === 'Const' || ...`) and
walkers.ts:207 isOwnableValueLabel (`Const | Variable | Property | Static`).
No language hook in src/core/ingestion/languages/ branches on
`def.type === 'Variable'` for what's actually a const declaration.
- Sentinel stress test (the full unit + integration suite run with the
renamed label in place): 6137/6137 unit tests pass; 2967/2967 integration
tests pass. One pre-existing Windows-only flake on worker-pool.test.ts when
run alongside the full integration suite (passes 28/28 in isolation,
unrelated to scope-extractor — same flake observed before this diff).
The variable mapping (`'variable' → 'Variable'`) is preserved for `var`
declarations, matching the legacy DAG's `@definition.variable` capture for
variable_declaration. The split now mirrors the parse-phase capture
distinction exactly.
Per plan docs/plans/2026-05-21-002-feat-pr1718-followups-class-instance-and-label-normalization-plan.md
U4 + U5. T1 (class-instance singleton resolution from issue #1358's second
sub-case) is deferred to a standalone pre-plan investigation, not shipped
here.
* test(ingestion): add regression coverage for issue #1358 singleton sub-cases
Closes the remaining sub-cases of issue #1358 surfaced by PR #1718's
adversarial review (Finding 4, NOTED): the class-instance singleton
(`export const fooService = new FooService();`) and the factory-pattern
singleton (`export const fooService = makeFooService();`).
Pre-plan investigation (per docs/plans/2026-05-21-002 § "Pre-Plan
Investigation Task (T1)") confirmed Outcome A for both patterns — they
already resolve end-to-end through scope-resolution's
`@type-binding.constructor` capture (languages/typescript/query.ts:489-511)
+ `propagateImportedReturnTypes` chain-follow
(scope-resolution/passes/imported-return-types.ts:114) + receiver-bound
Case 4 simple typeBinding lookup (receiver-bound-calls.ts:625). The
mechanism was wired correctly before this session; the regression-net
wasn't.
This test pins the behavior:
- Pattern 1: `caller → FooService.getUser` CALLS edge with
confidence 0.85 and reason 'import-resolved'
- Pattern 2: same edge shape via factory chain-follow (the
`@type-binding.alias` capture for `const u = find()` style)
Both assertions use exact `.toEqual([{...}])` shape pinning so a future
regression that targets a phantom Method node, emits at lower confidence,
or drops the cross-file import-resolved reason fails loudly.
Verification: 5/5 pass, 127/127 in targeted regression sweep including
object-literal-owner-resolution.test.ts, ast-helpers-object-literal-
binding.test.ts, has-method.test.ts, and cross-file-binding.test.ts.
No production code change. The class methods get a class-qualified node id
(`Method:src/service.ts:FooService.getUser#1`) distinguishing them from
same-name methods on other classes — distinct from the bare-name node id
shape PR #1718's object-literal case uses.
* test(resolvers): add class-instance + factory-pattern singleton coverage for TS/JS (issue #1358)
Closes the remaining sub-cases of issue #1358 surfaced by PR #1718's
adversarial review (Finding 4). PR #1718 fixed object-literal-shorthand
singletons (`export const fooService = { getUser() {} }`); this commit adds
parallel coverage for the two other singleton shapes that resolve through
the existing scope-resolution chain:
// Pattern 1 — class-instance singleton
export class FooService { getUser(id) { ... } }
export const fooService = new FooService();
// Pattern 2 — factory-pattern singleton
export class FooService { getUser(id) { ... } }
export function makeFooService() { return new FooService(); }
export const fooService = makeFooService();
Pre-plan investigation (per local plan docs/plans/2026-05-21-002 § "Pre-Plan
Investigation Task (T1)") confirmed Outcome A — both patterns already
resolve end-to-end through:
- `@type-binding.constructor` capture (languages/{typescript,javascript}/
query.ts) seeds `fooService → FooService` at parse time
- `propagateImportedReturnTypes` (scope-resolution/passes/
imported-return-types.ts:114) mirrors the typeBinding cross-file
- Receiver-bound Case 4 simple typeBinding lookup
(scope-resolution/passes/receiver-bound-calls.ts:625) MRO-walks
FooService and emits the CALLS edge to getUser
Tests added per language × pattern (5 each, 10 total):
- node existence (Class, Method, Function, Const, plus Function for the
factory pattern's `makeFooService`)
- HAS_METHOD edge from class to method (class-instance variant)
- CALLS edge from caller to `getUser` with `targetFilePath: 'src/service.{ts,js}'`,
`reason: 'import-resolved'`, `confidence: 0.85` — exact `.toEqual([{...}])`
shape pinning so a regression that emits at lower confidence or drops the
cross-file reason fails loudly
Fixtures placed under the existing `test/fixtures/lang-resolution/` convention.
Tests appended to `test/integration/resolvers/{typescript,javascript}.test.ts`,
matching the in-file pattern of every other resolver scenario.
Also supersedes and removes the standalone
`test/integration/class-instance-and-factory-singleton-resolution.test.ts`
introduced earlier in this PR session (`0df91b77`) — the proper home for
language-resolver scenarios is the per-language resolver test file alongside
similar fixtures (`javascript-self-this-resolution`, `javascript-cross-file`,
`typescript-tsconfig-paths`, etc.). One canonical location for the scenario,
not two.
Verification: 10/10 new singleton tests pass; 297/297 full TS+JS resolver
suite pass (no regression in any existing resolver test).
* test(resolvers): gate TS/JS singleton tests behind scope-resolution parity (CI run 26223603426)
The class-instance and factory-pattern singleton CALLS-edge resolution
tests added in c8e573bc rely on scope-resolution-only mechanisms
(`@type-binding.constructor` capture + `propagateImportedReturnTypes`
mirror + receiver-bound Case 4). The `scope-parity / typescript parity`
and `scope-parity / javascript parity` CI jobs run with
`REGISTRY_PRIMARY_TYPESCRIPT=0` / `REGISTRY_PRIMARY_JAVASCRIPT=0` and
exercise the legacy DAG path, which has no cross-file constructor-derived
typeBinding propagation. Verified by job 77202610819 (TS parity) and
77202610869 (JS parity) failing with:
× resolves caller.fooService.getUser() to FooService.getUser via constructor-inferred typeBinding
× resolves caller.fooService.getUser() through the factory chain to FooService.getUser
Note: my local Windows shell-prefix env-var invocation did not propagate
the flag into vitest workers correctly (the cpp parity gate's 47-skipped
behavior masked the issue when I ran an ad-hoc comparison), so the
empirical "both modes pass" finding I posted earlier was wrong. CI is the
source of truth.
Changes:
- test/integration/resolvers/helpers.ts: add `typescript` and `javascript`
entries to `LEGACY_RESOLVER_PARITY_EXPECTED_FAILURES` for the 2 CALLS-edge
resolution tests in each language. Node-existence and HAS_METHOD
assertions are NOT excluded — those pass under legacy DAG (parser-level
emission is intact).
- test/integration/resolvers/typescript.test.ts: drop the `it` import from
vitest; replace with `const it = createResolverParityIt('typescript');`
shadow (matches the c/cpp/csharp/go pattern at the top of those files).
- test/integration/resolvers/javascript.test.ts: same shadow with
`createResolverParityIt('javascript')`.
Verification:
- Default mode (registry-primary): 297/297 TS+JS resolver tests pass.
- Legacy DAG mode: the 4 listed singleton CALLS-edge tests will skip; all
other singleton assertions (node existence + HAS_METHOD edge) continue
to run and pass under both modes.
---------
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
189 lines
7.1 KiB
TypeScript
189 lines
7.1 KiB
TypeScript
/**
|
|
* processParsing — worker-pool error handling contract.
|
|
*
|
|
* U20 design pivot (PR #1693): there is NO sequential-parser fallback
|
|
* when the worker pool fails. The pool's resilience layers (respawn
|
|
* budget, circuit breaker, quarantine, slot-attribution, cumulative
|
|
* timeout) are the sole contract for handling worker failures. When
|
|
* those exhaust, `processParsing` propagates the error to the caller
|
|
* — `runChunkedParseAndResolve` and the analyze entry point above it.
|
|
*
|
|
* This file replaces the previous sequential-fallback tests (which
|
|
* asserted that processParsing caught WorkerPoolDispatchError and
|
|
* called processParsingSequential on the remaining files). The new
|
|
* contract is "errors propagate, no rescue."
|
|
*
|
|
* Why removing the fallback was the right call:
|
|
* - The fallback ran the SAME tree-sitter parser the worker just
|
|
* crashed on, but on the main thread. A native crash (SIGSEGV
|
|
* from a tree-sitter binding) in the worker would re-trigger the
|
|
* same SIGSEGV on the main thread, killing the whole analyze
|
|
* instead of just the worker.
|
|
* - It hid pool failures behind a degraded-but-completing analyze
|
|
* run, making them harder to detect and diagnose.
|
|
* - U2's chunk-cache write suppression keeps cross-run retry
|
|
* working: a quarantined file's chunk stays uncached, so the
|
|
* next analyze with a fresh pool gets another chance.
|
|
*/
|
|
import { describe, expect, it, vi } from 'vitest';
|
|
import { createASTCache } from '../../src/core/ingestion/ast-cache.js';
|
|
import { processParsing } from '../../src/core/ingestion/parsing-processor.js';
|
|
import type { WorkerPool } from '../../src/core/ingestion/workers/worker-pool.js';
|
|
import { WorkerPoolDispatchError } from '../../src/core/ingestion/workers/worker-pool.js';
|
|
import { createKnowledgeGraph } from '../../src/core/graph/graph.js';
|
|
import { createSymbolTable } from '../../src/core/ingestion/model/symbol-table.js';
|
|
|
|
describe('processParsing — worker-pool error propagation (U20)', () => {
|
|
it('propagates a raw worker-pool throw to the caller without rescuing', async () => {
|
|
const graph = createKnowledgeGraph();
|
|
const workerPool: WorkerPool = {
|
|
size: 1,
|
|
dispatch: vi.fn(async () => {
|
|
throw new Error('replacement worker failed');
|
|
}),
|
|
terminate: vi.fn(async () => undefined),
|
|
};
|
|
|
|
await expect(
|
|
processParsing(
|
|
graph,
|
|
[{ path: 'src/a.ts', content: 'export function a() { return 1; }\n' }],
|
|
createSymbolTable(),
|
|
createASTCache(),
|
|
createASTCache(),
|
|
() => {},
|
|
workerPool,
|
|
),
|
|
).rejects.toThrow('replacement worker failed');
|
|
|
|
// No sequential fallback ran, so the graph stays empty.
|
|
expect(
|
|
graph.nodes.some((node) => node.label === 'Function' && node.properties.name === 'a'),
|
|
).toBe(false);
|
|
});
|
|
|
|
it('propagates WorkerPoolDispatchError with quarantinedPaths intact', async () => {
|
|
const graph = createKnowledgeGraph();
|
|
const workerPool: WorkerPool = {
|
|
size: 1,
|
|
dispatch: vi.fn(async () => {
|
|
throw new WorkerPoolDispatchError(
|
|
'Worker pool circuit breaker tripped: 2 consecutive failures on slot 0',
|
|
['src/poison.ts'],
|
|
);
|
|
}),
|
|
terminate: vi.fn(async () => undefined),
|
|
};
|
|
|
|
const rejection = processParsing(
|
|
graph,
|
|
[
|
|
{ path: 'src/poison.ts', content: 'export function poison() { return 0; }\n' },
|
|
{ path: 'src/a.ts', content: 'export function a() { return 1; }\n' },
|
|
],
|
|
createSymbolTable(),
|
|
createASTCache(),
|
|
createASTCache(),
|
|
() => {},
|
|
workerPool,
|
|
);
|
|
|
|
await expect(rejection).rejects.toBeInstanceOf(WorkerPoolDispatchError);
|
|
const err = await rejection.catch((e) => e as WorkerPoolDispatchError);
|
|
expect(err.quarantinedPaths).toEqual(['src/poison.ts']);
|
|
|
|
// No sequential fallback ran for either file. The caller (analyze
|
|
// entry point) is responsible for surfacing this as a hard
|
|
// failure.
|
|
expect(
|
|
graph.nodes.some((node) => node.label === 'Function' && node.properties.name === 'a'),
|
|
).toBe(false);
|
|
expect(
|
|
graph.nodes.some((node) => node.label === 'Function' && node.properties.name === 'poison'),
|
|
).toBe(false);
|
|
});
|
|
|
|
it('worker-path returns successfully when the pool reports a quarantine snapshot without throwing', async () => {
|
|
// Quarantine is a normal session-scoped signal: the pool filters
|
|
// quarantined files out of dispatch, returns the survivors'
|
|
// results, and reports the cumulative set via getQuarantinedPaths.
|
|
// processParsing's worker-path completes successfully on this
|
|
// partial-coverage signal — the quarantined file is missing from
|
|
// the graph, but no error is thrown. The chunk-loop caller uses
|
|
// the quarantine snapshot to decide whether to write the chunk
|
|
// cache (U2 in parse-impl.ts).
|
|
const graph = createKnowledgeGraph();
|
|
const workerPool: WorkerPool = {
|
|
size: 1,
|
|
dispatch: vi.fn(async () => []),
|
|
terminate: vi.fn(async () => undefined),
|
|
getQuarantinedPaths: () => ['src/poison.ts'],
|
|
};
|
|
|
|
const progressDetails: string[] = [];
|
|
const result = await processParsing(
|
|
graph,
|
|
[
|
|
{ path: 'src/poison.ts', content: 'export function poison() { return 0; }\n' },
|
|
{ path: 'src/a.ts', content: 'export function a() { return 1; }\n' },
|
|
],
|
|
createSymbolTable(),
|
|
createASTCache(),
|
|
createASTCache(),
|
|
(_current, _total, detail) => {
|
|
progressDetails.push(detail);
|
|
},
|
|
workerPool,
|
|
);
|
|
|
|
// Worker path returned successfully (not null — null was the
|
|
// pre-U20 sentinel for "ran sequential fallback"). The progress
|
|
// log surfaces the quarantine count for operator visibility.
|
|
expect(result).not.toBeNull();
|
|
expect(progressDetails).toContain('1 worker-quarantined file(s) skipped');
|
|
});
|
|
});
|
|
|
|
describe('TypeScript object literal method exports', () => {
|
|
it('links exported object literal shorthand methods back to the exported object', async () => {
|
|
const graph = createKnowledgeGraph();
|
|
|
|
await processParsing(
|
|
graph,
|
|
[
|
|
{
|
|
path: 'src/foo.ts',
|
|
content: `export const fooService = {
|
|
async getUser(id: string) {
|
|
return findUser(id);
|
|
},
|
|
saveUser(user: User) {
|
|
return persist(user);
|
|
},
|
|
};
|
|
`,
|
|
},
|
|
],
|
|
createSymbolTable(),
|
|
createASTCache(),
|
|
createASTCache(),
|
|
);
|
|
|
|
const service = graph.nodes.find(
|
|
(node) => node.label === 'Const' && node.properties.name === 'fooService',
|
|
);
|
|
expect(service, 'exported object literal should be captured as a Const').toBeDefined();
|
|
|
|
const methodNames = new Set(
|
|
graph.nodes.filter((node) => node.label === 'Method').map((node) => node.properties.name),
|
|
);
|
|
expect(methodNames).toEqual(new Set(['getUser', 'saveUser']));
|
|
|
|
const linkedMethodNames = graph.relationships
|
|
.filter((rel) => rel.type === 'HAS_METHOD' && rel.sourceId === service!.id)
|
|
.map((rel) => graph.getNode(rel.targetId)?.properties.name)
|
|
.sort();
|
|
|
|
expect(linkedMethodNames).toEqual(['getUser', 'saveUser']);
|
|
});
|
|
});
|