mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* perf(python): remove quadratic import-claim reconciliation * test(python): count identity and import-claim reads separately The repeated-import scaling case counted `claim` getter reads under the name `identityReads`, so a regression that re-read every import's identity per claim could still pass. Instrument both properties: claim reads must equal the import count (the old nested membership scan read n(n+1)/2), and identity reads must stay within 2n. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(python): walk lexical bindings iteratively; find annotations by span Syntax depth is input-controlled. The recursive lexical walk (visit, bind, pattern) overflowed V8's stack near depth 2,000, e.g. a generated 2,000-term `a + b + ...` chain or 2,000 nested list literals, dropping the whole file's scope extraction. All three walks now use an explicit stack. Steps that the recursive walk interleaved between child visits (parameter and comprehension-target binding) run as deferred tasks, so events, environments and range marks keep their pre-order. isPythonTypeAnnotation climbed `.parent` from every bare read and attribute. tree-sitter keeps no parent pointers, so each `.parent` re-walks from the root: n(n+1)/2 parent reads and O(n^3) time for an n-term chain (10 s at 1,000 terms). It now collects `type` node byte spans once per tree with a query, memoized per tree like javaTypeIdentityMemo, and binary-searches them. Expressions never contain a block, so span containment equals the old "type ancestor below the nearest block" walk. Captures are byte-identical to the merge base over 340 repository .py fixtures plus synthetic edge cases. The only difference is a 1,000-level annotation the base walk could not process. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(python): check annotations with one hash lookup per node The span binary search cost log2(spans) iterations per read, so capture work grew n log n: exact V8 block-execution growth on the value-reference corpus rose to 1.0012 per doubling (gate: <= 1.0). Collect identifier and attribute nodes under each outermost `type` node once per tree with the native descendantsOfType, and answer each check with a Set lookup. Nested `type` nodes are skipped, so deeply nested generics stay linear. Capture block growth is back to 0.9990, the same as before the deep-syntax change. Resolution block counts match the pre-change head exactly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(python): cover deep pattern and tuple-target walks The explicit-stack `pattern` and `bind` walks had no deep regression case, and the nested-literal case only checked that nothing threw. The deep cases now assert the module claims of a 2,000-level class pattern (`q`), a 2,000-level nested tuple target (`a`) and the nested-literal assignment (`x`); all three throw RangeError on the merge base's recursive walk. The value-references benchmark identity now hashes attribute-references.ts/.js, which sits on the measured capture path, and the local-import scoping doc points at import-claims.ts for the conflicting-import policy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(python): classify attribute accesses with one query pass per tree pythonAttributeAccessKinds read .parent three times per attribute to find its target context, and node-tree-sitter re-walks from the root for each read, so member and call chains cost O(n^2). Annotation membership and access kinds now come from one query pass per tree: the existing (type) pattern plus nine context patterns that capture the node in target position and descend through tuple, list and parenthesized wrappers. Both exports become one map lookup by node.id, and the file reads no .parent. Every context pattern ends at its capture. A two-step pattern such as (assignment left: (_) @write right: (_)) keeps its match open across the target, and tree-sitter buffers every capture inside it: quadratic, and past 65,535 buffered captures the 16-bit capture ids wrap and the process segfaults. The annotation-only target gets its own capture and wins over the plain assignment capture in JS instead. Also drops the unreachable tree === undefined fallback and its cast. Captures are identical in emission order to the previous head on the repository fixtures, the CPython 3.13 stdlib and 23,464 generated and mutated files. Parent-bound rows cover member reads, member chains and call chains; a 70,000-argument assignment target pins the buffering hazard. The parent-read wrapper is shared by both bound tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ingestion): walk named trees and binding targets without recursion Syntax depth is input-controlled. Two shared helpers recursed once per level and overflowed V8's stack on deep code in every language that uses them: - walkNamedTree (about 30 capture call sites across Go, Objective-C, Rust, Swift, PHP, Ruby, C#, Python and Dart) threw near depth 8,000. It now keeps an explicit stack of (node, next child index) frames and makes the same namedChildCount / namedChild(i) calls, in the same order, as the recursion. That order matters: namedChild(i) steps inside a visible anonymous node such as Python's `not in` while namedChildren does not, and the exact navigation-count tests for Dart and Ruby pin the calls. - bindingIdentifier threw on 8,000 nested tuple targets. It searched each binding field and then every named child, and a field is usually also a named child, so a subtree that failed was searched again: O(2^depth) on a left-nested chain without an identifier (4,194,303 visits at depth 20, 83 now). It now uses an explicit stack whose entries each make one lazy read in the recursion's order, and a seen set skips subtrees that already failed. Results are unchanged. A node-level differential over the fixtures of 17 grammars (as written, truncated and corrupted) and the CPython stdlib found 0 differences in visit sequence, navigation calls or returned node. Scope-capture fingerprints pass for all 17 languages, and no node makes more navigation calls than before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(python): keep scope-query matches and flow lookups linear on deep chains - Anchor the eight scope-query rules that stayed open across a nested child (member call, member read, binary and boolean operands, call arguments) at the node they end on. expandPythonScopeMatches() rebuilds the original capture lists in the same order. Open matches on a chain drop from one per level to at most 11; matches() on a 4,000-link call chain goes from 1,100 ms to 9 ms. - Run the scope query and the attribute context query with maxStartDepth 0xffff. tree-sitter keeps a match's start depth in 16 bits, and past depth 65,535 a wrapped match stays open: 90,000 `or` operands took 35.7 s in the context query, now 0.3 s. - Memoize nearestFunctionOwner, nearestLexicalRegion, terminalIdentifier and hasMultipleIdentifierLeaves per file in synthesizeCallableFlowCaptures, and read a call's text once for all of its arguments. Nested walrus at 600 levels: 12.2 s to 37 ms; assignment chains at 600 targets: 2.6 s to 49 ms; call-only chains at 2,000 calls: 10.2 s to 52 ms. Captures are identical in emission order on the repo (340 files), stdlib (598) and generated (23,464) corpora, and the 15 languages that share the flow helper show no differences. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(parse): read node text from the source string after a chunked parse node-tree-sitter rebuilds `node.text` of a callback-parsed tree (sources over DIRECT_PARSE_LIMIT_CHARS) by calling the input callback again on every read: a fresh copy of the node's source each time. Point the tree at the source string, as node-tree-sitter already does for a string parse, so a read is one substring. Long Python chains become linear in time and memory (a 16,000-target assignment chain: 3.6 s and 1.7 GB before, 1.5 s and 184 MB after), and a call with 40,000 arguments or an expression with 40,000 `or` operands no longer exhausts a 4 GB heap. Peak RSS of analyze on the stdlib and on gitnexus/src is unchanged (within 0.5%), with identical graphs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(python): keep the scope-query match helper out of the grammar gate The grammar-literal gate calls every `*ScopeQuery` export of a language's query.ts with no arguments to compile its query. matchPythonScopeQuery(root) matched that name and threw on the missing root. Rename it to pythonScopeQueryMatches and note the constraint at its definition. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
224 lines
7.8 KiB
TypeScript
224 lines
7.8 KiB
TypeScript
/**
|
|
* A call argument that wraps a function literal must not cost the literal's
|
|
* whole body every time a call is nested in it (#3912 review).
|
|
*
|
|
* Dart's `argument`, Kotlin's `value_argument`, C#'s `argument` and PHP's
|
|
* `argument` wrap the literal, so `operandSyntax` does not stop at it as a
|
|
* function node. It searched the literal's body for a terminal identifier and
|
|
* then for a second identifier leaf, and `emitCallFacts` dropped the result
|
|
* because such an argument is no designator. Each call nested k levels deep
|
|
* paid for the k levels below it: O(depth^2) over a nest. The terminal
|
|
* identifier is now memoized per file, and a dropped argument returns before
|
|
* the second-leaf search. Capture output is unchanged (the scope-capture
|
|
* fingerprints pin every language).
|
|
*
|
|
* The test hook counts the subtree nodes the operand search enters. Each
|
|
* added nesting level must add the same number, at any depth.
|
|
*/
|
|
import { describe, expect, it } from 'vitest';
|
|
import type { CaptureMatch } from 'gitnexus-shared';
|
|
import {
|
|
getCallableFlowCaptureStats,
|
|
resetCallableFlowCaptureStats,
|
|
} from '../../../src/core/ingestion/utils/callable-flow-captures.js';
|
|
import { emitDartScopeCaptures } from '../../../src/core/ingestion/languages/dart/captures.js';
|
|
import { emitKotlinScopeCaptures } from '../../../src/core/ingestion/languages/kotlin/index.js';
|
|
import { emitCsharpScopeCaptures } from '../../../src/core/ingestion/languages/csharp/index.js';
|
|
import { emitPhpScopeCaptures } from '../../../src/core/ingestion/languages/php/index.js';
|
|
import { emitPythonScopeCaptures } from '../../../src/core/ingestion/languages/python/index.js';
|
|
import { emitJsScopeCaptures } from '../../../src/core/ingestion/languages/javascript/index.js';
|
|
import {
|
|
isLanguageAvailable,
|
|
loadLanguage,
|
|
loadParser,
|
|
} from '../../../src/core/tree-sitter/parser-loader.js';
|
|
import { SupportedLanguages } from '../../../src/config/supported-languages.js';
|
|
|
|
// Optional grammar cases skip where their parser cannot load.
|
|
let dartAvailable = isLanguageAvailable(SupportedLanguages.Dart);
|
|
if (dartAvailable) {
|
|
try {
|
|
await loadParser();
|
|
await loadLanguage(SupportedLanguages.Dart);
|
|
} catch {
|
|
dartAvailable = false;
|
|
}
|
|
}
|
|
|
|
let kotlinAvailable = isLanguageAvailable(SupportedLanguages.Kotlin);
|
|
if (kotlinAvailable) {
|
|
try {
|
|
await loadParser();
|
|
await loadLanguage(SupportedLanguages.Kotlin);
|
|
} catch {
|
|
kotlinAvailable = false;
|
|
}
|
|
}
|
|
|
|
type Emit = (source: string, filePath: string) => readonly CaptureMatch[];
|
|
|
|
/** `depth` literals passed as call arguments, each nested in the previous one. */
|
|
interface Nest {
|
|
readonly emit: Emit;
|
|
readonly file: string;
|
|
readonly open: (j: number) => string;
|
|
readonly close: string;
|
|
readonly wrap: (body: string) => string;
|
|
}
|
|
|
|
const NESTS: Record<string, Nest> = {
|
|
dart: {
|
|
emit: emitDartScopeCaptures,
|
|
file: 'lib/nest.dart',
|
|
open: (j) => ` items.forEach((x${j}) { cs.save(x${j});\n`,
|
|
close: ' });\n',
|
|
wrap: (body) => `void f(Address cs, List<int> items) {\n${body}}\n`,
|
|
},
|
|
kotlin: {
|
|
emit: emitKotlinScopeCaptures,
|
|
file: 'Nest.kt',
|
|
open: (j) => ` run({ x${j}: Int -> save(x${j})\n`,
|
|
close: ' })\n',
|
|
wrap: (body) => `fun f(cs: Int) {\n${body}}\n`,
|
|
},
|
|
csharp: {
|
|
emit: emitCsharpScopeCaptures,
|
|
file: 'Nest.cs',
|
|
open: (j) => ` Run((x${j}) => { Save(x${j});\n`,
|
|
close: ' });\n',
|
|
wrap: (body) => `class C { void F(int cs) {\n${body}} }\n`,
|
|
},
|
|
php: {
|
|
emit: emitPhpScopeCaptures,
|
|
file: 'nest.php',
|
|
open: (j) => ` run(function ($x${j}) { save($x${j});\n`,
|
|
close: ' });\n',
|
|
wrap: (body) => `<?php\nfunction f($cs) {\n${body}}\n`,
|
|
},
|
|
};
|
|
|
|
function operandNodeVisits(nest: Nest, depth: number): number {
|
|
let body = '';
|
|
for (let j = 0; j < depth; j++) body += nest.open(j);
|
|
for (let j = 0; j < depth; j++) body += nest.close;
|
|
resetCallableFlowCaptureStats(true);
|
|
try {
|
|
nest.emit(nest.wrap(body), nest.file);
|
|
return getCallableFlowCaptureStats().operandNodeVisits;
|
|
} finally {
|
|
resetCallableFlowCaptureStats();
|
|
}
|
|
}
|
|
|
|
function expectLinear(nest: Nest, perLevel: number, fixed: number): void {
|
|
for (const depth of [8, 16, 64]) {
|
|
expect(operandNodeVisits(nest, depth)).toBe(perLevel * depth + fixed);
|
|
}
|
|
}
|
|
|
|
describe('a call argument wrapping a function literal is not searched again per nested call', () => {
|
|
it.skipIf(!dartAvailable)('Dart', () => expectLinear(NESTS.dart, 14, 1));
|
|
it.skipIf(!kotlinAvailable)('Kotlin', () => expectLinear(NESTS.kotlin, 12, 0));
|
|
it('C#', () => expectLinear(NESTS.csharp, 12, 1));
|
|
it('PHP', () => expectLinear(NESTS.php, 14, 1));
|
|
});
|
|
|
|
function pythonOperandNodeVisits(source: string): number {
|
|
resetCallableFlowCaptureStats(true);
|
|
try {
|
|
emitPythonScopeCaptures(source, 'nest.py');
|
|
return getCallableFlowCaptureStats().operandNodeVisits;
|
|
} finally {
|
|
resetCallableFlowCaptureStats();
|
|
}
|
|
}
|
|
|
|
// A call whose callee is a call, and an assignment whose value is an
|
|
// assignment, hold the whole nest below them. The callee and the assigned
|
|
// value were searched without the per-file memo, and the second-leaf search
|
|
// had none, so level k paid for the k levels under it: 2 * depth^2 - 1 visits
|
|
// for `a()()...()` (32,767 at depth 128, now 510).
|
|
describe('a nest of calls or assignments is not searched again per level', () => {
|
|
const depths = [8, 16, 64];
|
|
|
|
it.each([
|
|
{
|
|
nest: 'a call of a call',
|
|
source: (depth: number) => `a${'()'.repeat(depth)}\n`,
|
|
perLevel: 4,
|
|
fixed: -2,
|
|
},
|
|
{
|
|
nest: 'an assignment chain',
|
|
source: (depth: number) => `${'a = '.repeat(depth)}b\n`,
|
|
perLevel: 3,
|
|
fixed: 1,
|
|
},
|
|
{
|
|
nest: 'nested named expressions',
|
|
source: (depth: number) => `${'(a := '.repeat(depth)}f()${')'.repeat(depth)}\n`,
|
|
perLevel: 4,
|
|
fixed: 3,
|
|
},
|
|
])('Python: $nest', ({ source, perLevel, fixed }) => {
|
|
expect(depths.map((depth) => pythonOperandNodeVisits(source(depth)))).toEqual(
|
|
depths.map((depth) => perLevel * depth + fixed),
|
|
);
|
|
});
|
|
});
|
|
|
|
function emittedOperandNodeVisits(emit: Emit, file: string, source: string): number {
|
|
resetCallableFlowCaptureStats(true);
|
|
try {
|
|
emit(source, file);
|
|
return getCallableFlowCaptureStats().operandNodeVisits;
|
|
} finally {
|
|
resetCallableFlowCaptureStats();
|
|
}
|
|
}
|
|
|
|
/** `o[(o[(o[0] = 1).k] = 1).k] = 1`: each destination holds the next assignment. */
|
|
function nestedSubscriptDestination(depth: number): string {
|
|
let target = 'o[0]';
|
|
for (let level = 0; level < depth; level++) target = `o[(${target} = 1).k]`;
|
|
return `${target} = 1;\n`;
|
|
}
|
|
|
|
// The second-leaf search answers "more than one identifier leaf?" and must stop
|
|
// at the second leaf it reaches. Finishing the subtree around that leaf first
|
|
// walked the whole receiver of `a.f.f…` and the whole nest under a destination
|
|
// that holds the next assignment: O(depth) per operand, O(depth^2) per nest.
|
|
describe('the second-leaf search stops at the second leaf', () => {
|
|
const depths = [8, 16, 64];
|
|
|
|
it.each([
|
|
{
|
|
shape: 'Python: a member-chain argument',
|
|
emit: emitPythonScopeCaptures,
|
|
file: 'chain.py',
|
|
source: (depth: number) => `f(a${'.f'.repeat(depth)})\n`,
|
|
perLevel: 0,
|
|
fixed: 7,
|
|
},
|
|
{
|
|
shape: 'Python: a member-chain callee',
|
|
emit: emitPythonScopeCaptures,
|
|
file: 'chain.py',
|
|
source: (depth: number) => `a${'.f'.repeat(depth)}()\n`,
|
|
perLevel: 0,
|
|
fixed: 6,
|
|
},
|
|
{
|
|
shape: 'JavaScript: a destination that holds the next assignment',
|
|
emit: emitJsScopeCaptures,
|
|
file: 'nest.js',
|
|
source: nestedSubscriptDestination,
|
|
perLevel: 14,
|
|
fixed: 8,
|
|
},
|
|
])('$shape', ({ emit, file, source, perLevel, fixed }) => {
|
|
expect(depths.map((depth) => emittedOperandNodeVisits(emit, file, source(depth)))).toEqual(
|
|
depths.map((depth) => perLevel * depth + fixed),
|
|
);
|
|
});
|
|
});
|