Skip to content

Commit 5c27e4f

Browse files
author
Forge
committed
Reuse pure core parses across atomic semantic updates
1 parent 4e54a29 commit 5c27e4f

16 files changed

Lines changed: 382 additions & 28 deletions

‎.github/workflows/extensions-native.yml‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,8 @@ jobs:
3636
timeout-minutes: 35
3737
env:
3838
CODEGRAPH_TELEMETRY: '0'
39-
# This increment changes registry storage and hosted browser behavior.
40-
# Prior core lifecycle/native-path/70-kill matrices remain recorded.
41-
NATIVE_VALIDATION_SCOPE: marketplace
39+
# Core parsing/candidate recovery changed: exercise native lifecycle too.
40+
NATIVE_VALIDATION_SCOPE: full
4241
steps:
4342
- uses: actions/checkout@v4
4443
with:

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
1717

1818
### Extension preview
1919

20-
- Reconcile global semantic-extension links after sync or explicit file indexing with an atomic candidate rebuild. Failed passes preserve the working graph; changed-file sync currently pays full-rebuild cost for these extensions.
20+
- Reconcile global semantic-extension links after sync or explicit file indexing with an atomic candidate rebuild. Failed passes preserve the working graph. Reuse bounded core parse results on warm project instances while rerunning all framework hooks, global resolution and semantic passes; cold or disabled reuse retains full parsing. Reject observed source changes before commit and reclaim interrupted graph-only candidates.
2121

2222
- Prepare immutable Drupal extension 0.1.1: ignore unrelated static receivers and commented/quoted declarations, and resolve both explicit Symfony event argument orders. Preserve the reviewed 0.1.0 artifact and policy.
2323
- Keep installed and selected marketplace versions distinct while compatibility metadata refreshes; pending requests no longer display an incompatible catalog version as installed.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { expect, it } from 'vitest';
2+
import { CoreExtractionReuse } from '../src/extraction/core-reuse';
3+
import type { ExtractionResult } from '../src/types';
4+
const result = (): ExtractionResult => ({ nodes: [], edges: [], unresolvedReferences: [], errors: [], durationMs: 0 });
5+
it('invalidates changed bytes/languages/paths and never caches failures', () => {
6+
const c = new CoreExtractionReuse();const r=result();c.set('a.php','a','php',r);
7+
expect(c.get('a.php','a','php')).toBe(r);expect(c.get('b.php','a','php')).toBeUndefined();
8+
expect(c.get('a.php','b','php')).toBeUndefined();expect(c.get('a.php','a','php')).toBeUndefined();
9+
c.set('a.php','a','php',r);expect(c.get('a.php','a','python')).toBeUndefined();
10+
c.set('a.php','a','php',{...r,errors:[{message:'failed',severity:'error'}]});expect(c.get('a.php','a','php')).toBeUndefined();
11+
});
12+
it('bounds retained data, does not evict the whole working set during a large scan and prunes deleted paths', () => {
13+
const r=result(),size=Buffer.byteLength(JSON.stringify(r))*2,c=new CoreExtractionReuse(size);
14+
c.set('a','a','php',r);c.set('b','b','php',r);expect(c.stats().bytes).toBe(size);
15+
expect(c.get('a','a','php')).toBe(r);expect(c.get('b','b','php')).toBeUndefined();
16+
c.retain(['b']);expect(c.stats().entries).toBe(0);c.set('b','b','php',r);c.clear();expect(c.stats().bytes).toBe(0);
17+
});

‎__tests__/extension-sync.test.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ it('semantic extension sync replaces cross-file links and preserves working grap
1515
fs.writeFileSync(path.join(author, 'index.cjs'), `module.exports = () => ({ synthPasses: [{name:'bindings',languages:['python'],run(ctx) {
1616
const text=ctx.readFile('binding.py')||''; if(text.includes('FAIL')) throw Error('fixture candidate failed');
1717
const name=/target: (\\w+)/.exec(text)?.[1]; if(!name)return [];
18-
const from=ctx.getNodesByName('dispatch'),to=ctx.getNodesByName(name);if(from.length!==1||to.length!==1)return [];
18+
const from=ctx.getNodesByName('dispatch').filter(n=>n.kind==='function'),to=ctx.getNodesByName(name).filter(n=>n.kind==='function');if(from.length!==1||to.length!==1)return [];
1919
return [{source:from[0].id,target:to[0].id,kind:'calls',metadata:{label:'Test binding'},line:1}];
2020
}}] });`);
2121
fs.writeFileSync(path.join(project, 'handlers.py'), 'def dispatch():\n pass\ndef send_receipt():\n pass\ndef cancel_order():\n pass\n');
@@ -41,3 +41,59 @@ it('semantic extension sync replaces cross-file links and preserves working grap
4141
expect(noChanges.filesAdded + noChanges.filesModified + noChanges.filesRemoved).toBe(0);
4242
} finally { graph.close(); }
4343
}, 90_000);
44+
45+
it('reuses core parsing while rerunning global hooks, rejects source races, isolates projects and matches a cold rebuild', async () => {
46+
const { channel } = await import('node:diagnostics_channel');
47+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-semantic-reuse-')); roots.push(root);
48+
const author = path.join(root, 'author'); createExtensionProject(author, 'global-fixture');
49+
const manifestPath = path.join(author, 'package.json'), manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
50+
manifest.codegraph.capabilities = ['frameworks', 'synthPasses']; fs.writeFileSync(manifestPath, JSON.stringify(manifest));
51+
fs.writeFileSync(path.join(author, 'index.cjs'), `module.exports = ({projectRoot}) => ({
52+
frameworks:[{name:'global-framework',languages:['python'],detect:()=>true,resolve:()=>null,
53+
extract(file){ if(file!=='handlers.py')return {nodes:[],references:[]};
54+
const name=require('fs').readFileSync(require('path').join(projectRoot,'binding.py'),'utf8').trim();
55+
return {nodes:[{id:'plugin:global-fixture:route',kind:'route',name,qualifiedName:name,filePath:file,language:'python',startLine:1,endLine:1,startColumn:0,endColumn:1,metadata:{}}],references:[]}; }}],
56+
synthPasses:[{name:'bindings',languages:['python'],run(ctx){
57+
const name=(ctx.readFile('binding.py')||'').trim(); if(name==='FAIL')throw Error('real pass failed');
58+
const from=ctx.getNodesByName('dispatch').filter(n=>n.kind==='function'),to=ctx.getNodesByName(name).filter(n=>n.kind==='function');if(from.length!==1||to.length!==1)return [];
59+
return [{source:from[0].id,target:to[0].id,kind:'calls',line:1,metadata:{label:'Global binding'}}]; }}]
60+
});`);
61+
const pkg = packExtension(author), graphs: CodeGraph[] = [], events: any[] = [];
62+
const diagnostics = channel('codegraph.semantic.update'), listener = (event: unknown) => events.push(event);
63+
diagnostics.subscribe(listener);
64+
try {
65+
for (const target of ['receipt', 'cancel']) {
66+
const project = path.join(root, target); fs.mkdirSync(project);
67+
fs.writeFileSync(path.join(project, 'binding.py'), target);
68+
fs.writeFileSync(path.join(project, 'handlers.py'), 'def dispatch():\n unknown_symbol()\ndef receipt():\n pass\ndef cancel():\n pass\n');
69+
await new ExtensionManager(project).install({ bytes: pkg }); graphs.push(await CodeGraph.open(project));
70+
}
71+
const g = graphs[0], project = path.join(root, 'receipt'), binding = path.join(project, 'binding.py');
72+
const edges = (graph: CodeGraph) => {
73+
const nodes = graph.getNodesByKind('function'), names = new Map(nodes.map(n=>[n.id,n.name]));
74+
return graph.getOutgoingEdgesFrom(nodes.map(n=>n.id)).filter(e=>e.metadata?.synthesizedBy==='global-fixture')
75+
.map(e=>[names.get(e.source),names.get(e.target)]);
76+
};
77+
await g.indexFiles(['handlers.py']); // populate a cold owner cache
78+
fs.writeFileSync(binding, 'cancel'); await g.sync({ paths: ['binding.py'] });
79+
expect(events.filter(e=>e.phase==='candidate_ready').at(-1)).toMatchObject({coreReused:1,coreParsed:1});
80+
expect(edges(g)).toEqual([['dispatch','cancel']]);
81+
expect(g.getNodesByKind('route').map(n=>n.name)).toContain('cancel'); // hook uses a different file
82+
expect(g.getNodesByKind('route').map(n=>n.name)).not.toContain('receipt');
83+
await graphs[1].indexFiles(['binding.py']); expect(edges(graphs[1])).toEqual([['dispatch','cancel']]);
84+
fs.writeFileSync(binding, 'receipt');
85+
const change = (event: any) => {if(event.projectRoot===project && event.phase==='candidate_ready')fs.writeFileSync(binding,'cancel');};
86+
diagnostics.subscribe(change);
87+
try { await expect(g.sync()).rejects.toThrow('changed during semantic indexing'); }
88+
finally { diagnostics.unsubscribe(change); }
89+
expect(edges(g)).toEqual([['dispatch','cancel']]);
90+
fs.writeFileSync(binding, 'FAIL'); await expect(g.sync()).rejects.toThrow('real pass failed');
91+
expect(edges(g)).toEqual([['dispatch','cancel']]);
92+
fs.writeFileSync(binding,'receipt'); await g.sync(); expect(edges(g)).toEqual([['dispatch','receipt']]);
93+
expect(edges(graphs[1])).toEqual([['dispatch','cancel']]);
94+
const before = JSON.stringify([edges(g),g.getNodesByKind('route')]);
95+
const fresh = await CodeGraph.open(project); graphs.push(fresh); await fresh.refreshPluginIndex();
96+
expect(JSON.stringify([edges(fresh),fresh.getNodesByKind('route')])).toBe(before);
97+
const count = events.length; await g.sync(); await g.sync(); expect(events.length).toBe(count);
98+
} finally { diagnostics.unsubscribe(listener); graphs.forEach(g=>g.close()); }
99+
}, 90_000);
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Semantic update reuse (preview)
2+
3+
API v1 has arbitrary whole-graph semantic passes and framework hooks. Their
4+
output is never treated as file-local, and no extension dependency is inferred
5+
from language, filename or a previous set of returned edges.
6+
7+
The first optimization keeps a bounded in-memory cache of **core extraction
8+
before framework hooks** on the owning CodeGraph instance. Keys include exact
9+
relative path, decoded source, selected language and engine environment switches.
10+
An instance cannot survive an engine upgrade; no persistent cache schema exists.
11+
Framework detection/extract/postExtract, reference resolution and every semantic
12+
pass still rerun against a fresh candidate in the original insertion order.
13+
Workers still evaluate framework hooks. Failed extraction is not retained.
14+
Results are cloned before any downstream mutation. Candidates do not share graph
15+
or extension output; only core parser results are reused.
16+
17+
The budget is 128 MiB of estimated serialized payload (twice UTF-8 JSON size),
18+
not a guaranteed JS heap ceiling. The first working set that fits is retained;
19+
a scan larger than the budget does not repeatedly evict everything. Missing,
20+
changed, renamed, failed or non-retained entries use ordinary extraction.
21+
Closing a graph clears its cache. Fresh CLI processes and the first update after
22+
open remain cold. `CODEGRAPH_NO_SEMANTIC_REUSE=1` selects the conservative full
23+
parse path. This is **partial core-parse reuse**, not file-local semantic
24+
invalidation or an incremental database update. Global resolve/store cost remains.
25+
26+
No breaking author API or package change is required. Unrestricted I/O outside
27+
the supplied source/context remains subject to the existing deterministic-author
28+
contract; this optimization does not infer or certify those dependencies.
29+
Before/after source stamps cover the scanned indexed files plus root config and
30+
ignore rules. An observed change aborts before commit and preserves the working
31+
graph. This does not lock the filesystem: arbitrary external plugin I/O or a
32+
write after the final observation is not a certified snapshot. Retry after edits
33+
settle. Cache entries are content-keyed, so a failed candidate may safely retain
34+
unchanged core parses but never graph or plugin output.
35+
36+
Graph-only candidate records contain a checksummed UUID and diagnostic PID.
37+
The project SQLite coordinator is authoritative, independent of PID reuse.
38+
Fresh opens reclaim the exact orphaned stage after process death; an invalid
39+
record blocks recovery without deleting files. During a live graph-only update,
40+
readers can use the old committed graph. The existing SQLite graph transaction
41+
still determines old/new visibility. A commit marker invalidates long-lived
42+
reader caches. Managed config/trust transactions retain their exclusive guard.
43+
44+
Measurements and correctness/recovery coverage will be linked after validation.

‎scripts/validation/native-validation.cjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,13 @@ async function run(name, command, args, timeout = 360000, overrides = {}) {
4848
await run('drupal-package', process.execPath, ['scripts/build-extensions.mjs']);
4949
await run('drupal-accuracy', process.execPath, ['--test', 'scripts/validation/drupal-accuracy.test.cjs', 'scripts/validation/drupal-negative.test.cjs']);
5050
await run('focused', process.execPath, ['node_modules/vitest/vitest.mjs', 'run',
51-
'__tests__/marketplace-storage.test.ts', '__tests__/foundation.test.ts', '__tests__/extension-trust.test.ts', '__tests__/extension-releases.test.ts', '__tests__/extension-marketplace.test.ts', '__tests__/extension-author.test.ts', '__tests__/extension-sync.test.ts', '__tests__/plugins.test.ts', '__tests__/extension-explore.test.ts',
51+
'__tests__/marketplace-storage.test.ts', '__tests__/foundation.test.ts', '__tests__/extension-trust.test.ts', '__tests__/extension-releases.test.ts', '__tests__/extension-marketplace.test.ts', '__tests__/extension-author.test.ts', '__tests__/extension-sync.test.ts', '__tests__/core-extraction-reuse.test.ts', '__tests__/parse-pool.test.ts', '__tests__/plugins.test.ts', '__tests__/extension-explore.test.ts',
5252
'__tests__/db-reopen-on-replace.test.ts', '__tests__/status-json.test.ts', '__tests__/sync.test.ts', '__tests__/concurrent-locking.test.ts',
5353
'--maxWorkers=2', '--minWorkers=1', '--reporter=default', '--reporter=json', `--outputFile.json=${path.join(out, 'focused.json')}`]);
5454
await run('registry-storage', process.execPath, ['scripts/validation/marketplace-storage.cjs'], 120000, { STORAGE_OUTPUT: path.join(out, 'registry-storage') });
5555
await run('compiled-workers', process.execPath, ['--test', 'scripts/validation/extensions-runtime.test.cjs']);
5656
await run('native-paths', process.execPath, ['scripts/validation/native-paths.cjs']);
57+
await run('semantic-update-recovery', process.execPath, ['scripts/validation/semantic-update-recovery.cjs'], 180000, { SEMANTIC_RECOVERY_OUTPUT: path.join(out, 'semantic-recovery') });
5758
await run('process-recovery', process.execPath, ['scripts/validation/extensions-recovery.cjs'], 600000);
5859
await run('process-recovery-override', process.execPath, ['scripts/validation/extensions-recovery.cjs'], 600000, { CODEGRAPH_DIR: '.codegraph-native', RECOVERY_OUTPUT: path.join(out, 'recovery-override') });
5960
await run('external-author', process.execPath, ['scripts/validation/extension-author.cjs'], 600000);
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const diagnosticEvents=[];require('node:diagnostics_channel').channel('codegraph.semantic.update').subscribe(e=>diagnosticEvents.push(e));
2+
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),assert=require('node:assert/strict');const {CodeGraph}=require('../../dist');const {DatabaseSync}=require('node:sqlite');
3+
Object.assign(process.env,{CODEGRAPH_TELEMETRY:'0',CODEGRAPH_PARSE_WORKERS:'2',CODEGRAPH_RESOLVE_WORKERS:'0',CODEGRAPH_SYNTH_TIMINGS:'all'});
4+
const [root,file,out]=process.argv.slice(2),original=fs.readFileSync(path.join(root,file)),rows=[];fs.mkdirSync(path.dirname(out),{recursive:true});
5+
const save=()=>fs.writeFileSync(out,JSON.stringify({root,file,distSHA:crypto.createHash('sha256').update(fs.readFileSync('dist/index.js')).digest('hex'),rows},null,2));
6+
function refs(){const d=new DatabaseSync(path.join(root,'.codegraph/codegraph.db'),{readOnly:true});try{return d.prepare('select status,count(*) n from unresolved_refs group by status').all()}finally{d.close()}}
7+
(async()=>{const g=await CodeGraph.open(root);async function run(name,fn){const eventStart=diagnosticEvents.length;let progress=0;const started=performance.now(),cpu=process.cpuUsage();const result=await fn(p=>{if(p.phase==='parsing')progress=Math.max(progress,p.current)});rows.push({name,wallMs:performance.now()-started,cpu:process.cpuUsage(cpu),maxRSS:process.resourceUsage().maxRSS,parseProgress:progress,diagnostics:diagnosticEvents.slice(eventStart),result,refs:refs()});save();console.log(name,rows.at(-1).wallMs)}
8+
try{for(let i=0;i<3;i++)await run('no-change-'+i,p=>g.sync({onProgress:p}));fs.appendFileSync(path.join(root,file),'\n// semantic update timing fixture\n');await run('ordinary',p=>g.sync({paths:[file],onProgress:p}));await run('indexFiles-unchanged',()=>g.indexFiles([file]));fs.writeFileSync(path.join(root,file),original);await run('restore',p=>g.sync({paths:[file],onProgress:p}));for(let i=0;i<3;i++)await run('final-no-change-'+i,p=>g.sync({onProgress:p}));}finally{fs.writeFileSync(path.join(root,file),original);g.close();save()}})().catch(e=>{console.error(e);process.exitCode=1});

0 commit comments

Comments
 (0)