In this section
- Replicate Generation energy-data · gridatlas / tools/twin/replicate-generation.mjs lines 1–379
- Build Streaming Bridge interaction · gridatlas / tools/v9_5/build_streaming_bridge.py lines 1–297
Replicate Generation
A JavaScript module in the twin folder of GridAtlas that reads generations and substations, using SHA-256.
energy-datagridatlas / tools/twin/replicate-generation.mjs · lines 1–379 of 379 · Entry point · pattern fetchPinned (shared by 2 files)
- What it does
- It loads generations and substations. Defines done, same, constant, fetchPinned. Uses libraries node:fs, node:path. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'generation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: substations.
- Inputs & outputs
- In: JSON file current.json; JSON file generations.json; DuckDB queries; command-line arguments.
- Downstream impact
- Used directly by 3 files: CI PR Gate (gridatlas); GridAtlas Verify Live Workflow (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas). Reached from 1 other entry point, including Map Promotion Rehearsal (gridatlas).
- What it achieves
- It fetches pinned (`fetchPinned`) and is built from the done step (`done`) and the same step (`same`). The twin of a generation: rebuild it from its pinned source in a clean temporary directory, with the repository's own compiler and cut tools, and compare every rebuilt file with the committed one byte for byte. It reads `tools/train/gazetteer/generations.json`.
- Why it matters
- Run by CI PR Gate, GridAtlas Verify Live Workflow and GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/twin · JavaScript module
- Uses
- GridAtlas — Twin (import), node:fs, node:path
- Used by
- run by CI PR Gate (script call), run by GridAtlas Verify Live Workflow (workflow run), run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- done, same, constant, fetchPinned
- Defines here
- done, same, constant, fetchPinned
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/twin/replicate-generation.mjs:1-379 · blob 91362d8912cfa5db50151757c6edc1bba4cadd9f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/**
* The twin of a generation: rebuild it from its pinned source in a clean
* temporary directory, with the repository's own compiler and cut tools, and
* compare every rebuilt file with the committed one byte for byte. The
* committed generation must be exactly reproducible from its source, or this
* fails naming the file. Nothing in the repository is written.
*
* node tools/twin/replicate-generation.mjs --offline
* pins, coupling and cartridges only; no socket, no Python. The data
* rebuild is reported as NOT RUN. This is what tools/ci/pr-gate.mjs runs.
* node tools/twin/replicate-generation.mjs --source repd-2026q3.csv --oracle repd_master.json
* the whole twin from local files; no socket.
* node tools/twin/replicate-generation.mjs --network
* the whole twin; the source register and the oracle are fetched from
* the commit-pinned URLs in tools/twin/sources.json.
* --generation G default: the generation atlas/current.json names, and the newest
* generation in tools/twin/sources.json when that is a different one
* --python PATH default: python3 (needs requirements.lock: duckdb, pyproj)
* --keep keep the temporary directory and print its path
*
* Order (Ventusltd/testcode README, "offline first, then network, then
* publish"; nothing here publishes): every offline step runs first, and the
* network is not touched while an offline step is red.
*
* 1 pins tools/twin/sources.json, the compiler's constants and the
* committed data manifest name the same source bytes
* 2 coupling the committed data files hash to what their manifest says,
* and the generation's own cartridges carry those hashes
* 3 cartridges every cartridge the generation cut (same stamp) is rebuilt:
* an assembled cartridge by tools/build-cartridge.mjs from the
* parts its manifest lists, an overlay module by its build.mjs
* 4 source local file or pinned URL; refused unless sha256 and bytes
* equal the pin (Ventusltd/star-quantum-twin README: a record
* whose hash does not match is not used)
* 5 data the compiler, run twice into two empty directories; the two
* builds must agree with each other and with the committed files
*
* Without --offline, --source or --network the data step would examine
* nothing, so the tool refuses (exit 2) instead of passing.
*
* Exit: 0 reproduced; 1 FAIL (a file differs, named); 2 refused; 3 this rig
* cannot build (Python or a library missing); 4 a pinned URL did not answer.
*/
import fs from 'node:fs';
import path from 'node:path';
import { ROOT, STAMP, EXIT, abs, exists, sha256, sha256Of, readJson, sources, liveGeneration, tmpDir, arg, has, run, composition, reporter } from './lib.mjs';
// Default targets: the live generation, and the newest generation with pinned sources (a preview not yet live).
if (!arg('--generation')) {
const targets = [...new Set([liveGeneration(), Object.keys(sources()).sort().at(-1)].filter(Boolean))];
if (targets.length > 1) {
let worst = 0;
for (const g of targets) worst = Math.max(worst, run(['node', process.argv[1], ...process.argv.slice(2), '--generation', g], { stdio: 'inherit' }).code);
process.exit(worst);
}
}
const G = arg('--generation', liveGeneration());
const OFFLINE = has('--offline'), NETWORK = has('--network');
let SOURCE = arg('--source'), ORACLE = arg('--oracle');
const PYTHON = arg('--python', process.env.TWIN_PYTHON || 'python3');
if (!STAMP.test(G)) { console.error(`--generation must be YYYYMMDDHHMM, got ${G}`); process.exit(EXIT.REFUSED); }
if (!OFFLINE && !NETWORK && !SOURCE) {
console.error('refused: no --source, --network or --offline, so the data files would not be examined. A check that examines nothing refuses; it does not pass.');
process.exit(EXIT.REFUSED);
}
if (OFFLINE && (NETWORK || SOURCE)) { console.error('refused: --offline excludes --network and --source'); process.exit(EXIT.REFUSED); }
const R = reporter(`twin ${G}`);
const pin = sources()[G];
const work = tmpDir(`twin-${G}`);
const done = code => { if (has('--keep')) console.log(`kept ${work}`); else fs.rmSync(work, { recursive: true, force: true }); process.exit(code); };
const same = (name, rebuilt, committedRel) => {
if (!exists(committedRel)) return R.fail(name, `${committedRel} is not in the repository`);
const a = fs.readFileSync(rebuilt), b = fs.readFileSync(abs(committedRel));
if (a.equals(b)) return R.pass(name, `${committedRel} ${b.length} B sha256 ${sha256(b)} rebuilt byte for byte`);
let i = 0; while (i < a.length && i < b.length && a[i] === b[i]) i++;
R.fail(name, `${committedRel} differs from its rebuild at byte ${i} (committed ${b.length} B ${sha256(b)}, rebuilt ${a.length} B ${sha256(a)})`);
};
console.log(`twin of generation ${G}; mode ${OFFLINE ? 'offline (no data rebuild)' : SOURCE ? 'local source' : 'network'}; work ${work}`);
if (!exists(`atlas/v/${G}/current.json`)) { R.fail('generation', `atlas/v/${G}/current.json missing`); done(R.finish()); }
const comp = composition(G);
// ------------------------------------------------------------------ 1 pins
let manifest = null;
if (!pin) {
// A generation that cut no data (only cartridges) has no entry; one that did must have one.
const owns = fs.readdirSync(abs('data')).filter(f => f.includes(`_${G}.`));
if (owns.length) R.fail('pins', `data/ holds ${owns.join(', ')} but tools/twin/sources.json has no entry for ${G}`);
else R.note('pins', `${G} cut no data files; cartridges only`);
} else {
const bad = [];
const compiler = fs.readFileSync(abs(pin.compiler), 'utf8');
const constant = name => (compiler.match(new RegExp(`^${name} = "?([^"\\n]+)"?$`, 'm')) || [])[1];
manifest = readJson(pin.data_manifest);
if (constant('GENERATION') !== G) bad.push(`${pin.compiler} GENERATION is ${constant('GENERATION')}`);
if (constant('SOURCE_SHA256') !== pin.source.sha256) bad.push(`${pin.compiler} SOURCE_SHA256 is not the pinned source`);
if (Number(constant('SOURCE_BYTES')) !== pin.source.bytes) bad.push(`${pin.compiler} SOURCE_BYTES is not the pinned size`);
if (constant('V8_SHA256') !== pin.oracle.sha256) bad.push(`${pin.compiler} V8_SHA256 is not the pinned oracle`);
if (manifest.generation !== G) bad.push(`${pin.data_manifest} declares generation ${manifest.generation}`);
if (manifest.source?.sha256 !== pin.source.sha256 || manifest.source?.bytes !== pin.source.bytes) bad.push(`${pin.data_manifest} source is not the pinned source`);
if (manifest.v8_oracle?.sha256 !== pin.oracle.sha256) bad.push(`${pin.data_manifest} oracle is not the pinned oracle`);
for (const k of ['source', 'oracle']) if (!/\/[0-9a-f]{40}\//.test(pin[k].url)) bad.push(`${k} URL does not name a commit`);
if (bad.length) R.fail('pins', bad.join('; '));
else R.pass('pins', `source ${pin.source.sha256} (${pin.source.bytes} B) and oracle ${pin.oracle.sha256.slice(0, 12)}… agree in sources.json, ${pin.compiler} and ${pin.data_manifest}`);
}
// ------------------------------------------------------------------ 2 coupling
const dataFiles = []; // [name written by the compiler, committed path]
if (manifest) {
const bad = [];
for (const k of ['parquet', 'browser_registry']) {
const rel = `data/${manifest[k].path}`;
dataFiles.push([manifest[k].path, rel]);
if (!exists(rel)) { bad.push(`${rel} missing`); continue; }
if (sha256Of(rel) !== manifest[k].sha256 || fs.statSync(abs(rel)).size !== manifest[k].bytes) bad.push(`${rel} is not the file ${pin.data_manifest} describes`);
}
dataFiles.push([path.basename(pin.data_manifest), pin.data_manifest]);
// The generation's own cartridges read the data by URL and refuse it unless it hashes to these two values.
const wanted = [sha256Of(pin.data_manifest), manifest.parquet.sha256];
const own = comp.cartridges.filter(c => !c.missing && String(c.generation) === G);
const carriers = own.filter(c => wanted.every(h => fs.readFileSync(abs(c.file), 'utf8').includes(h)));
if (!carriers.length) bad.push(`no cartridge cut at ${G} carries the manifest and parquet hashes, so nothing ties the composition to these data files`);
if (bad.length) R.fail('coupling', bad.join('; '));
else R.pass('coupling', `committed parquet and registry are the files the manifest describes; ${carriers.map(c => c.id).join(', ')} pin manifest ${wanted[0].slice(0, 12)}… and parquet ${wanted[1].slice(0, 12)}…`);
}
// ------------------------------------------------------------------ 3 cartridges
const own = comp.cartridges.filter(c => !c.missing && String(c.generation) === G);
if (!own.length) R.note('cartridges', `the composition of ${G} cut no cartridge of its own`);
for (const c of own) {
const name = `cartridge ${c.id}`;
const overlay = c.file.match(/^atlas\/modules\/(\d{12})-uk-(lightning|offtakers)-overlay\.js$/);
if (c.assembled_from) {
// tools/build-cartridge.mjs writes beside itself and refuses an existing output, so it is run from a copy in an
// empty tree that holds only the tool and the parts the manifest lists.
const partsRel = path.posix.normalize(path.posix.join(`atlas/v/${G}`, c.assembled_from));
const parts = readJson(partsRel);
const tree = path.join(work, `assemble-${c.id}`);
for (const d of ['tools', 'atlas/cartridges', 'atlas/manifests']) fs.mkdirSync(path.join(tree, d), { recursive: true });
fs.copyFileSync(abs('tools/build-cartridge.mjs'), path.join(tree, 'tools', 'build-cartridge.mjs'));
const argv = ['node', path.join(tree, 'tools', 'build-cartridge.mjs'), '--generation', String(parts.generation),
'--name', path.basename(parts.cartridge, '.js').slice(13)];
const flag = { carried_shell_script: '--carry', module: '--module', part: '--part' };
for (const p of parts.assembled_from) {
fs.mkdirSync(path.dirname(path.join(tree, p.path)), { recursive: true });
fs.copyFileSync(abs(p.path), path.join(tree, p.path));
argv.push(flag[p.role], p.path);
}
const r = run(argv, { cwd: tree });
const out = path.join(tree, 'atlas', path.normalize(parts.cartridge));
if (r.code !== 0 || !fs.existsSync(out)) { R.fail(name, `tools/build-cartridge.mjs exit ${r.code}: ${(r.stderr || r.stdout).trim().slice(0, 200)}`); continue; }
same(name, out, c.file);
if (sha256(fs.readFileSync(out)) !== c.sha256) R.fail(`${name} pin`, `rebuilt ${c.file} is not the sha256 atlas/v/${G}/current.json pins`);
same(`${name} parts manifest`, path.join(tree, partsRel), partsRel);
} else if (overlay) {
const kind = overlay[2], gens = readJson(`tools/${kind}/generations.json`), entry = gens.generations[overlay[1]];
if (!entry) { R.fail(name, `${overlay[1]} is not listed in tools/${kind}/generations.json`); continue; }
if (entry.historical) { R.note(name, `historical: built from ${entry.historical}; the current source no longer rebuilds it, so it is held by its hash only (tools/twin/preserve.mjs)`); continue; }
const out = path.join(work, path.basename(c.file));
const argv = ['node', `tools/${kind}/build.mjs`, '--gen', overlay[1], '--out', out];
if (entry.variant) argv.push('--variant', entry.variant);
const r = run(argv);
if (r.code !== 0 || !fs.existsSync(out)) { R.fail(name, `tools/${kind}/build.mjs exit ${r.code}: ${(r.stderr || r.stdout).trim().slice(0, 200)}`); continue; }
same(name, out, c.file);
if (sha256(fs.readFileSync(out)) !== c.sha256) R.fail(`${name} pin`, `rebuilt ${c.file} is not the sha256 atlas/v/${G}/current.json pins`);
} else if (c.id === 'uk-gazetteer-flyto' && exists('tools/train/gazetteer/generations.json') && readJson('tools/train/gazetteer/generations.json').generations[G]) {
const entry=readJson('tools/train/gazetteer/generations.json').generations[G],tree=path.join(work,'gazetteer-lookup-source');
for(const rel of ['tools/train/gazetteer/build.mjs','tools/train/gazetteer/generations.json',entry.base.path,entry.edits]){const to=path.join(tree,rel);fs.mkdirSync(path.dirname(to),{recursive:true});fs.copyFileSync(abs(rel),to);}
const out=path.join(work,path.basename(c.file)),r=run(['node',path.join(tree,'tools/train/gazetteer/build.mjs'),'--gen',G,'--out',out]);
if(r.code!==0||!fs.existsSync(out)){R.fail(name,'Gazetteer lookup source rebuild failed: '+(r.stderr||r.stdout).trim().slice(0,200));continue;}
same(name,out,c.file);if(sha256(fs.readFileSync(out))!==c.sha256)R.fail(name+' pin','Rebuilt gazetteer differs from composition pin');
} else if (c.id === 'substation-intelligence' && exists('tools/pipeline-lifecycle/generations.json') && readJson('tools/pipeline-lifecycle/generations.json').generations[G]) {
const entry = readJson('tools/pipeline-lifecycle/generations.json').generations[G];
const tree = path.join(work, 'pipeline-lifecycle-source');
for (const rel of ['tools/pipeline-lifecycle/build.mjs', 'tools/pipeline-lifecycle/generations.json', entry.base.path, entry.edits]) {
const to = path.join(tree, rel); fs.mkdirSync(path.dirname(to), {recursive: true}); fs.copyFileSync(abs(rel), to);
}
const out = path.join(work, path.basename(c.file));
const r = run(['node', path.join(tree, 'tools/pipeline-lifecycle/build.mjs'), '--gen', G, '--out', out]);
if (r.code !== 0 || !fs.existsSync(out)) { R.fail(name, 'Pipeline lifecycle source rebuild failed: ' + (r.stderr || r.stdout).trim().slice(0, 200)); continue; }
same(name, out, c.file);
if (sha256(fs.readFileSync(out)) !== c.sha256) R.fail(name + ' pin', 'Rebuilt substation differs from composition pin');
} else if (c.id === 'sld-sandbox' && G === '202611222130') {
// Rebuild the full 451 kB carrier from its ORIGINAL immutable V9.191 bytes
// and five exact layout-retirement edits. The expected target is absent
// from the independent temporary source checkout.
const tree=path.join(work,'sld-without-layout-source');
for(const rel of [
'tools/sld/retire-gridatlas-layout.mjs',
'atlas/cartridges/202611161720-sld-sandbox-v9-8.js'
]){
const to=path.join(tree,rel);
fs.mkdirSync(path.dirname(to),{recursive:true});
fs.copyFileSync(abs(rel),to);
}
fs.mkdirSync(path.join(tree,'atlas/modules'),{recursive:true});
const out=path.join(tree,c.file);
const r=run(['node',path.join(tree,'tools/sld/retire-gridatlas-layout.mjs')],{cwd:tree});
if(r.code!==0||!fs.existsSync(out)){
R.fail(name,'Layout retirement source rebuild failed: '+(r.stderr||r.stdout).trim().slice(0,220));
continue;
}
same(name,out,c.file);
if(sha256(fs.readFileSync(out))!==c.sha256)
R.fail(name+' pin','Rebuilt no-layout carrier differs from the composition SHA-256');
} else if (c.id === 'vicinity-focus' && G === '202611222130') {
// Source-owned, immutable Vicinity focus: copy only its pinned source
// and reproducer into a clean tree, never the expected output file.
const tree=path.join(work,'vicinity-focus-source');
for(const rel of [
'tools/vicinity-focus/build.mjs',
'tools/vicinity-focus/src/202611222130-vicinity-focus.js'
]){
const to=path.join(tree,rel);
fs.mkdirSync(path.dirname(to),{recursive:true});
fs.copyFileSync(abs(rel),to);
}
const out=path.join(work,path.basename(c.file));
const r=run(['node',path.join(tree,'tools/vicinity-focus/build.mjs'),'--generation',G,'--out',out],{cwd:tree});
if(r.code!==0||!fs.existsSync(out)){
R.fail(name,'Vicinity-focus source rebuild failed: '+(r.stderr||r.stdout).trim().slice(0,220));
continue;
}
same(name,out,c.file);
if(sha256(fs.readFileSync(out))!==c.sha256)
R.fail(name+' pin','Rebuilt vicinity focus differs from composition SHA-256');
} else if (c.id === 'vicinity-controls-rescue' && ['202611222325','202611222343'].includes(G)) {
// A clean tree contains only the small source and deterministic builder.
// Never copy the committed output as the supposed proof of its own bytes.
const tree=path.join(work,'vicinity-controls-source');
for(const rel of [
'tools/vicinity-controls/build.mjs',
'tools/vicinity-controls/src/'+G+'-vicinity-controls-rescue.js'
]){
const to=path.join(tree,rel);
fs.mkdirSync(path.dirname(to),{recursive:true});
fs.copyFileSync(abs(rel),to);
}
const out=path.join(work,path.basename(c.file));
const r=run(['node',path.join(tree,'tools/vicinity-controls/build.mjs'),'--generation',G,'--out',out],{cwd:tree});
if(r.code!==0||!fs.existsSync(out)){
R.fail(name,'Vicinity recovery source rebuild failed: '+(r.stderr||r.stdout).trim().slice(0,220));
continue;
}
same(name,out,c.file);
if(sha256(fs.readFileSync(out))!==c.sha256)
R.fail(name+' pin','V9.196 rebuild differs from composition SHA256');
} else if (c.id === 'sld-sandbox' && exists('tools/sld/generations.json') && readJson('tools/sld/generations.json').generations[G]) {
// Only pinned source inputs enter this empty tree. The expected final cartridge is absent.
const entry = readJson('tools/sld/generations.json').generations[G];
const tree = path.join(work, 'sld-source');
for (const rel of ['tools/sld/build.mjs', 'tools/sld/generations.json', entry.base.path, entry.owner.path, entry.edits]) {
const to = path.join(tree, rel); fs.mkdirSync(path.dirname(to), { recursive: true }); fs.copyFileSync(abs(rel), to);
}
const out = path.join(work, path.basename(c.file));
const r = run(['node', path.join(tree, 'tools/sld/build.mjs'), '--gen', G, '--out', out]);
if (r.code !== 0 || !fs.existsSync(out)) { R.fail(name, 'SLD source rebuild failed: ' + (r.stderr || r.stdout).trim().slice(0, 200)); continue; }
same(name, out, c.file);
if (sha256(fs.readFileSync(out)) !== c.sha256) R.fail(name + ' pin', 'rebuilt SLD differs from the composition pin');
} else if (c.id === 'pipeline-vicinity-button') {
const tree=path.join(work,'pipeline-vicinity-source');
for(const rel of ['tools/pipeline-vicinity/build.mjs','tools/pipeline-vicinity/src/202611222000-entry.js']){
const dest=path.join(tree,rel);fs.mkdirSync(path.dirname(dest),{recursive:true});fs.copyFileSync(abs(rel),dest);
}
const out=path.join(work,path.basename(c.file));
const r=run(['node',path.join(tree,'tools/pipeline-vicinity/build.mjs'),'--generation',G,'--out',out]);
if(r.code!==0||!fs.existsSync(out)){R.fail(name,'source rebuild failed: '+(r.stderr||r.stdout).trim().slice(0,200));continue;}
same(name,out,c.file);
if(sha256(fs.readFileSync(out))!==c.sha256)R.fail(name+' pin','source-built launcher SHA differs');
} else if (c.id === 'ukpn-secondary-substations' && G === '202612010912') {
const tree=path.join(work,'ukpn-secondary-source');
for(const rel of ['tools/secondary/build.mjs','tools/secondary/src/202612010912-native-layer.js']){
const dest=path.join(tree,rel);fs.mkdirSync(path.dirname(dest),{recursive:true});fs.copyFileSync(abs(rel),dest);
}
const out=path.join(work,path.basename(c.file));
const r=run(['node',path.join(tree,'tools/secondary/build.mjs'),'--out',out]);
if(r.code!==0||!fs.existsSync(out)){R.fail(name,'UKPN source rebuild failed: '+(r.stderr||r.stdout).trim().slice(0,200));continue;}
same(name,out,c.file);
if(sha256(fs.readFileSync(out))!==c.sha256)R.fail(name+' pin','UKPN rebuilt SHA differs');
} else if (['grid-journey-preview', 'grid-vicinity'].includes(c.id)) {
// Rebuild source-owned explorer modules in an empty tree. No expected output enters it.
const kind = c.id === 'grid-journey-preview' ? 'journey' : 'vicinity';
const tree = path.join(work, `${kind}-source`), rel = `tools/${kind}`;
fs.mkdirSync(path.join(tree, 'tools'), {recursive: true});
fs.cpSync(abs(rel), path.join(tree, rel), {recursive: true});
if (kind === 'vicinity' && exists('tools/train')) fs.cpSync(abs('tools/train'),path.join(tree,'tools/train'),{recursive:true});
const out = path.join(work, path.basename(c.file));
const entry = kind === 'journey' ? 'build-module.mjs' : 'build.mjs';
const r = run(['node', path.join(tree, rel, entry), '--generation', G, '--out', out]);
if (r.code !== 0 || !fs.existsSync(out)) { R.fail(name, `${kind} source rebuild failed: ${(r.stderr || r.stdout).trim().slice(0, 200)}`); continue; }
same(name, out, c.file);
if (sha256(fs.readFileSync(out)) !== c.sha256) R.fail(`${name} pin`, 'Rebuilt explorer module differs from the composition pin');
} else {
R.fail(name, `${c.file} was cut at ${G} but no builder is known for it (not assembled_from, not an overlay module); the twin cannot rebuild it`);
}
}
// ------------------------------------------------------------------ the offline phase ends here
if (!manifest && G === '202612010912' && NETWORK && !R.failed().length) {
const a=run([PYTHON,abs('tools/secondary/audit_ukpn.py'),'--work',path.join(work,'ukpn-data')]);
console.log(a.stdout);
if(a.code!==0) R.fail('UKPN real-source DuckDB audit',a.stderr.trim().slice(-1200));
else R.pass('UKPN real-source DuckDB audit','two source builds and historical partition comparison executed; outputs are temporary, not published');
}
if (!manifest) done(R.finish());
if (OFFLINE) {
R.note('data', `NOT RUN in the offline phase: ${dataFiles.map(d => d[1]).join(', ')} are rebuilt only with --source or --network`);
done(R.finish('data rebuild not run'));
}
if (R.failed().length) {
R.note('data', 'NOT RUN: an offline step is red, so neither the source nor the network is touched');
done(R.finish('stopped before the source'));
}
// ------------------------------------------------------------------ 4 source
function fetchPinned(what, to) {
// curl, because it honours the runner's and a sandbox's proxy settings; Node's fetch does not everywhere.
const r = run(['curl', '-fsSL', '--retry', '2', '--max-time', '120', '-o', to, pin[what].url]);
if (r.code !== 0) { console.error(`BLOCKED_DEPENDENCY ${what}: ${pin[what].url} did not answer (curl exit ${r.code}: ${r.stderr.trim().slice(0, 160)})`); done(EXIT.BLOCKED_DEPENDENCY); }
return to;
}
const inputs = {};
for (const [what, given] of [['source', SOURCE], ['oracle', ORACLE]]) {
let file;
if (given) file = path.resolve(given);
else if (NETWORK) file = fetchPinned(what, path.join(work, pin[what].name));
else { R.fail(what, `--${what} PATH is required with --source (or use --network): the compiler needs ${pin[what].name}`); continue; }
if (!fs.existsSync(file)) { R.fail(what, `${file} does not exist`); continue; }
const got = sha256Of(file), size = fs.statSync(file).size;
if (got !== pin[what].sha256 || size !== pin[what].bytes) { R.fail(what, `${given ? file : pin[what].url} is ${size} B sha256 ${got}; the pin is ${pin[what].bytes} B ${pin[what].sha256}. Not used.`); continue; }
inputs[what] = file;
R.pass(what, `${given ? `local ${path.basename(file)}` : pin[what].url} is the pinned ${pin[what].bytes} B sha256 ${got}`);
}
if (R.failed().length) done(R.finish('stopped before the build'));
// ------------------------------------------------------------------ 5 data
const probe = run([PYTHON, '-c', 'import duckdb, pyproj; print(duckdb.__version__, pyproj.__version__)']);
if (probe.code !== 0) {
console.error(`BLOCKED_HARNESS: ${PYTHON} cannot import duckdb and pyproj (pip install -r requirements.lock): ${probe.stderr.trim().split('\n').pop()}`);
done(EXIT.BLOCKED_HARNESS);
}
const [duck, proj] = probe.stdout.trim().split(' ');
const lock = Object.fromEntries(fs.readFileSync(abs('requirements.lock'), 'utf8').split('\n').filter(l => l.includes('==')).map(l => l.trim().split('==')));
const offLock = duck !== lock.duckdb || proj !== lock.pyproj || duck !== manifest.runtime.duckdb;
console.log(`runtime: duckdb ${duck}, pyproj ${proj} (requirements.lock: ${lock.duckdb}, ${lock.pyproj}; the committed manifest was built with duckdb ${manifest.runtime.duckdb})`);
const builds = [];
for (const side of ['a', 'b']) {
const out = path.join(work, `build-${side}`);
fs.mkdirSync(out);
// cwd is the empty build directory: the compiler reads only its two inputs and writes only into --output.
const r = run([PYTHON, abs(pin.compiler), '--source', inputs.source, '--v8', inputs.oracle, '--output', out], { cwd: out });
if (r.code !== 0) { R.fail(`compile ${side}`, `${pin.compiler} exit ${r.code}: ${r.stderr.trim().split('\n').pop().slice(0, 240)}`); break; }
builds.push(out);
console.log(`build ${side}: ${r.stdout.trim()}`);
}
if (builds.length === 2) {
const extra = fs.readdirSync(builds[0]).filter(f => !dataFiles.some(d => d[0] === f));
if (extra.length) R.fail('data closure', `the compiler wrote ${extra.join(', ')}, which the manifest does not list`);
let stable = true;
for (const [name] of dataFiles) {
const a = path.join(builds[0], name), b = path.join(builds[1], name);
if (!fs.existsSync(a) || !fs.existsSync(b) || !fs.readFileSync(a).equals(fs.readFileSync(b))) { stable = false; R.fail(`deterministic ${name}`, 'two builds from the same source on this machine differ, so no rebuild can be compared with the committed file'); }
}
if (stable) {
R.pass('deterministic', `two builds agree on ${dataFiles.length} files`);
for (const [name, rel] of dataFiles) same(`data ${name}`, path.join(builds[0], name), rel);
}
}
if (R.failed().length && offLock) {
R.finish();
console.error(`BLOCKED_HARNESS: this rig's duckdb ${duck} / pyproj ${proj} are not the locked versions, and Parquet bytes depend on the writer; install requirements.lock and run again before reading the failures above as a fault in the generation`);
done(EXIT.BLOCKED_HARNESS);
}
done(R.finish());Build Streaming Bridge
A Python command-line tool in the tools folder of GridAtlas that reads streaming road fix, streaming road build and 400kV, using SHA-256.
interactiongridatlas / tools/v9_5/build_streaming_bridge.py · lines 1–297 of 297 · Entry point · pattern dump_json (shared by 2 files)
- What it does
- It loads streaming road fix, streaming road build and 400kV. Defines load_json, dump_json, sha256_bytes, compile_bridge, main. Uses libraries __future__, argparse, copy, hashlib, json. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV.
- Inputs & outputs
- In: JSON file current.json; JSON file streaming-road-fix.json; JSON file streaming-road-build.json; DuckDB queries; command-line arguments. Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: GridAtlas Verify Live Workflow (gridatlas).
- What it achieves
- It loads JSON (`load_json`), dumps JSON (`dump_json`) and compiles bridge (`compile_bridge`). Compile a streaming-response bridge cartridge over the immutable GridAtlas shell. Its code works with 400 kV. It accepts `--generation`, `--request` and `--report`.
- Why it matters
- Run by GridAtlas Verify Live Workflow.
- Application
- gridatlas · tools/v9_5 · Python CLI
- Uses
- __future__, argparse, copy, hashlib, json, re, pathlib, typing
- Used by
- run by GridAtlas Verify Live Workflow (workflow run)
- Produces
- load_json, dump_json, sha256_bytes, compile_bridge, main
- Defines here
- load_json, dump_json, sha256_bytes, compile_bridge, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/v9_5/build_streaming_bridge.py:1-297 · blob 29d2d60df1d26613665409ccc54dcc4d67cf4c2d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Compile a streaming-response bridge cartridge over the immutable GridAtlas shell."""
from __future__ import annotations
import argparse
import copy
import hashlib
import json
import re
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[2]
CURRENT = ROOT / "atlas/current.json"
BRIDGE_SLOT = "202608292311-maplibre-worker-bridge.js"
TRANSPORT_ID = "streaming-parquet-bridge"
SEARCH_ID = "uk-gazetteer-flyto"
def load_json(path: Path) -> dict[str, Any]:
return json.loads(path.read_text(encoding="utf-8"))
def dump_json(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, indent=2, sort_keys=False) + "\n", encoding="utf-8")
def sha256_bytes(value: bytes) -> str:
return hashlib.sha256(value).hexdigest()
def compile_bridge(source: str, generation: str) -> str:
replacements = {
"const GENERATION = '202608292311';": f"const GENERATION = '{generation}';",
" preload_browser_duckdb: false,": " preload_browser_duckdb: 'AFTER_CRITICAL_SOURCE',",
" failures: []": " failures: [],\n streamed_responses: 0,\n stream_failures: [],\n runtime_prewarm: { requested: false, started: false, completed: false, failed: null }",
" const expected = `partitions/${stem}.parquet`.toLowerCase();": " const alias = stem === 'uk_metros_trams' ? 'uk_metros_trams_root' : stem;\n const expected = `partitions/${alias}.parquet`.toLowerCase();",
}
for old, new in replacements.items():
if source.count(old) != 1:
raise RuntimeError(f"bridge marker changed or ambiguous: {old!r}")
source = source.replace(old, new, 1)
anchor = " async function resolvePartition(pathname) {"
prewarm = r''' function scheduleRuntimePrewarm() {
state.runtime_prewarm.requested = true;
let checks = 0;
const poll = setInterval(() => {
checks += 1;
let criticalReady = false;
try {
const map = window.__GRIDATLAS_V9_MAP__;
criticalReady = Boolean(map && map.getSource('src-400') && map.isSourceLoaded('src-400'));
} catch {}
if (!criticalReady && checks < 240) return;
clearInterval(poll);
const start = () => {
state.runtime_prewarm.started = true;
getRuntime().then(() => {
state.runtime_prewarm.completed = true;
}).catch(error => {
state.runtime_prewarm.failed = String(error?.message || error);
state.failures.push({ pathname: 'duckdb-runtime-prewarm', message: state.runtime_prewarm.failed });
});
};
if (typeof requestIdleCallback === 'function') requestIdleCallback(start, { timeout: 2000 });
else setTimeout(start, 0);
}, 250);
}
queueMicrotask(scheduleRuntimePrewarm);
'''
if source.count(anchor) != 1:
raise RuntimeError("resolvePartition anchor changed")
source = source.replace(anchor, prewarm + anchor, 1)
old_fetch = r''' state.intercepted_on_demand += 1;
if (init?.signal?.aborted) throw new DOMException('Aborted', 'AbortError');
const payload = await queryOnDemand(pathname);
if (init?.signal?.aborted) throw new DOMException('Aborted', 'AbortError');
return new Response(JSON.stringify(payload), {
status: 200,
headers: {
'Content-Type': 'application/geo+json; charset=utf-8',
'Cache-Control': 'private, max-age=3600',
'X-GridAtlas-Data-Plane': 'V9-PARQUET-DUCKDB-ON-DEMAND'
}
});'''
new_fetch = r''' state.intercepted_on_demand += 1;
if (init?.signal?.aborted) throw new DOMException('Aborted', 'AbortError');
// Return response headers before DuckDB imports, downloads, queries and serialises the body.
// This preserves the native fetch contract expected by the V8 engine: its 15 s timer protects
// response establishment, while response.json() may continue consuming a streamed body.
state.streamed_responses += 1;
const encoder = new TextEncoder();
let bodyController = null;
let aborted = false;
const abort = () => {
aborted = true;
try { bodyController?.error(new DOMException('Aborted', 'AbortError')); } catch {}
};
init?.signal?.addEventListener('abort', abort, { once: true });
const body = new ReadableStream({
start(controller) {
bodyController = controller;
queryOnDemand(pathname).then(payload => {
if (aborted || init?.signal?.aborted) return abort();
controller.enqueue(encoder.encode(JSON.stringify(payload)));
controller.close();
}).catch(error => {
state.stream_failures.push({ pathname, message: String(error?.message || error) });
try { controller.error(error); } catch {}
});
},
cancel() { aborted = true; }
});
return new Response(body, {
status: 200,
headers: {
'Content-Type': 'application/geo+json; charset=utf-8',
'Cache-Control': 'private, max-age=3600',
'X-GridAtlas-Data-Plane': 'V9-PARQUET-DUCKDB-STREAMED-RESPONSE'
}
});'''
if source.count(old_fetch) != 1:
raise RuntimeError("fetch bridge block changed or ambiguous")
source = source.replace(old_fetch, new_fetch, 1)
return source
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--generation", required=True)
parser.add_argument("--request", default="state/streaming-road-fix.json")
parser.add_argument("--report", default="work/streaming-road-build.json")
args = parser.parse_args()
generation = str(args.generation)
if not re.fullmatch(r"20\d{10}", generation):
raise RuntimeError(f"invalid UTC generation: {generation!r}")
request = load_json(ROOT / args.request)
if request.get("schema") != "gridatlas.streaming-road-fix-request.v1":
raise RuntimeError("request schema mismatch")
if request.get("composition_version") != "v9.5":
raise RuntimeError("request composition version mismatch")
current = load_json(CURRENT)
if current.get("schema") != "gridatlas.current.v2":
raise RuntimeError("current composition schema mismatch")
by_id = {item["id"]: item for item in current.get("cartridges", [])}
if SEARCH_ID not in by_id:
raise RuntimeError("v9.5 search cartridge is missing")
if TRANSPORT_ID in by_id:
report = {
"schema": "gridatlas.streaming-road-build.v1",
"status": "ALREADY_BUILT",
"generation": current.get("generation"),
"transport": by_id[TRANSPORT_ID],
}
dump_json(ROOT / args.report, report)
print(json.dumps(report, sort_keys=True))
return 0
shell_index = (ROOT / "atlas" / current["shell"]["index"]).resolve()
bridge_source = shell_index.parent / BRIDGE_SLOT
if not bridge_source.is_file():
raise RuntimeError(f"immutable bridge slot missing: {bridge_source}")
manifest = load_json((ROOT / "atlas" / current["composition_manifest"]).resolve())
expected_bridge_sha = manifest.get("shell", {}).get("hashes", {}).get("maplibre_worker_bridge")
source_bytes = bridge_source.read_bytes()
actual_bridge_sha = sha256_bytes(source_bytes)
if actual_bridge_sha != expected_bridge_sha:
raise RuntimeError(f"immutable bridge hash mismatch: {actual_bridge_sha} != {expected_bridge_sha}")
compiled = compile_bridge(source_bytes.decode("utf-8"), generation)
compiled_bytes = compiled.encode("utf-8")
cartridge_sha = sha256_bytes(compiled_bytes)
cartridge_rel = Path(f"atlas/cartridges/{generation}-streaming-parquet-bridge-v9-5.js")
cartridge_path = ROOT / cartridge_rel
if cartridge_path.exists() and cartridge_path.read_bytes() != compiled_bytes:
raise RuntimeError(f"immutable cartridge collision: {cartridge_rel}")
cartridge_path.parent.mkdir(parents=True, exist_ok=True)
cartridge_path.write_bytes(compiled_bytes)
contract_rel = Path(f"ui/cartridges/{generation}-streaming-parquet-bridge-v9-5.mjs")
contract_path = ROOT / contract_rel
contract_text = f"""export const STREAMING_PARQUET_BRIDGE_V9_5_CONTRACT = Object.freeze({{\n schema: 'gridatlas.cartridge.v1',\n generation: '{generation}',\n version: 'v9.5',\n slot: '{BRIDGE_SLOT}',\n responseEstablishedBeforeBodyReconstruction: true,\n duckdbPrewarm: 'after-critical-400kv-source',\n metroPartitionAlias: 'uk_metros_trams_root',\n immutableShellModified: false,\n ful … [line shortened here: 439 characters; full line on GitHub]
if contract_path.exists() and contract_path.read_text(encoding="utf-8") != contract_text:
raise RuntimeError(f"immutable contract collision: {contract_rel}")
contract_path.parent.mkdir(parents=True, exist_ok=True)
contract_path.write_text(contract_text, encoding="utf-8")
transport = {
"id": TRANSPORT_ID,
"generation": generation,
"version": "v9.5",
"type": "script",
"slot": "replace-script",
"replace_script": BRIDGE_SLOT,
"path": f"./cartridges/{cartridge_rel.name}",
"sha256": cartridge_sha,
"contract": f"../{contract_rel.as_posix()}",
"capabilities": [
"response-before-body-reconstruction",
"duckdb-runtime-prewarm-after-400kv",
"metro-partition-alias",
"parquet-on-demand-preserved",
],
"immutable_shell_modified": False,
}
search = copy.deepcopy(by_id[SEARCH_ID])
previous_generation = str(current["generation"])
new_current = copy.deepcopy(current)
new_current.update({
"generation": generation,
"previous_generation": previous_generation,
"composition_version": "v9.5",
"composition_id": f"{generation}-gridatlas-v9.5",
"cartridge_order": [TRANSPORT_ID, SEARCH_ID],
"cartridges": [transport, search],
"composition_manifest": f"./manifests/{generation}-composition.json",
})
new_current["transport"] = {
"response_contract": "HEADERS_BEFORE_PARQUET_BODY",
"engine_timeout_seconds": 15,
"duckdb_prewarm": "AFTER_400KV_SOURCE_READY",
"data_plane": "PARQUET_DUCKDB_ON_DEMAND",
"highway_layers": ["motorways", "trunk_roads", "primary_roads"],
"v8_oracle_commit": request["v8_oracle_commit"],
"fidelity_workflow": request["fidelity_workflow"],
}
new_current.setdefault("provenance", {})["cvaa_commit"] = request["cvaa_commit"]
new_current["provenance"]["v8_oracle_commit"] = request["v8_oracle_commit"]
new_current["scope_closure"] = {
"generation": generation,
"status": "DONE",
"scope": "GridAtlas v9.5 streamed Parquet response and A-road recovery",
"schedule_retired": True,
}
new_manifest = copy.deepcopy(manifest)
new_manifest.update({
"generation": generation,
"parent_generation": previous_generation,
"version": "v9.5",
"composition_id": f"{generation}-gridatlas-v9.5",
"cartridge_order": [TRANSPORT_ID, SEARCH_ID],
"cartridges": [transport, search],
})
acceptance = copy.deepcopy(new_manifest.get("acceptance", {}))
acceptance.update({
"full_application_copies_created": 0,
"immutable_shell_modified": False,
"parquet_on_demand_preserved": True,
"response_established_before_body_reconstruction": True,
"a_road_browser_budget_seconds": 15,
"a_road_heap_budget_mb": 400,
"v8_feature_hash_fidelity_required": True,
"search_cartridge_preserved": True,
"golden_browser_verification": "REQUIRED",
})
new_manifest["acceptance"] = acceptance
new_manifest["source_pattern"] = {
"repository": "Ventusltd/gridatlas",
"path": f"atlas/releases/{current['release_id']}/{BRIDGE_SLOT}",
"source_sha256": actual_bridge_sha,
"transformation": "return streamed Response before DuckDB body reconstruction; prewarm runtime after 400 kV readiness",
}
manifest_path = ROOT / f"atlas/manifests/{generation}-composition.json"
dump_json(manifest_path, new_manifest)
dump_json(CURRENT, new_current)
report = {
"schema": "gridatlas.streaming-road-build.v1",
"status": "BUILT",
"generation": generation,
"previous_generation": previous_generation,
"source_bridge": str(bridge_source.relative_to(ROOT)),
"source_bridge_sha256": actual_bridge_sha,
"transport_cartridge": str(cartridge_rel),
"transport_sha256": cartridge_sha,
"transport_contract": str(contract_rel),
"composition_manifest": str(manifest_path.relative_to(ROOT)),
"preserved_cartridge": search,
"full_application_copies_created": 0,
"immutable_shell_modified": False,
}
dump_json(ROOT / args.report, report)
print(json.dumps(report, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())