Skip to content

Commit 018b840

Browse files
author
Forge
committed
Replace candidate text search atomically in bulk
1 parent 5c27e4f commit 018b840

7 files changed

Lines changed: 24 additions & 10 deletions

File tree

‎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. 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.
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. Rebuild text search in bulk inside the atomic replacement transaction.
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.

‎docs/design/semantic-update-reuse.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,11 @@ The project SQLite coordinator is authoritative, independent of PID reuse.
3838
Fresh opens reclaim the exact orphaned stage after process death; an invalid
3939
record blocks recovery without deleting files. During a live graph-only update,
4040
readers can use the old committed graph. The existing SQLite graph transaction
41-
still determines old/new visibility. A commit marker invalidates long-lived
41+
still determines old/new visibility. FTS triggers are suspended and rebuilt
42+
inside that same transaction using the existing bulk-load API, avoiding per-row
43+
FTS work during replacement. A kill rolls back the trigger schema and FTS data
44+
with the graph; readers never see a committed missing-trigger window.
45+
`CODEGRAPH_NO_SEMANTIC_BULK_FTS=1` retains the previous trigger path. A commit marker invalidates long-lived
4246
reader caches. Managed config/trust transactions retain their exclusive guard.
4347

4448
Measurements and correctness/recovery coverage will be linked after validation.

‎scripts/validation/semantic-update-poll.cjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const diagnosticEvents=[];require('node:diagnostics_channel').channel('codegraph.semantic.update').subscribe(e=>diagnosticEvents.push(e));
1+
const diagnosticEvents=[];require('node:diagnostics_channel').channel('codegraph.semantic.update').subscribe(e=>diagnosticEvents.push({...e,atMs:performance.now()}));
22
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');
33
Object.assign(process.env,{CODEGRAPH_TELEMETRY:'0',CODEGRAPH_PARSE_WORKERS:'2',CODEGRAPH_RESOLVE_WORKERS:'0',CODEGRAPH_SYNTH_TIMINGS:'all'});
44
const [root,file,out]=process.argv.slice(2),original=fs.readFileSync(path.join(root,file)),rows=[];fs.mkdirSync(path.dirname(out),{recursive:true});

‎scripts/validation/semantic-update-recovery.cjs‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,16 @@ const {spawn}=require('node:child_process'),{channel}=require('node:diagnostics_
44
const {CodeGraph,createExtensionProject,packExtension}=require('../../dist');const {ExtensionManager}=require('../../dist/plugins/manager');
55
const {DatabaseSync}=require('node:sqlite');
66
Object.assign(process.env,{CODEGRAPH_TELEMETRY:'0',CODEGRAPH_PARSE_WORKERS:'2',CODEGRAPH_RESOLVE_WORKERS:'2',CODEGRAPH_PARALLEL_RESOLVE_MIN:'0'});
7-
const phases=['candidate_ready','before_commit','in_commit','committed'];
7+
const phases=['candidate_ready','before_commit','copy_started','in_commit','committed'];
8+
function ftsAdded(root){const db=new DatabaseSync(path.join(root,'.codegraph/codegraph.db'),{readOnly:true});try{return db.prepare("SELECT count(*) n FROM nodes_fts WHERE nodes_fts MATCH 'added_function'").get().n}finally{db.close()}}
89
function snapshot(root){const db=new DatabaseSync(path.join(root,'.codegraph/codegraph.db'),{readOnly:true});try{return db.prepare("select a.name source,b.name target from edges e join nodes a on a.id=e.source join nodes b on b.id=e.target where e.metadata like '%\"synthesizedBy\":\"kill-fixture\"%' order by a.name,b.name").all().map(r=>[r.source,r.target]);}finally{db.close()}}
910
if(process.argv[2]==='--child'){
1011
const [root,action,phase]=process.argv.slice(3);
1112
(async()=>{const g=await CodeGraph.open(root);try{
1213
if(action==='update'){
1314
await g.indexFiles(['binding.py']); // warm this process's cache on old source
1415
channel('codegraph.semantic.update').subscribe(e=>{if(e.phase===phase){fs.writeSync(1,JSON.stringify({phase,pid:process.pid})+'\n');Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0);}});
15-
fs.writeFileSync(path.join(root,'binding.py'),'cancel');await g.sync();
16+
fs.writeFileSync(path.join(root,'binding.py'),'cancel');fs.writeFileSync(path.join(root,'added.py'),'def added_function():\n pass\n');await g.sync();
1617
}else if(action==='retry')await g.sync();
1718
console.log(JSON.stringify({edges:snapshot(root),stats:g.getStats()}));
1819
}finally{g.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});
@@ -27,12 +28,12 @@ if(process.argv[2]==='--child'){
2728
for(const phase of phases){const root=path.join(lab,phase);fs.mkdirSync(root);fs.writeFileSync(path.join(root,'handlers.py'),'def dispatch():\n missing()\ndef receipt():\n pass\ndef cancel():\n pass\n');fs.writeFileSync(path.join(root,'binding.py'),'receipt');await new ExtensionManager(root).install({bytes});const config=fs.readFileSync(path.join(root,'codegraph.json'),'utf8');
2829
const reader=await CodeGraph.open(root);assert.deepEqual(snapshot(root),[['dispatch','receipt']]);reader.getNodesByKind('function');
2930
const c=child(root,'update',phase);let timer;try{await Promise.race([c.reached,c.done.then(r=>{throw Error('child ended '+r.stderr)}),new Promise((_,r)=>timer=setTimeout(()=>r(Error('timeout '+phase)),90000))])}finally{clearTimeout(timer)}
30-
const expected=phase==='committed'?'cancel':'receipt';assert.deepEqual(snapshot(root),[['dispatch',expected]]);assert.ok(reader.getStats().nodeCount>0);
31+
const expected=phase==='committed'?'cancel':'receipt';assert.deepEqual(snapshot(root),[['dispatch',expected]]);assert.ok(reader.getStats().nodeCount>0);assert.equal(ftsAdded(root),phase==='committed'?1:0);
3132
const concurrent=await child(root,'retry').done;assert.notEqual(concurrent.exit,0);assert.match(concurrent.stderr,/operation is active/);
3233
assert.equal(c.p.kill('SIGKILL'),true);const killed=await c.done;assert.ok(killed.signal==='SIGKILL'||(process.platform==='win32'&&killed.exit!==0));
33-
fs.writeFileSync(path.join(root,'keep.txt'),'unrelated user file');const inspect=await child(root,'inspect').done;assert.equal(inspect.exit,0,inspect.stderr);assert.deepEqual(snapshot(root),[['dispatch',expected]]);
34+
fs.writeFileSync(path.join(root,'keep.txt'),'unrelated user file');const inspect=await child(root,'inspect').done;assert.equal(inspect.exit,0,inspect.stderr);assert.deepEqual(snapshot(root),[['dispatch',expected]]);assert.equal(ftsAdded(root),phase==='committed'?1:0);
3435
assert.equal(fs.existsSync(path.join(root,'.codegraph/plugins/candidate.json')),false);assert.deepEqual(fs.readdirSync(path.join(root,'.codegraph')).filter(f=>f.startsWith('extension-stage-')),[]);
35-
assert.equal((await child(root,'inspect').done).exit,0);assert.equal((await child(root,'retry').done).exit,0);assert.deepEqual(snapshot(root),[['dispatch','cancel']]);
36+
assert.equal((await child(root,'inspect').done).exit,0);assert.equal((await child(root,'retry').done).exit,0);assert.deepEqual(snapshot(root),[['dispatch','cancel']]);assert.equal(ftsAdded(root),1);
3637
const funcs=reader.getNodesByKind('function');const names=new Map(funcs.map(n=>[n.id,n.name]));assert.deepEqual(reader.getOutgoingEdgesFrom(funcs.map(n=>n.id)).filter(e=>e.metadata?.synthesizedBy==='kill-fixture').map(e=>[names.get(e.source),names.get(e.target)]),[['dispatch','cancel']]);reader.close();
3738
assert.equal(fs.readFileSync(path.join(root,'codegraph.json'),'utf8'),config);assert.equal(fs.readFileSync(path.join(root,'keep.txt'),'utf8'),'unrelated user file');rows.push({phase,passed:true,edgesAfterKill:expected,concurrentExcluded:true,repeatedRecovery:true,readerFresh:true});save();console.log('PASS',phase);
3839
}

‎scripts/validation/semantic-update-sample.cjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const diagnosticEvents=[];require('node:diagnostics_channel').channel('codegraph.semantic.update').subscribe(e=>diagnosticEvents.push(e));
1+
const diagnosticEvents=[];require('node:diagnostics_channel').channel('codegraph.semantic.update').subscribe(e=>diagnosticEvents.push({...e,atMs:performance.now()}));
22
// Disposable existing corpus only. Keeps the graph open across an edit sequence.
33
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),cp=require('node:child_process'),assert=require('node:assert/strict');
44
const {DatabaseSync}=require('node:sqlite');const {CodeGraph}=require('../../dist');

‎src/extraction/parse-worker.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,9 @@ parentPort!.on('message', async (msg: { type: string; id?: number; filePath?: st
9999
let result: ReusableExtraction | undefined;
100100
if (msg.reuseCore) {
101101
const core = msg.coreExtraction ?? extractFromSource(filePath!, content!, language);
102-
result = applyFrameworkExtraction(structuredClone(core), filePath!, content!, language, frameworkNames);
102+
// A received base was already cloned by postMessage; only a new base
103+
// needs a second copy so the returned cache entry stays unmodified.
104+
result = applyFrameworkExtraction(msg.coreExtraction ? core : structuredClone(core), filePath!, content!, language, frameworkNames);
103105
if (!msg.coreExtraction) result.coreExtraction = core;
104106
}
105107
const frameworksNeedDecode =

‎src/index.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,10 +594,17 @@ export class CodeGraph {
594594
throw new Error('Project sources or configuration changed during semantic indexing; previous graph retained. Retry the update.');
595595
channel('codegraph.semantic.update').publish({ projectRoot: this.projectRoot, phase: 'before_commit' });
596596
connection.transaction(() => {
597+
// Candidate replacement is one bulk load. Keep the FTS trigger window
598+
// INSIDE this SQLite transaction so a kill rolls back graph and FTS
599+
// schema together; readers keep the prior committed index.
600+
const bulkFts = process.env.CODEGRAPH_NO_SEMANTIC_BULK_FTS !== '1';
601+
if (bulkFts) this.db.beginBulkNodeLoad();
602+
channel('codegraph.semantic.update').publish({ projectRoot: this.projectRoot, phase: 'copy_started' });
597603
this.queries.clear();
598604
for (const table of ['files', 'nodes', 'edges', 'unresolved_refs']) {
599605
connection.exec(`INSERT INTO main.${table} SELECT * FROM extension_candidate.${table}`);
600606
}
607+
if (bulkFts) this.db.endBulkNodeLoad();
601608
this.queries.setMetadata('plugins_last_run', JSON.stringify(plugins.diagnostics));
602609
this.queries.setMetadata('indexed_with_plugins', this.extensionStamp(plugins));
603610
this.queries.setMetadata('indexed_with_version', CodeGraphPackageVersion);

0 commit comments

Comments
 (0)