From 619628ed7eae2673099b4809c8b477cc70e0664a Mon Sep 17 00:00:00 2001 From: Quintin Botes Date: Mon, 30 Nov 2026 13:03:54 +0100 Subject: [PATCH 1/2] Link again only the Python modules a change reaches (#145) The Python linker emits its output per module and records what each module's link read in link_refs: the files whose symbols or bindings it looked up, and the layout keys its resolution read (mod:, top:, stem:). A re-map links again the changed modules, the modules that read a layout key of a Python file that came or went, the modules that read either, and modules with unused-member evidence; every other module reuses its kept output. Different source roots, an empty link_refs or a semantic index link every module. directories() and packFact/unpackFact move to link-state.mjs and are shared with the JavaScript linker; a packed `path:line` source ref is stored as the line number. The randomized test harness moves to tests/helpers/incremental-link.mjs. Co-Authored-By: Claude Opus 5.5 --- adapters/language/javascript/link.mjs | 29 +- adapters/language/python/link.mjs | 265 ++++++++++++------ runtime/graph/link-state.mjs | 23 ++ tests/helpers/incremental-link.mjs | 39 +++ .../adapters/javascript/incremental.test.mjs | 38 +-- .../unit/adapters/python/incremental.test.mjs | 100 +++++++ .../graph/incremental-python-link.test.mjs | 113 ++++++++ 7 files changed, 463 insertions(+), 144 deletions(-) create mode 100644 tests/helpers/incremental-link.mjs create mode 100644 tests/unit/adapters/python/incremental.test.mjs create mode 100644 tests/unit/graph/incremental-python-link.test.mjs diff --git a/adapters/language/javascript/link.mjs b/adapters/language/javascript/link.mjs index 3a46e6c..1553859 100644 --- a/adapters/language/javascript/link.mjs +++ b/adapters/language/javascript/link.mjs @@ -4,11 +4,12 @@ // Resolution is by name and path (no type information), so call and inheritance edges are // marked confidence 'medium'. -import { digest, sha256 } from '../../../runtime/core/canonical.mjs'; +import { digest } from '../../../runtime/core/canonical.mjs'; import { enclosingRoots } from '../../../runtime/core/paths.mjs'; import { linkFrameworks } from '../framework-link.mjs'; import { edgeFact, nodeFact, prov } from '../../../runtime/graph/facts.mjs'; import { LANGUAGE_IDS } from '../../../runtime/graph/languages.mjs'; +import { directories, packFact, unpackFact } from '../../../runtime/graph/link-state.mjs'; import { EXTRACTOR } from './config.mjs'; import { joinPath } from './frameworks.mjs'; import { createResolver, normalize as normalizePath } from './resolver.mjs'; @@ -21,29 +22,9 @@ const dirOf = (p) => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : ''); const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0); -/** directory -> signature of the file names in it: where files came or went since the last link. */ -function directories(files) { - const names = new Map(); - for (const p of files.keys()) { - const d = dirOf(p); - (names.get(d) ?? names.set(d, []).get(d)).push(p); - } - const out = {}; - for (const [d, ps] of names) out[d] = sha256(ps.sort().join('\0')).slice(0, 16); - return out; -} - -// A kept edge as a row: what P() and edgeFact always set (the extractor, empty scope and -// contradictions, the file's own module as source) is left out. -const packFact = (f, path) => (f.kind === 'edge' && f.provenance.extractor === EXTRACTOR && !f.provenance.scope.length && !f.provenance.contradicts.length - ? [f.type, f.from === `module:${path}` ? 0 : f.from, f.to, f.attrs, f.provenance.source_type, f.provenance.source_ref, f.provenance.confidence] - : f); -const unpackFact = (e, path) => (Array.isArray(e) - ? { kind: 'edge', type: e[0], from: e[1] === 0 ? `module:${path}` : e[1], to: e[2], attrs: e[3], provenance: { source_type: e[4], source_ref: e[5], extractor: EXTRACTOR, confidence: e[6], scope: [], contradicts: [] } } - : e); const mapRecord = (rec, fn) => Object.fromEntries(Object.entries(rec).map(([k, vs]) => [k, k === 'deps' ? vs : vs.map((v) => (k === 'renders' ? [v[0], fn(v[1])] : fn(v)))])); -const pack = (rec, path) => mapRecord(rec, (f) => packFact(f, path)); -const unpack = (rec, path) => mapRecord(rec, (f) => unpackFact(f, path)); +const pack = (rec, path) => mapRecord(rec, (f) => packFact(f, path, EXTRACTOR)); +const unpack = (rec, path) => mapRecord(rec, (f) => unpackFact(f, path, EXTRACTOR)); export function linkFacts(ctx) { const files = ctx.files; @@ -441,7 +422,7 @@ export function linkFacts(ctx) { let again = null; if (inc) { const env = digest({ tsconfigs: [...tsconfigs], packages, aliases }); - const listing = directories(files); + const listing = directories(files.keys()); const prev = inc.previous; const changed = prev?.env === env && !ctx.semantic?.size ? inc.changed : null; if (changed) { diff --git a/adapters/language/python/link.mjs b/adapters/language/python/link.mjs index 8119f36..ebe65b0 100644 --- a/adapters/language/python/link.mjs +++ b/adapters/language/python/link.mjs @@ -1,11 +1,14 @@ -// Cross-file linking for the Python adapter. Recomputed on every map from the cached -// per-file facts, so it only does map lookups: import resolution against source roots, -// call targets through import bindings, class inheritance, tests and package containment. +// Cross-file linking for the Python adapter. Works only from the cached per-file facts with map +// lookups: import resolution against source roots, call targets through import bindings, class +// inheritance, tests and package containment. A re-map links again only the files a change +// reaches (#145). +import { digest } from '../../../runtime/core/canonical.mjs'; import { enclosingRoots } from '../../../runtime/core/paths.mjs'; import { linkFrameworks } from '../framework-link.mjs'; import { edgeFact, nodeFact, prov } from '../../../runtime/graph/facts.mjs'; import { LANGUAGE_IDS, extensionsFor, languageForPath } from '../../../runtime/graph/languages.mjs'; +import { directories, packFact, unpackFact } from '../../../runtime/graph/link-state.mjs'; import { EXTRACTOR, isDjangoConventionPath } from './build.mjs'; import { normalizeRoute } from './frameworks.mjs'; import { MANIFEST_RE, manifestKind } from './manifests.mjs'; @@ -20,6 +23,7 @@ const cleanRoot = (r) => String(r).replace(/\\/g, '/').replace(/^\.?\/+|\/+$/g, const PYTHON_EXTENSIONS = extensionsFor([LANGUAGE_IDS.PYTHON]); const pythonExtension = (path) => PYTHON_EXTENSIONS.find((extension) => path.endsWith(extension)) ?? null; const pythonPath = (base) => `${base}${PYTHON_EXTENSIONS[0]}`; +const mapRecord = (rec, fn) => Object.fromEntries(Object.entries(rec).map(([k, fs]) => [k, fs.map(fn)])); /** Dotted module name of a file relative to a source root, or null when not importable. */ function dottedName(rel) { @@ -89,7 +93,24 @@ export function link(ctx) { tops.add(dotted.split('.')[0]); } } + // What a file's resolution reads of the module layout (#145): `mod:` a dotted name, `top:` a + // top-level package, `stem:` a relative or sibling candidate (a path without its extension or + // `/__init__`). A file added or removed there can change the answer. + let reads = null; + const layoutKeys = (path) => { + const keys = [`stem:${path.slice(0, -pythonExtension(path).length).replace(/(^|\/)__init__$/, '')}`]; + for (const root of sourceRoots(path)) { + const dotted = dottedName(root ? path.slice(root.length + 1) : path); + if (dotted) keys.push(`mod:${dotted}`, `top:${dotted.split('.')[0]}`); + } + return keys; + }; + const isTop = (top) => { + reads?.add(`top:${top}`); + return tops.has(top); + }; const resolveDotted = (dotted, importer) => { + reads?.add(`mod:${dotted}`); const first = index.get(dotted); if (!first?.byRoot) return first?.path ?? null; const roots = sourceRoots(importer); @@ -105,10 +126,13 @@ export function link(ctx) { const resolveAbsolute = (language, dotted, importer) => { const path = resolveDotted(dotted, importer); if (path) return { path, inferred: false }; - return STDLIB.has(dotted) ? null : resolveFlatSiblingImport(language, importer, dotted, pyPaths); + if (STDLIB.has(dotted)) return null; + reads?.add(`stem:${join(dirOf(importer), dotted)}`); + return resolveFlatSiblingImport(language, importer, dotted, pyPaths); }; const tryRel = (dir, parts) => { const base = join(dir, parts.join('/')); + reads?.add(`stem:${parts.length ? base : dir}`); const stems = parts.length ? [base, `${base}/__init__`] : [join(dir, '__init__')]; for (const cand of stems.flatMap((stem) => PYTHON_EXTENSIONS.map((extension) => `${stem}${extension}`))) { if (pyPaths.has(cand)) return cand; @@ -122,13 +146,21 @@ export function link(ctx) { : prov({ source_type: 'ast', source_ref: `${path}:${line}`, extractor: EXTRACTOR, confidence })); const inferredPv = (path, line) => prov({ source_type: 'inference', source_ref: `${path}:${line}`, extractor: EXTRACTOR, confidence: 'low' }); - // --- imports: bindings, IMPORTS edges, external dependencies --------------------------- - const bindings = new Map(); // path -> Map - const importedModules = new Map(); // test path -> sorted import targets - for (const path of orderedModules) { + // The other files the file being linked reads (#145): it is linked again when one changes. + let refs = null; + + // --- imports: bindings and their targets, external dependencies ---------------------- + const bindings = new Map(); // path -> { bind: Map, targets, externals, reads } | null + // Another module's bindings are read only after its symbols (resolveName), which records it in refs. + function bindingsOf(path) { + if (bindings.has(path)) return bindings.get(path); const mod = modules.get(path); + if (!mod) { + bindings.set(path, null); + return null; + } + reads = new Set(); const bind = new Map(); - bindings.set(path, bind); const targets = new Map(); // target path -> { names, line } const externals = new Map(); // dependency id -> { top, line, stdlib } const a = mod.attrs; @@ -149,7 +181,7 @@ export function link(ctx) { if (!externals.has(id)) externals.set(id, { top, line, stdlib }); }; - for (const imp of mod.attrs.imports ?? []) { + for (const imp of a.imports ?? []) { cur = imp; const parts = imp.module ? imp.module.split('.') : []; if (imp.level > 0) { @@ -176,7 +208,7 @@ export function link(ctx) { resolved = resolveAbsolute(a.language, parts.slice(0, len).join('.'), path); if (resolved) { resolvedLen = len; break; } } - if (!resolved) { if (!tops.has(parts[0])) external(parts[0], imp.line); continue; } + if (!resolved) { if (!isTop(parts[0])) external(parts[0], imp.line); continue; } internal(resolved.path, imp.line, null, resolved.inferred); if (imp.as && resolvedLen === parts.length) bind.set(imp.as, { path: resolved.path, symbol: null }); else if (!imp.as) { @@ -199,68 +231,13 @@ export function link(ctx) { internal(target.path, imp.line, n.name, target.inferred); } } - if (!any && !tops.has(parts[0])) external(parts[0], imp.line); + if (!any && !isTop(parts[0])) external(parts[0], imp.line); else if (target && !imp.names.length) internal(target.path, imp.line, null, target.inferred); } - - const moduleId = `module:${path}`; - // A type held only through a member nothing reads (members.mjs): every name imported from a - // module must be such a type, and nothing may import it for its effects or by `*`. - const sem = ctx.semantic?.get(path) ?? null; - const found = new Map(); // target path -> what the file's members say - if (a.refs && a.decl_only && !sem) { - const bound = new Map(); - for (const [local, b] of bind) { - if (b.path === path) continue; - bound.set(b.path, (bound.get(b.path) ?? 0) + 1); - let h = found.get(b.path); - if (!h) found.set(b.path, (h = { spec: local, decl: true, members: new Set(), pub: new Set() })); - if (b.symbol && Object.hasOwn(a.decl_only, local)) { - for (const m of a.decl_only[local].split(', ')) h.members.add(m); - if (a.decl_public && Object.hasOwn(a.decl_public, local)) { - for (const m of a.decl_public[local]) h.pub.add(m); - } - } else h.decl = false; - } - for (const [target, t] of targets) if (found.has(target) && bound.get(target) !== t.names.length) found.get(target).decl = false; - } - const sorted = [...targets].sort((x, y) => (x[0] < y[0] ? -1 : 1)); - if (a.is_test) importedModules.set(path, sorted.map(([target]) => target)); - const items = sorted.map(([target, t]) => ({ - to: target, - line: t.line, - attrs: { names: [...new Set(t.names)].sort(), line: t.line, ...(t.lazy && { lazy: true }), ...(t.typeOnly && { type_only: true }), ...(t.inferred && { inferred: true, via: 'flat-sibling' }), ...(found.has(target) && declaredEdge(path, found.get(target), a.public_owners ?? {}, reach, MEMBER_SYNTAX.python).attrs) }, - inferred: t.inferred, - })); - for (const e of withSemantic(sem, items)) { - let attrs = e.attrs; - if (attrs.via === 'type') { - const { spec, via, ...rest } = attrs; - attrs = { names: [spec].filter(Boolean), line: e.line, ...rest }; - } - emit(edgeFact('IMPORTS', moduleId, `module:${e.to}`, attrs, e.semantic - ? prov({ source_type: 'lsp', source_ref: `${path}:${e.line}`, extractor: EXTRACTOR, confidence: 'high' }) - : e.inferred ? inferredPv(path, e.line) : pvFor(path, e.line))); - } - dropMemberAttrs(a); - for (const [id, e] of [...externals].sort((a, b) => (a[0] < b[0] ? -1 : 1))) { - emit(nodeFact('dependency', id.slice('dependency:'.length), { - name: id.slice('dependency:'.length), - attrs: { ecosystem: e.stdlib ? 'python-stdlib' : 'pypi' }, - }, pvFor(path, e.line))); - emit(edgeFact('IMPORTS', moduleId, id, { line: e.line, external: true, stdlib: e.stdlib }, pvFor(path, e.line))); - } - } - - // --- Django conventions that need the project layout (manage.py, sibling apps.py) ------ - const managePath = pythonPath('manage'); - const appsPath = pythonPath('apps'); - const hasManage = [...pyPaths].some((p) => p === managePath || p.endsWith(`/${managePath}`)); - for (const [path, mod] of modules) { - if (mod.attrs.django_convention || !isDjangoConventionPath(path)) continue; - const base = path.slice(path.lastIndexOf('/') + 1); - const sibling = [appsPath, pythonPath('admin'), pythonPath('models'), pythonPath('urls')].includes(base) && pyPaths.has(join(dirOf(path), appsPath)); - if (hasManage || sibling) emit(nodeFact('module', path, { name: path, path, attrs: { django_convention: true } }, pvFor(path, 1, 'medium'))); + const b = { bind, targets, externals, reads }; + reads = null; + bindings.set(path, b); + return b; } // --- name resolution ----------------------------------------------------------------- @@ -268,6 +245,7 @@ export function link(ctx) { // symbol index from all its extractors the first time name resolution needs it. const symbols = new Map(); const symbolsOf = (path) => { + refs?.add(path); if (!symbols.has(path)) { const names = new Map(); for (const f of factsByFile.get(path) ?? []) { @@ -283,7 +261,7 @@ export function link(ctx) { /** Where a dotted name used in `path` points: { path, qual } or null. */ const resolveName = (path, name) => { if (symbolsOf(path).has(name)) return { path, qual: name }; - const bind = bindings.get(path); + const bind = bindingsOf(path)?.bind; if (!bind) return null; const parts = name.split('.'); for (let len = parts.length; len > 0; len--) { @@ -317,8 +295,56 @@ export function link(ctx) { return null; }; - // --- CALLS, EXTENDS, Django view exposure -------------------------------------------- - for (const path of orderedModules) { + /** One module's share of the output, by section: internal and external IMPORTS, CALLS (with EXTENDS and EXPOSES), TESTS. */ + function linkOne(path) { + const rec = {}; + const add = (k, f) => (rec[k] ??= []).push(f); + const a = modules.get(path).attrs; + const { bind, targets, externals, reads: keys } = bindingsOf(path); + for (const k of keys) refs?.add(k); + const moduleId = `module:${path}`; + // A type held only through a member nothing reads (members.mjs): every name imported from a + // module must be such a type, and nothing may import it for its effects or by `*`. + const sem = ctx.semantic?.get(path) ?? null; + const found = new Map(); // target path -> what the file's members say + if (a.refs && a.decl_only && !sem) { + const bound = new Map(); + for (const [local, b] of bind) { + if (b.path === path) continue; + bound.set(b.path, (bound.get(b.path) ?? 0) + 1); + let h = found.get(b.path); + if (!h) found.set(b.path, (h = { spec: local, decl: true, members: new Set(), pub: new Set() })); + if (b.symbol && Object.hasOwn(a.decl_only, local)) { + for (const m of a.decl_only[local].split(', ')) h.members.add(m); + if (a.decl_public && Object.hasOwn(a.decl_public, local)) { + for (const m of a.decl_public[local]) h.pub.add(m); + } + } else h.decl = false; + } + for (const [target, t] of targets) if (found.has(target) && bound.get(target) !== t.names.length) found.get(target).decl = false; + } + const sorted = [...targets].sort((x, y) => (x[0] < y[0] ? -1 : 1)); + const items = sorted.map(([target, t]) => ({ + to: target, + line: t.line, + attrs: { names: [...new Set(t.names)].sort(), line: t.line, ...(t.lazy && { lazy: true }), ...(t.typeOnly && { type_only: true }), ...(t.inferred && { inferred: true, via: 'flat-sibling' }), ...(found.has(target) && declaredEdge(path, found.get(target), a.public_owners ?? {}, reach, MEMBER_SYNTAX.python).attrs) }, + inferred: t.inferred, + })); + for (const e of withSemantic(sem, items)) { + let attrs = e.attrs; + if (attrs.via === 'type') { + const { spec, via, ...rest } = attrs; + attrs = { names: [spec].filter(Boolean), line: e.line, ...rest }; + } + add('imports', edgeFact('IMPORTS', moduleId, `module:${e.to}`, attrs, e.semantic + ? prov({ source_type: 'lsp', source_ref: `${path}:${e.line}`, extractor: EXTRACTOR, confidence: 'high' }) + : e.inferred ? inferredPv(path, e.line) : pvFor(path, e.line))); + } + for (const [id, e] of [...externals].sort((a, b) => (a[0] < b[0] ? -1 : 1))) { + add('external', edgeFact('IMPORTS', moduleId, id, { line: e.line, external: true, stdlib: e.stdlib }, pvFor(path, e.line))); + } + + // --- CALLS, EXTENDS, Django view exposure ------------------------------------------ for (const f of factsByFile.get(path)) { if (f.kind === 'node' && (f.type === 'function' || f.type === 'method')) { const cls = f.attrs.class; @@ -332,7 +358,7 @@ export function link(ctx) { if (r) target = lookup(r.path, r.qual); } if (target && target !== f.id && !target.startsWith('class:')) { - emit(edgeFact('CALLS', f.id, target, { callee: call }, pvFor(path, f.attrs.start_line, 'medium'))); + add('calls', edgeFact('CALLS', f.id, target, { callee: call }, pvFor(path, f.attrs.start_line, 'medium'))); } } } else if (f.kind === 'node' && f.type === 'class') { @@ -340,25 +366,98 @@ export function link(ctx) { const r = resolveName(path, b); const target = r ? lookup(r.path, r.qual) : null; if (target?.startsWith('class:') && target !== f.id) { - emit(edgeFact('EXTENDS', f.id, target, { base: b }, pvFor(path, f.attrs.start_line))); + add('calls', edgeFact('EXTENDS', f.id, target, { base: b }, pvFor(path, f.attrs.start_line))); } } } else if (f.kind === 'edge' && f.type === 'EXPOSES' && f.attrs.view && f.from.startsWith('module:')) { const r = resolveName(path, f.attrs.view); const target = r ? lookup(r.path, r.qual) : null; - if (target) emit(edgeFact('EXPOSES', target, f.to, { framework: f.attrs.framework }, f.provenance)); + if (target) add('calls', edgeFact('EXPOSES', target, f.to, { framework: f.attrs.framework }, f.provenance)); + } + } + + // --- TESTS ------------------------------------------------------------------------- + if (a.is_test) { + for (const [target] of sorted) { + refs?.add(target); + if (modules.get(target)?.attrs.is_test) continue; + add('tests', edgeFact('TESTS', moduleId, `module:${target}`, {}, pvFor(path, 1))); } } + return rec; } - // --- TESTS --------------------------------------------------------------------------- - for (const [path, mod] of modules) { - if (!mod.attrs.is_test) continue; - for (const target of importedModules.get(path)) { - if (modules.get(target)?.attrs.is_test) continue; - emit(edgeFact('TESTS', `module:${path}`, `module:${target}`, {}, pvFor(path, 1))); + // Incremental (#145): each module's share of the output is kept with what it read (link_refs): + // the files whose symbols or bindings it looked up, and the layout keys its resolution read. A + // module is linked again when it changed, when a file it read changed or was linked again for a + // layout key, or when a file came or went where its resolution looked. Modules with unused-member + // evidence read every module's member accesses and are always linked again. A change to the + // source roots or a semantic index links every module. + const inc = ctx.incremental; + let again = null; + if (inc) { + const env = digest([...roots].sort()); + const listing = directories(pyPaths); + const prev = inc.previous; + const changed = prev?.env === env && !ctx.semantic?.size ? inc.changed : null; + if (changed) { + const moved = new Set([...Object.keys(prev.dirs), ...Object.keys(listing)].filter((d) => prev.dirs[d] !== listing[d])); + const probed = inc.refsTo([...changed].filter((p) => pythonExtension(p) && moved.has(dirOf(p))).flatMap(layoutKeys)); + const reached = probed && inc.refsTo([...changed, ...probed]); + if (reached) again = new Set([...changed, ...probed, ...reached, ...orderedModules.filter((p) => modules.get(p).attrs.decl_only)]); + } + inc.save({ env, dirs: listing }); + } + const kept = again ? inc.files() : new Map(); + const records = new Map(); + const linkedNow = new Map(); + const readNow = new Map(); + for (const path of orderedModules) { + const prior = again && !again.has(path) ? kept.get(path) : undefined; + if (prior) { + records.set(path, mapRecord(prior, (e) => unpackFact(e, path, EXTRACTOR))); + continue; } + refs = inc ? new Set() : null; + const rec = linkOne(path); + records.set(path, rec); + if (!inc) continue; + refs.delete(path); + linkedNow.set(path, mapRecord(rec, (f) => packFact(f, path, EXTRACTOR))); + readNow.set(path, [...refs]); } + refs = null; + if (inc) { + inc.saveFiles(linkedNow); + inc.saveRefs(readNow); + if (ctx.stats) (ctx.stats.link ??= {}).python = { relinked: linkedNow.size, files: orderedModules.length }; + } + for (const m of modules.values()) dropMemberAttrs(m.attrs); + + // Merge in the order one pass over every module emits. + for (const path of orderedModules) { + const rec = records.get(path); + for (const f of rec.imports ?? []) emit(f); + for (const f of rec.external ?? []) { + const name = f.to.slice('dependency:'.length); + emit(nodeFact('dependency', name, { name, attrs: { ecosystem: f.attrs.stdlib ? 'python-stdlib' : 'pypi' } }, pvFor(path, f.attrs.line))); + emit(f); + } + } + + // --- Django conventions that need the project layout (manage.py, sibling apps.py) ------ + const managePath = pythonPath('manage'); + const appsPath = pythonPath('apps'); + const hasManage = [...pyPaths].some((p) => p === managePath || p.endsWith(`/${managePath}`)); + for (const [path, mod] of modules) { + if (mod.attrs.django_convention || !isDjangoConventionPath(path)) continue; + const base = path.slice(path.lastIndexOf('/') + 1); + const sibling = [appsPath, pythonPath('admin'), pythonPath('models'), pythonPath('urls')].includes(base) && pyPaths.has(join(dirOf(path), appsPath)); + if (hasManage || sibling) emit(nodeFact('module', path, { name: path, path, attrs: { django_convention: true } }, pvFor(path, 1, 'medium'))); + } + + for (const path of orderedModules) for (const f of records.get(path).calls ?? []) emit(f); + for (const path of modules.keys()) for (const f of records.get(path).tests ?? []) emit(f); // --- package containment --------------------------------------------------------------- const rank = { pyproject: 0, 'setup.cfg': 1, 'setup.py': 2 }; diff --git a/runtime/graph/link-state.mjs b/runtime/graph/link-state.mjs index a3e841e..d71e380 100644 --- a/runtime/graph/link-state.mjs +++ b/runtime/graph/link-state.mjs @@ -2,6 +2,7 @@ // Linkers in the same map share the snapshot, but can have different previous snapshots // after a partial map. A missing artifact means that linker must recompute its result. import { brotliCompressSync, brotliDecompressSync, constants } from 'node:zlib'; +import { sha256 } from '../core/canonical.mjs'; import { casDrop, casGet, casPut } from '../state/cas.mjs'; import { readExtraction, storedExtractions } from '../state/extraction-cache.mjs'; import { cacheJSONBytes, packCacheJSON, putCacheJSON } from './cache-json.mjs'; @@ -135,3 +136,25 @@ function writeRefs(store, id, entries, stale) { const put = store.db.prepare('INSERT OR IGNORE INTO link_refs(adapter, from_p, to_p) VALUES (?, ?, ?)'); for (const [from, tos] of entries) for (const to of tos) put.run(id, from, to); } + +/** directory -> signature of the paths in it: where files came or went since the last link. */ +export function directories(paths) { + const names = new Map(); + for (const p of paths) { + const d = p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : ''; + (names.get(d) ?? names.set(d, []).get(d)).push(p); + } + const out = {}; + for (const [d, ps] of names) out[d] = sha256(ps.sort().join('\0')).slice(0, 16); + return out; +} + +// A kept edge as a row: what prov() and edgeFact always set (the extractor, empty scope and +// contradictions, the file's own module as source, the file's own path in `path:line`) is left out. +const lineOf = (ref, path) => (ref?.startsWith(`${path}:`) && /^\d+$/.test(ref.slice(path.length + 1)) ? Number(ref.slice(path.length + 1)) : ref); +export const packFact = (f, path, extractor) => (f.kind === 'edge' && f.provenance.extractor === extractor && !f.provenance.scope.length && !f.provenance.contradicts.length + ? [f.type, f.from === `module:${path}` ? 0 : f.from, f.to, f.attrs, f.provenance.source_type, lineOf(f.provenance.source_ref, path), f.provenance.confidence] + : f); +export const unpackFact = (e, path, extractor) => (Array.isArray(e) + ? { kind: 'edge', type: e[0], from: e[1] === 0 ? `module:${path}` : e[1], to: e[2], attrs: e[3], provenance: { source_type: e[4], source_ref: typeof e[5] === 'number' ? `${path}:${e[5]}` : e[5], extractor, confidence: e[6], scope: [], contradicts: [] } } + : e); diff --git a/tests/helpers/incremental-link.mjs b/tests/helpers/incremental-link.mjs new file mode 100644 index 0000000..2793cd1 --- /dev/null +++ b/tests/helpers/incremental-link.mjs @@ -0,0 +1,39 @@ +// Shared plumbing for the randomized incremental-link tests (#145). + +/** In-memory stand-in for runtime/graph/link-state.mjs: one publication, replaced on commit. */ +export function memory() { + let state = null; + return (factsByFile) => { + const inputs = new Map([...factsByFile].map(([p, f]) => [p, JSON.stringify(f)])); + const changed = state && new Set([...inputs.keys(), ...state.inputs.keys()].filter((p) => inputs.get(p) !== state.inputs.get(p))); + const copy = (v) => JSON.parse(JSON.stringify(v)); + let next, files, refs, selective = false; + return { + inc: { + previous: state?.data ?? null, + changed, + files: () => { selective = true; return new Map([...state.files].map(([p, r]) => [p, copy(r)])); }, + save: (d) => { next = d; }, + saveFiles: (m) => { files = m; }, + saveRefs: (m) => { refs = m; }, + refsTo: (keys) => new Set([...state.refs].filter(([, tos]) => tos.some((t) => keys.includes(t))).map(([from]) => from)), + }, + commit() { + const kept = selective ? [...state.files].filter(([p]) => inputs.has(p)) : []; + const read = selective ? [...state.refs].filter(([p]) => !changed.has(p) && !refs.has(p)) : []; + state = { data: copy(next), inputs, files: new Map([...kept, ...[...files].map(([p, r]) => [p, copy(r)])]), refs: new Map([...read, ...refs]) }; + }, + }; + }; +} + +/** mulberry32. */ +export function rng(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = Math.imul(a ^ (a >>> 15), a | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} diff --git a/tests/unit/adapters/javascript/incremental.test.mjs b/tests/unit/adapters/javascript/incremental.test.mjs index bdb1350..93cc9ec 100644 --- a/tests/unit/adapters/javascript/incremental.test.mjs +++ b/tests/unit/adapters/javascript/incremental.test.mjs @@ -6,43 +6,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import adapter from '../../../../adapters/language/javascript/index.mjs'; import { censusEntry } from './helpers.mjs'; - -/** In-memory stand-in for runtime/graph/link-state.mjs: one publication, replaced on commit. */ -function memory() { - let state = null; - return (factsByFile) => { - const inputs = new Map([...factsByFile].map(([p, f]) => [p, JSON.stringify(f)])); - const changed = state && new Set([...inputs.keys(), ...state.inputs.keys()].filter((p) => inputs.get(p) !== state.inputs.get(p))); - const copy = (v) => JSON.parse(JSON.stringify(v)); - let next, files, refs, selective = false; - return { - inc: { - previous: state?.data ?? null, - changed, - files: () => { selective = true; return new Map([...state.files].map(([p, r]) => [p, copy(r)])); }, - save: (d) => { next = d; }, - saveFiles: (m) => { files = m; }, - saveRefs: (m) => { refs = m; }, - refsTo: (keys) => new Set([...state.refs].filter(([, tos]) => tos.some((t) => keys.includes(t))).map(([from]) => from)), - }, - commit() { - const kept = selective ? [...state.files].filter(([p]) => inputs.has(p)) : []; - const read = selective ? [...state.refs].filter(([p]) => !changed.has(p) && !refs.has(p)) : []; - state = { data: copy(next), inputs, files: new Map([...kept, ...[...files].map(([p, r]) => [p, copy(r)])]), refs: new Map([...read, ...refs]) }; - }, - }; - }; -} - -function rng(seed) { - let a = seed >>> 0; - return () => { - a = (a + 0x6d2b79f5) >>> 0; - let t = Math.imul(a ^ (a >>> 15), a | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} +import { memory, rng } from '../../../helpers/incremental-link.mjs'; const DIRS = ['a', 'a/b', 'c']; const STEMS = DIRS.flatMap((d) => [0, 1, 2, 3].map((n) => `${d}/m${n}`)); diff --git a/tests/unit/adapters/python/incremental.test.mjs b/tests/unit/adapters/python/incremental.test.mjs new file mode 100644 index 0000000..d04cf69 --- /dev/null +++ b/tests/unit/adapters/python/incremental.test.mjs @@ -0,0 +1,100 @@ +// Randomized differential test of the incremental Python link (#145): over random edits (modules +// added, deleted and rewritten, `__init__` re-exports, absolute, relative and sibling imports, +// `import *`, namespace packages that come and go, imports of modules that do not exist yet, +// cycles, inheritance across modules, a manifest that moves the source roots), linking with the +// kept per-file results and link_refs returns exactly what a cold link of the same facts returns, +// and leaves the same input facts. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import adapter from '../../../../adapters/language/python/index.mjs'; +import { memory, rng } from '../../../helpers/incremental-link.mjs'; + +const DIRS = ['pkg', 'pkg/sub', 'ns', 'other']; +const STEMS = DIRS.flatMap((d) => [0, 1, 2].map((n) => `${d}/m${n}`)); +const dotted = (p) => p.replace(/\//g, '.'); + +function source(path, r) { + const pick = (xs) => xs[Math.floor(r() * xs.length)]; + const name = () => pick(['e0', 'e1', 'K']); + const m = () => `m${Math.floor(r() * 3)}`; + const lines = []; + const n = 1 + Math.floor(r() * 3); + for (let i = 0; i < n; i++) { + const s = pick(STEMS); + const roll = r(); + if (roll < 0.3) lines.push(`from ${dotted(s)} import ${name()} as v${i}`); + else if (roll < 0.4) lines.push(`from ${dotted(s.slice(0, s.lastIndexOf('/')))} import ${pick([name(), m()])} as v${i}`); + else if (roll < 0.5) lines.push(`from . import ${m()} as v${i}`); + else if (roll < 0.6) lines.push(`from .. import ${m()} as v${i}`); + else if (roll < 0.7) lines.push(`from .${pick([m(), `sub.${m()}`])} import ${name()} as v${i}`); + else if (roll < 0.8) lines.push(`from ..${pick(['other', 'pkg', 'ns'])}.${m()} import ${name()} as v${i}`); + else if (roll < 0.9) lines.push(`import ${m()} as v${i}`); + else lines.push(`from ${dotted(s)} import *`, `import ${dotted(s)} as v${i}`); + } + if (r() < 0.2) lines.push(`import ${dotted(pick(STEMS))}`); + const v = () => `v${Math.floor(r() * n)}`; + for (const e of ['e0', 'e1']) if (r() < 0.6) lines.push(`def ${e}():`, ` return ${pick([`${v()}()`, `${v()}.${name()}()`, 'e0()'])}`); + if (r() < 0.6) { + lines.push(`class K(${pick([v(), `${v()}.K`])}):`, ' def run(self):', ' return self.base()'); + if (r() < 0.4) lines.push(' def base(self):', ' return 1'); + } + // Unused-member evidence: a member held through an imported type, read (or not) in any module. + if (r() < 0.3) lines.push(`from ${dotted(pick(STEMS))} import K as Held`, 'class S:', ' def __init__(self, held: Held) -> None:', ' self.held = held'); + if (r() < 0.06) lines.push(`def use(x: ${pick(['S', 'K'])}):`, ' return x.held'); + return lines.join('\n') + '\n'; +} + +// `tests` stands in for the census classifying a module as test code. +function link(texts, tests, inc, stats = {}) { + const files = new Map(); + const factsByFile = new Map(); + for (const [path, text] of [...texts].sort((a, b) => (a[0] < b[0] ? -1 : 1))) { + files.set(path, { path }); + const facts = adapter.extract({ path }, text); + for (const f of facts) if (tests.has(path) && f.type === 'module') f.attrs.is_test = true; + factsByFile.set(path, facts); + } + const parsed = JSON.parse(JSON.stringify([...factsByFile])); + const run = inc?.(new Map(parsed)); + const facts = new Map(parsed); + const out = adapter.link({ files, factsByFile: facts, options: {}, stats, incremental: run?.inc }); + run?.commit(); + return JSON.stringify([out, [...facts]]); +} + +test('an incremental Python link equals a cold link over random edits (#145)', () => { + let relinked = 0, linked = 0; + for (const seed of [1, 2, 3, 4, 5, 6, 7, 8]) { + const r = rng(seed); + const texts = new Map(); + const tests = new Set(); + const inc = memory(); + const pathOf = () => { + const stem = STEMS[Math.floor(r() * STEMS.length)]; + return r() < 0.15 ? `${stem.slice(0, stem.lastIndexOf('/'))}/__init__.py` : `${stem}.py${r() < 0.05 ? 'i' : ''}`; + }; + for (let i = 0; i < 12; i++) texts.set(pathOf(), ''); + for (const p of texts.keys()) texts.set(p, source(p, r)); + for (let step = 0; step < 40; step++) { + const edits = 1 + Math.floor(r() * 3); + for (let e = 0; e < edits; e++) { + const roll = r(); + const existing = [...texts.keys()]; + const p = roll < 0.3 && existing.length > 3 ? existing[Math.floor(r() * existing.length)] : pathOf(); + if (roll < 0.22 && existing.length > 3) texts.delete(p); + else if (roll < 0.3 && existing.length > 3) { + if (!tests.delete(p)) tests.add(p); + } else if (roll < 0.33) { + // A manifest moves the source roots: `other` (and `other/src`) become roots, or stop being ones. + if (texts.has('other/pyproject.toml')) texts.delete('other/pyproject.toml'); + else texts.set('other/pyproject.toml', '[project]\nname = "other"\n'); + } else texts.set(p, source(p, r)); + } + const stats = {}; + assert.equal(link(texts, tests, inc, stats), link(texts, tests), `seed ${seed}, step ${step}`); + relinked += stats.link.python.relinked; + linked += stats.link.python.files; + } + } + assert.ok(relinked < linked * 0.7, `files keep their link (${relinked} of ${linked} linked again)`); +}); diff --git a/tests/unit/graph/incremental-python-link.test.mjs b/tests/unit/graph/incremental-python-link.test.mjs new file mode 100644 index 0000000..81a8759 --- /dev/null +++ b/tests/unit/graph/incremental-python-link.test.mjs @@ -0,0 +1,113 @@ +// The Python linker links again only the modules a change reaches (#145): the changed modules, the +// modules whose link read them (link_refs), and the modules whose resolution looked where a module +// came or went. Each step is compared, row by row, with a cold map of the tree as it then is, on the +// cases that break a naive reuse: a deleted module, a renamed `__init__` re-export, relative imports +// across packages, a new module that satisfies an unresolved import, `import *`, a namespace package +// that appears, an import cycle, and a base class found through another module's imports. +import assert from 'node:assert/strict'; +import { after, test } from 'node:test'; +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import * as K from '../../helpers/kernel.mjs'; +import { mapRepository } from '../../../runtime/graph/builder.mjs'; + +after(() => K.cleanup()); + +const config = K.cfg({ mode: 'plan' }); +const map = (p) => mapRepository(p.ctx, { config, configDigest: 'd', history: false }); + +function dump(ctx) { + const all = (sql) => ctx.store.all(sql).map((r) => ({ ...r })); + return { + nodes: all('SELECT * FROM nodes ORDER BY id'), + edges: all('SELECT * FROM edges ORDER BY id'), + facts: all('SELECT id, kind, subject, predicate, object, attrs, source_type, source_ref, extractor, confidence, scope, contradicts, path, expires_at, digest FROM facts ORDER BY id'), + derived: all("SELECT kind, key, body FROM derived WHERE kind != '_done' ORDER BY kind, key, body"), + }; +} + +const write = (dir, path, body) => { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), body); +}; + +const N = 40; +const chain = (i) => `from lib.f${(i + 1) % N} import f${(i + 1) % N}\n\n\ndef f${i}(x):\n return f${(i + 1) % N}(x - 1) if x > ${i} else ${i}\n`; +const tree = { + 'pkg/__init__.py': 'from .impl import thing\n', + 'pkg/impl.py': 'def thing():\n return 1\n', + 'pkg/q.py': 'from .base import Root as B\n\n\nclass Mid(B):\n pass\n', + 'pkg/sub/rel.py': 'from ..impl import thing\nfrom .. import impl\n\n\ndef rel():\n return thing() + impl.thing()\n', + 'app/use.py': 'from pkg import thing\n\n\ndef use():\n return thing()\n', + 'app/leaf.py': 'from pkg.q import Mid\n\n\nclass Leaf(Mid):\n def run(self):\n return self.base()\n', + 'app/star.py': 'from pkg.impl import *\n\n\ndef star():\n return thing()\n', + 'app/wants.py': 'from later.mod import go\nimport ns.tool\n\n\ndef wants():\n return go() + ns.tool.make()\n', + 'cyc/a.py': 'from cyc.b import fb\n\n\ndef fa():\n return fb()\n', + 'cyc/b.py': 'from cyc.a import fa\n\n\ndef fb():\n return fa()\n', + ...Object.fromEntries(Array.from({ length: N }, (_, i) => [`lib/f${i}.py`, chain(i)])), +}; + +test('an incremental Python link stores what a cold map stores, linking again only what a change reaches (#145)', async () => { + const files = { ...tree }; + const p = K.makeProject({ files }); + const first = await map(p); + const total = first.link.python.files; + assert.equal(first.link.python.relinked, total, 'the first map links every module'); + assert.ok(p.ctx.store.get("SELECT COUNT(*) AS n FROM link_refs WHERE adapter = 'python'").n > 0); + + const step = async (name, edit) => { + edit(files); + for (const [path, body] of Object.entries(files)) write(p.dir, path, body); + K.git(p.dir, 'add', '-A'); + K.git(p.dir, 'commit', '-q', '-m', name); + const delta = await map(p); + const cold = K.makeProject({ files }); + await map(cold); + const a = dump(p.ctx); + const b = dump(cold.ctx); + for (const k of Object.keys(b)) assert.deepEqual(a[k], b[k], `${name}: ${k} match a cold map`); + return delta.link.python; + }; + const del = (path) => (f) => { + delete f[path]; + rmSync(join(p.dir, path)); + }; + const edges = (src) => p.ctx.store.all("SELECT type, dst FROM edges WHERE src = ? AND type != 'CONTAINS' ORDER BY type, dst", src).map((r) => `${r.type} ${r.dst}`); + + const ten = await step('ten modules edited', (f) => { for (let i = 0; i < 10; i++) f[`lib/f${i * 4}.py`] += `\n\ndef touched${i}():\n return ${i}\n`; }); + // Each edited module and the one module that calls into it. + assert.equal(ten.relinked, 20, `ten edits link their callers again, not every module (${JSON.stringify(ten)})`); + + const based = await step('a base class appears behind another module\'s import', (f) => { f['pkg/base.py'] = 'class Root:\n def base(self):\n return 1\n'; }); + assert.ok(based.relinked < total, JSON.stringify(based)); + assert.deepEqual(edges('method:app/leaf.py#Leaf.run'), ['CALLS method:pkg/base.py#Root.base']); + + await step('a renamed __init__ re-export', (f) => { + f['pkg/impl.py'] = 'def thing2():\n return 1\n'; + f['pkg/__init__.py'] = 'from .impl import thing2\n'; + }); + await step('a deleted module', del('pkg/impl.py')); + assert.deepEqual(edges('module:pkg/sub/rel.py'), ['IMPORTS module:pkg/__init__.py'], 'rel.py no longer imports impl'); + + await step('a relative import target becomes a package', (f) => { f['pkg/impl/__init__.py'] = 'def thing():\n return 3\n'; }); + assert.deepEqual(edges('function:pkg/sub/rel.py#rel'), ['CALLS function:pkg/impl/__init__.py#thing']); + assert.ok(edges('module:app/star.py').includes('IMPORTS module:pkg/impl/__init__.py'), 'import * finds the package'); + + const satisfied = await step('new modules satisfy unresolved imports, one in a namespace package', (f) => { + f['later/mod.py'] = 'def go():\n return 4\n'; + f['ns/tool.py'] = 'def make():\n return 5\n'; + }); + assert.ok(satisfied.relinked < total, JSON.stringify(satisfied)); + assert.deepEqual(edges('module:app/wants.py'), ['IMPORTS module:later/mod.py', 'IMPORTS module:ns/tool.py']); + assert.deepEqual(edges('function:app/wants.py#wants'), ['CALLS function:later/mod.py#go', 'CALLS function:ns/tool.py#make']); + + await step('a name in an import cycle is renamed', (f) => { f['cyc/b.py'] = 'from cyc.a import fa\n\n\ndef fb2():\n return fa()\n'; }); + assert.deepEqual(edges('function:cyc/a.py#fa'), []); + + const rooted = await step('a pyproject moves the source roots and links every module again', (f) => { f['lib/pyproject.toml'] = '[project]\nname = "lib"\n'; }); + assert.equal(rooted.relinked, rooted.files); + + p.ctx.store.run('DELETE FROM link_refs'); + const missing = await step('missing link_refs link every module again', (f) => { f['lib/f1.py'] += '\n\ndef again():\n return 1\n'; }); + assert.equal(missing.relinked, missing.files); +}); From d416d806244fa0e622b575fe9897e79c87b18ab9 Mon Sep 17 00:00:00 2001 From: Quintin Botes Date: Mon, 30 Nov 2026 13:21:05 +0100 Subject: [PATCH 2/2] Decode cached facts on demand; count coverage from kept per-file summaries (#145 M3) Co-Authored-By: Claude Opus 5.5 --- runtime/diagnose/analysis-coverage.mjs | 26 ++-- runtime/graph/builder.mjs | 139 ++++++++++++++------- runtime/state/extraction-cache.mjs | 113 +++++++++++++---- runtime/state/extraction-pages.mjs | 3 +- scripts/bench.mjs | 6 +- tests/unit/graph/extraction-pages.test.mjs | 36 +++--- tests/unit/graph/remap-cost.test.mjs | 17 +++ 7 files changed, 242 insertions(+), 98 deletions(-) diff --git a/runtime/diagnose/analysis-coverage.mjs b/runtime/diagnose/analysis-coverage.mjs index 3dae8c2..ae73600 100644 --- a/runtime/diagnose/analysis-coverage.mjs +++ b/runtime/diagnose/analysis-coverage.mjs @@ -14,7 +14,7 @@ const DISPLAY = Object.freeze({ }); // A template language (Razor) is no source kind, but no adapter reads it either: it is a gap too (#92). -const source = (file) => !file.context && (file.kind === 'source' || (file.kind === 'other' && templateLanguageIds().includes(file.language))); +export const coveredSource = (file) => !file.context && (file.kind === 'source' || (file.kind === 'other' && templateLanguageIds().includes(file.language))); const moduleFact = (facts) => facts.find((fact) => fact.kind === 'node' && fact.type === 'module') ?? null; const numeric = (value) => typeof value === 'number' && Number.isFinite(value); @@ -38,19 +38,27 @@ function fileAnalyses(facts, mod, expected) { }; } +const expectedFor = (language) => (analysesFor(language).length ? analysesFor(language) : LOCAL_ANALYSES); + +/** The analyses one source file's facts show ran, and those it has symbols for (null: no module fact). */ +export function fileAnalysis(facts, language = 'unknown') { + const mod = moduleFact(facts); + const { ran, candidates } = fileAnalyses(facts, mod, expectedFor(language ?? 'unknown')); + return { ran: mod ? [...ran] : null, candidates: [...candidates] }; +} + /** - * Per-language analysis status for a map. An analysis with no applicable symbol is not a gap; - * one with an unhandled source file or a candidate whose metric was not emitted is. + * Per-language analysis status for a map, from each source file's fileAnalysis (`covered`). An + * analysis with no applicable symbol is not a gap; one with an unhandled source file or a candidate + * whose metric was not emitted is. */ -export function analysisCoverage(files, perFile) { +export function analysisCoverage(files, covered) { const byLanguage = new Map(); for (const file of files) { - if (!source(file)) continue; + if (!coveredSource(file)) continue; const language = file.language ?? 'unknown'; - const facts = perFile.get(file.path) ?? []; - const mod = moduleFact(facts); - const expected = analysesFor(language); - const entry = { path: file.path, mod, expected: expected.length ? expected : LOCAL_ANALYSES, ...fileAnalyses(facts, mod, expected.length ? expected : LOCAL_ANALYSES) }; + const { ran, candidates } = covered.get(file.path); + const entry = { path: file.path, mod: ran !== null, expected: expectedFor(language), ran: new Set(ran), candidates: new Set(candidates) }; if (!byLanguage.has(language)) byLanguage.set(language, []); byLanguage.get(language).push(entry); } diff --git a/runtime/graph/builder.mjs b/runtime/graph/builder.mjs index a7bb34a..62c3af5 100644 --- a/runtime/graph/builder.mjs +++ b/runtime/graph/builder.mjs @@ -9,6 +9,7 @@ import { readHistoryCache, saveHistoryCache } from './history-cache.mjs'; import { checkoutNotice, checkoutState } from './checkout.mjs'; import { compactPriorRuns, ID_LEN, KEYS_STAMP, projectionChanges } from './projection-runs.mjs'; import { readFileSync, statSync } from 'node:fs'; +import { brotliCompressSync, brotliDecompressSync, constants } from 'node:zlib'; import { resolve } from 'node:path'; import { canonicalJSON, digest } from '../core/canonical.mjs'; import { nowISO } from '../core/clock.mjs'; @@ -36,9 +37,9 @@ import { edgeWriter, packEdgeEndpoints } from '../state/edge-endpoints.mjs'; import { factSourceWriter, packFactSources } from '../state/fact-source-profiles.mjs'; import { MIN_NODE_ATTR_BYTES, packNodeFactAttributes } from '../state/node-fact-attributes.mjs'; import { observationId, packInlineObservations } from '../state/fact-observations.mjs'; -import { extractionBatch, extractionJSON, extractionRows } from '../state/extraction-cache.mjs'; +import { extractionBatch, extractionJSON, extractionRows, lazyExtractions } from '../state/extraction-cache.mjs'; import { appendEvent } from '../state/ledger.mjs'; -import { analysisCoverage } from '../diagnose/analysis-coverage.mjs'; +import { analysisCoverage, coveredSource, fileAnalysis } from '../diagnose/analysis-coverage.mjs'; import { analysable, census, readEntry } from './census.mjs'; import { templateLanguageIds } from './languages.mjs'; import { assertFact, edgeFact, edgeId, NODE_TYPES, nodeFact, prov } from './facts.mjs'; @@ -163,22 +164,21 @@ async function mapRepositoryInner(ctx, { config, configDigest, run = null, scope const { loaded, unavailable } = adapters ? { loaded: adapters, unavailable: [] } : await loadAdapters(config, only); const notes = []; // degraded-but-working conditions the person should know about const workers = defaultWorkers(config.limits.workers); - const perFile = new Map(); // path → facts (all adapters) const failures = []; let degradedAny = false; // a degraded batch is retried by the next map, so that map is not skipped const stats = { files: cen.files.filter((f) => !f.context).length, by_kind: cen.byKind, cached: 0, extracted: 0, adapters: {} }; const filesByPath = new Map(cen.files.map((f) => [f.path, f])); const cachedRows = extractionRows(ctx.store.db); - - const moduleBy = new Map(); // path → adapter id that produced its module fact + // Each file's facts (all adapters), decoded when asked for (#145). The census decides what is test + // code (test projects included); an adapter's own path rule only adds to it, so every command sees one classification. + const byFile = lazyExtractions(ctx.store.db, { + prepare(path, facts) { + if (filesByPath.get(path)?.kind === 'test') for (const f of facts) if (f.kind === 'node' && f.type === 'module' && f.attrs) f.attrs.is_test = true; + }, + lost: (path, adapter) => failures.push({ path, adapter, error: 'its cache entry changed during the map: map again' }), + }); const staleRows = new Map(); // path → encoded facts its cache rows held before this map re-extracted it const extractedPaths = new Set(); // paths extracted (not read from the cache) by this map - const addFacts = (path, facts, adapterId) => { - if (adapterId && !moduleBy.has(path) && facts.some((f) => f.kind === 'node' && f.type === 'module')) moduleBy.set(path, adapterId); - let list = perFile.get(path); - if (!list) perFile.set(path, (list = [])); - list.push(...facts); - }; // Only an adapter declaring generated-evidence globs may read a generated file. Keep // these inputs in the same budget, dirty-file check and per-file cache as its other inputs. @@ -298,7 +298,7 @@ async function mapRepositoryInner(ctx, { config, configDigest, run = null, scope } } if (emptyCache.has(f.path, f.blob, kindOf(f))) { - addFacts(f.path, [], adapter.id); + byFile.add(f.path, adapter.id); stats.cached++; continue; } @@ -307,14 +307,15 @@ async function mapRepositoryInner(ctx, { config, configDigest, run = null, scope } for (const [f, hit] of cachedRows(adapter.id, filesToLookUp())) { if (hit && hit.blob === f.blob && hit.adapter_version === adapter.version && hit.config_digest === keyOf(f)) { - const json = extractionJSON(hit.facts); - if (json === '[]') { - emptyHits.push(f); - if (emptyHits.length === COMMIT_CHUNK) migrateEmpty(); - } else if (hit.extraction_page == null || hit.repackSlot !== undefined) { - positives.add({ path: f.path, version: adapter.version, config: keyOf(f), blob: f.blob, json, original: hit.repackSlot ?? hit.facts, page: hit.extraction_page }); + if (hit.extraction_page != null) byFile.add(f.path, adapter.id, { row: hit }); + else { + const json = extractionJSON(hit.facts); + if (json === '[]') { + emptyHits.push(f); + if (emptyHits.length === COMMIT_CHUNK) migrateEmpty(); + } else positives.add({ path: f.path, version: adapter.version, config: keyOf(f), blob: f.blob, json, original: hit.facts, page: null }); + byFile.add(f.path, adapter.id, { json }); } - addFacts(f.path, JSON.parse(json), adapter.id); stats.cached++; } else { misses.push(f); @@ -381,7 +382,7 @@ async function mapRepositoryInner(ctx, { config, configDigest, run = null, scope } else emptyCache.put(r.path, blob, kindOf(entry)); } // As the next map reads them from the cache, so the runs `project` keeps keys for match then (#145). - addFacts(r.path, JSON.parse(text), adapter.id); + byFile.add(r.path, adapter.id, { facts: JSON.parse(text) }); extractedPaths.add(r.path); stats.extracted++; extracted++; @@ -393,30 +394,19 @@ async function mapRepositoryInner(ctx, { config, configDigest, run = null, scope stats.adapters[adapter.id] = { files: files.length, extracted, cached: files.length - misses.length }; } - // Census order, whatever the order cache hits and extractions arrived in, so a re-map merges - // facts exactly as a cold map of the same tree does. - const arrived = new Map(perFile); - perFile.clear(); - for (const f of cen.files) if (arrived.has(f.path)) perFile.set(f.path, arrived.get(f.path)); - for (const [path, facts] of arrived) if (!perFile.has(path)) perFile.set(path, facts); - - // The census decides what is test code (test projects included); an adapter's own path rule - // only adds to it, so every command sees one classification. - for (const [path, facts] of perFile) { - if (filesByPath.get(path)?.kind !== 'test') continue; - for (const f of facts) if (f.kind === 'node' && f.type === 'module' && f.attrs) f.attrs.is_test = true; - } - // Cached files were added before fresh ones, and fresh ones in whatever order extraction - // finished; every later step (linking, dedupe, tie-breaks) sees the files in path order. - const ordered = [...perFile].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); - perFile.clear(); - for (const [path, facts] of ordered) perFile.set(path, facts); lap('extraction_ms'); + const linkKey = digest({ v: LINK_STATE_VERSION, configDigest, adapters: loaded.map((a) => [a.id, a.version, config.adapters?.[a.id] ?? {}]), unavailable }); + // Before linking, which may change facts: coverage counts them as extracted. + const covered = coverageFiles(ctx, linkKey, cen.files, byFile, new Set([...extractedPaths, ...failures.map((f) => f.path)])); + // Every file's facts in path order, whatever order cache hits and extractions arrived in, so a + // re-map links, dedupes and merges exactly as a cold map of the same tree does. + const perFile = byFile.allFileFacts(); + repack(ctx.store, byFile.repack); + lap('all_facts_ms'); let fileFacts = []; const global = []; // Files a semantic adapter (a SCIP index) covers, with what it decided about them; read by the language adapters' link. const semantic = new Map(); - const linkKey = digest({ v: LINK_STATE_VERSION, configDigest, adapters: loaded.map((a) => [a.id, a.version, config.adapters?.[a.id] ?? {}]), unavailable }); const forAdapter = linkStates(ctx, linkKey, { perFile, filesByPath, extractedPaths, staleRows }); for (const adapter of loaded) { if (!adapter.link) continue; @@ -591,8 +581,8 @@ async function mapRepositoryInner(ctx, { config, configDigest, run = null, scope notes.push(...scopes.notes); const ps = parseScope(givenScope); if (ps.namespaces.length || ps.seeds.length) notes.push(NS_SEED_NOTE); - const coverage = languageCoverage(cen.files, perFile, moduleBy); - const analysis = analysisCoverage(cen.files, perFile); + const coverage = languageCoverage(cen.files, covered, semantic); + const analysis = analysisCoverage(cen.files, covered); const totalSource = cen.files.filter((f) => f.kind === 'source' && !f.context).length; coverage.forEach((c, i) => { if (c.qualities?.semantic && c.qualities.lexical) notes.push(`language coverage: ${c.language} ${c.qualities.semantic} of ${c.files} source files are resolved by the SCIP index (semantic), ${c.qualities.lexical} are read lexically`); @@ -654,6 +644,8 @@ async function mapRepositoryInner(ctx, { config, configDigest, run = null, scope failures: failures.slice(0, 200), failure_count: failures.length, facts: all.length, + // Facts and extraction pages decoded on demand, and by the step that still reads every file's (`all`, #145). + facts_read: byFile.counts, // How many facts' keys were worked out again rather than kept from the last map, and whether the facts // were matched with the store from the runs a change reached (`runs`) or one by one (`store`) (#145). projection: { hashed: projection.hashed, matched: projection.matched }, @@ -675,24 +667,75 @@ async function mapRepositoryInner(ctx, { config, configDigest, run = null, scope return summary; } +// Bump when what coverageFiles keeps per file changes. +const COVERAGE_VERSION = 1; + +/** + * What coverage counts of each source file's extracted facts: the adapter of its module fact, its + * parse quality and its analyses (analysis-coverage.mjs). Kept between maps, so a re-map decodes + * only the files that changed or were extracted (`fresh`) (#145). A file's facts are a function of + * its blob, census classification and language under one `key` (adapters, versions, options). + */ +function coverageFiles(ctx, key, files, byFile, fresh) { + const db = ctx.store.db; + key = `${COVERAGE_VERSION}:${key}`; + let kept = {}; + try { + const row = db.prepare("SELECT facts FROM file_index WHERE path='' AND adapter='coverage:files' AND config_digest=?").get(key); + if (row) kept = JSON.parse(brotliDecompressSync(row.facts)); + } catch { /* worked out again */ } + const out = new Map(); + const next = {}; + let dirty = false; + for (const f of files) { + if (!coveredSource(f)) continue; + const sig = `${f.blob?.slice(0, 16)}|${f.kind}|${f.is_test ? 1 : 0}|${f.language}`; + let entry = kept[f.path]; + if (entry?.[0] !== sig || !f.blob || fresh.has(f.path)) { + const facts = byFile.of(f.path); + const mod = facts.find((x) => x.kind === 'node' && x.type === 'module'); + const pq = mod?.attrs?.parse_quality; + const { ran, candidates } = fileAnalysis(facts, f.language); + entry = [sig, byFile.moduleAdapter(f.path) ?? 'none', !mod ? 'not analysed' : pq === 'lexical' ? 'lexical' : pq === 'degraded' ? 'degraded' : pq === 'semantic' ? 'semantic' : 'syntax_tree', ran, candidates]; + dirty ||= JSON.stringify(entry) !== JSON.stringify(kept[f.path]); + } + next[f.path] = entry; + out.set(f.path, { adapter: entry[1], quality: entry[2], ran: entry[3], candidates: entry[4] }); + } + if (dirty || out.size !== Object.keys(kept).length) { + ctx.store.tx(() => db.prepare("INSERT OR REPLACE INTO file_index(path, adapter, adapter_version, config_digest, blob, facts) VALUES ('', 'coverage:files', '1', ?, '', ?)") + .run(key, brotliCompressSync(Buffer.from(JSON.stringify(next)), { params: { [constants.BROTLI_PARAM_QUALITY]: 4 } }))); + } + return out; +} + +/** Write sparse extraction pages' members to fresh pages, so the sparse pages are released. */ +function repack(store, members) { + const by = Map.groupBy(members, (m) => m.adapter); + for (const [adapter, rows] of by) { + const batch = extractionBatch(store, adapter); + for (const r of rows) batch.add(r); + batch.flush(); + } +} + /** * Source files per language with the adapter that handled them and how: `semantic` (resolved by * a compiler's index), `syntax_tree` (parsed), `degraded` (parsed with fallbacks) or `lexical` * (name matching only). Most files first. `qualities` (files per quality) is present when a language - * is mixed or semantic. + * is mixed or semantic. `covered` is coverageFiles' result; `semantic` the files a SCIP index resolved. */ -export function languageCoverage(files, perFile, moduleBy) { +export function languageCoverage(files, covered, semantic) { const by = new Map(); const templates = templateLanguageIds(); const isTemplate = (f) => f.kind === 'other' && templates.includes(f.language); for (const f of files) { - if (f.context || (f.kind !== 'source' && !isTemplate(f))) continue; - const mod = (perFile.get(f.path) ?? []).find((x) => x.kind === 'node' && x.type === 'module'); - const pq = mod?.attrs?.parse_quality; - const quality = !mod ? 'not analysed' : pq === 'lexical' ? 'lexical' : pq === 'degraded' ? 'degraded' : pq === 'semantic' ? 'semantic' : 'syntax_tree'; + if (!coveredSource(f)) continue; + const c = covered.get(f.path); + const quality = semantic.has(f.path) && c.quality !== 'not analysed' ? 'semantic' : c.quality; const g = by.get(f.language) ?? { language: f.language, template: isTemplate(f), files: 0, adapters: new Map(), quals: new Map() }; g.files++; - const a = moduleBy.get(f.path) ?? 'none'; + const a = c.adapter; g.adapters.set(a, (g.adapters.get(a) ?? 0) + 1); g.quals.set(quality, (g.quals.get(quality) ?? 0) + 1); by.set(f.language, g); diff --git a/runtime/state/extraction-cache.mjs b/runtime/state/extraction-cache.mjs index 70dac04..05bfd9a 100644 --- a/runtime/state/extraction-cache.mjs +++ b/runtime/state/extraction-cache.mjs @@ -35,42 +35,25 @@ export function* storedExtractions(store, path) { } } -// Amortize SQLite's per-statement snapshot cost while replaying hits in census order. -// The prefetched payloads occupy at most 4 MiB. Larger rows are fetched individually. +// Validity metadata of cache hits in census order, batched to amortize SQLite's per-statement +// snapshot cost. A paged row's `facts` is its slot: the page is read only when its facts are +// (lazyExtractions). Unpaged payloads up to 64 KiB are prefetched; larger ones fetched alone. export function extractionRows(db) { const columns = 'blob, adapter_version, config_digest, extraction_page'; - const member = pageReader(db); const single = db.prepare(`SELECT path, ${columns}, facts FROM file_index WHERE adapter=? AND path=?`); const batch = db.prepare(`SELECT path, ${columns}, - CASE WHEN length(CAST(facts AS BLOB)) <= ? THEN facts END AS facts + CASE WHEN extraction_page IS NOT NULL OR length(CAST(facts AS BLOB)) <= ? THEN facts END AS facts FROM file_index WHERE adapter=? AND path IN (SELECT value FROM json_each(?))`); - function resolve(adapter, row) { - if (row?.extraction_page == null) return row; - let hit = member(row.extraction_page, row.facts); - // A writer may replace a member after the batch lookup and reclaim its page. - // Retry both the metadata and the page in one statement snapshot in that case. - if (!hit) { - const retry = db.prepare(`SELECT i.path,i.blob,i.adapter_version,i.config_digest,i.extraction_page,i.facts,p.payload, - (SELECT COUNT(*) FROM file_index WHERE extraction_page=p.id) AS live FROM file_index i - LEFT JOIN extraction_pages p ON p.id=i.extraction_page WHERE i.adapter=? AND i.path=?`).get(adapter, row.path); - if (!retry) return undefined; - const { payload, live, ...current } = retry; - row = current; - if (row.extraction_page == null) return row; - hit = member(row.extraction_page, row.facts, { payload, live }); - } - return { ...row, ...(hit.sparse && { repackSlot: row.facts }), facts: hit.json }; - } function* read(adapter, files) { if (files.length === 1) { - yield [files[0], resolve(adapter, single.get(adapter, files[0].path))]; + yield [files[0], single.get(adapter, files[0].path)]; return; } const paths = files.map((f) => f.path); const hits = new Map(batch.all(PREFETCH_ROW_BYTES, adapter, JSON.stringify(paths)).map((r) => [r.path, r])); for (const f of files) { const row = hits.get(f.path); - yield [f, resolve(adapter, row?.facts === null ? single.get(adapter, f.path) : row)]; + yield [f, row?.facts === null ? single.get(adapter, f.path) : row]; } } return function* (adapter, files) { @@ -86,6 +69,90 @@ export function extractionRows(db) { }; } +/** + * The facts of each mapped file, decoded only when asked for (#145). `add` records, in adapter + * order, a part of a file's facts: `{ facts }` in memory, `{ json }`, or `{ row }`, a valid paged + * cache row whose page is read on demand. `prepare(path, facts)` runs once on a file's facts. + * `reads` counts what lazy reads decoded; `all` what allFileFacts did. A row another writer + * replaced is read again if its key is unchanged, else reported to `lost`. Members of sparse + * pages are listed in `repack`. + */ +export function lazyExtractions(db, { prepare = () => {}, lost = () => {} } = {}) { + const member = pageReader(db, () => reads.pages++); + const retry = db.prepare(`SELECT i.blob,i.adapter_version,i.config_digest,i.extraction_page,i.facts,p.payload, + (SELECT COUNT(*) FROM file_index WHERE extraction_page=p.id) AS live FROM file_index i + LEFT JOIN extraction_pages p ON p.id=i.extraction_page WHERE i.adapter=? AND i.path=?`); + const parts = new Map(); + const loaded = new Map(); + const owners = new Map(); // path → adapter of its first module fact + const repack = []; + let reads = { files: 0, facts: 0, pages: 0 }, all = null; + function text(path, adapter, row) { + let hit = member(row.extraction_page, row.facts); + if (!hit) { + // A writer may replace a member after the lookup and reclaim its page. + const { payload, live, ...now } = retry.get(adapter, path) ?? {}; + if (now.blob !== row.blob || now.adapter_version !== row.adapter_version || now.config_digest !== row.config_digest) { + lost(path, adapter); + return '[]'; + } + if (now.extraction_page == null) return extractionJSON(now.facts); + row = now; + hit = member(row.extraction_page, row.facts, { payload, live }); + } + if (hit.sparse) repack.push({ adapter, path, version: row.adapter_version, config: row.config_digest, blob: row.blob, json: hit.json, original: row.facts, page: row.extraction_page }); + return hit.json; + } + const decode = (path, p) => { + p.facts = JSON.parse(p.json ?? text(path, p.adapter, p.row)); + p.json = p.row = undefined; + p.decoded = true; + reads.facts += p.facts.length; + }; + const self = { + add(path, adapter, part) { + if (!parts.has(path)) parts.set(path, []); + if (part) parts.get(path).push({ adapter, ...part }); + }, + has: (path) => parts.has(path), + of(path) { + let facts = loaded.get(path); + if (facts) return facts; + facts = []; + const ps = parts.get(path) ?? []; + for (const p of ps) { + if (!p.facts) decode(path, p); + if (!owners.has(path) && p.facts.some((f) => f.kind === 'node' && f.type === 'module')) owners.set(path, p.adapter); + for (const f of p.facts) facts.push(f); + } + if (ps.some((p) => p.decoded)) reads.files++; + prepare(path, facts); + loaded.set(path, facts); + return facts; + }, + moduleAdapter: (path) => owners.get(path), + // shortcut: every file's facts, for linking and projection, which read them all; replaced when they work from the change set (#145 M4). + allFileFacts() { + const lazy = reads; + reads = { files: 0, facts: 0, pages: 0 }; + // Page order, so each page is inflated once. + const pending = []; + for (const [path, ps] of parts) if (!loaded.has(path)) for (const p of ps) if (p.row) pending.push([path, p]); + pending.sort((a, b) => a[1].row.extraction_page - b[1].row.extraction_page); + for (const [path, p] of pending) decode(path, p); + const out = new Map(); + for (const path of [...parts.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) out.set(path, self.of(path)); + all = reads; + reads = lazy; + return out; + }, + // Facts and pages decoded by lazy reads, and by allFileFacts (`all`). + get counts() { return { ...reads, ...(all && { all }) }; }, + repack, + }; + return self; +} + // Fresh results are staged within an extraction chunk. Promotion of existing rows // compares their original bytes and metadata so a concurrent edit always wins. export function extractionBatch(store, adapter) { diff --git a/runtime/state/extraction-pages.mjs b/runtime/state/extraction-pages.mjs index 3b3c457..bdc02d6 100644 --- a/runtime/state/extraction-pages.mjs +++ b/runtime/state/extraction-pages.mjs @@ -29,7 +29,7 @@ function member(page, slot) { return { json, sparse: page.sparse }; } -export function pageReader(db) { +export function pageReader(db, onRead = () => {}) { const select = db.prepare(`SELECT payload, (SELECT COUNT(*) FROM file_index WHERE extraction_page=?) AS live FROM extraction_pages WHERE id=?`); // In census order neighbouring files usually read the same page. Keep at most @@ -41,6 +41,7 @@ export function pageReader(db) { const row = supplied ?? select.get(id, id); if (!row) return undefined; const lines = decode(row.payload); + onRead(); page = { lines, sparse: row.live * 2 < lines.length }; if (pages.size === 16) pages.delete(pages.keys().next().value); pages.set(id, page); diff --git a/scripts/bench.mjs b/scripts/bench.mjs index 644ea04..29bb0e6 100644 --- a/scripts/bench.mjs +++ b/scripts/bench.mjs @@ -298,7 +298,7 @@ export function machineDescription() { return { cpu: os.cpus()[0]?.model ?? 'unknown', cores: os.cpus().length, ram_gb: Math.round(os.totalmem() / 2 ** 30), platform: `${os.platform()} ${os.arch()}`, node: process.version }; } -const PHASES = ['census_ms', 'extraction_ms', 'link_ms', 'discovery_ms', 'history_ms', 'coverage_ms', 'projection_ms']; +const PHASES = ['census_ms', 'extraction_ms', 'all_facts_ms', 'link_ms', 'discovery_ms', 'history_ms', 'coverage_ms', 'projection_ms']; export function toMarkdown(machine, results) { const sec = (ms) => (ms === undefined ? 'n/a' : `${(ms / 1000).toFixed(1)} s`); @@ -318,8 +318,8 @@ export function toMarkdown(machine, results) { ...rows, '', ...(gateRows.length ? ['| Fixture | No change / cold | Changed / no change | Store / tree |', '| --- | ---: | ---: | ---: |', ...gateRows, ''] : []), - '| Run | Census | Extraction | Link | Discovery | History | Coverage | Projection |', - '| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |', + '| Run | Census | Extraction | All facts | Link | Discovery | History | Coverage | Projection |', + '| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |', ...phaseRows, '', ].join('\n'); diff --git a/tests/unit/graph/extraction-pages.test.mjs b/tests/unit/graph/extraction-pages.test.mjs index 5978cc5..7fe12c3 100644 --- a/tests/unit/graph/extraction-pages.test.mjs +++ b/tests/unit/graph/extraction-pages.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { after, test } from 'node:test'; import { Store } from '../../../runtime/state/store.mjs'; -import { extractionBatch, extractionRows, readExtraction, storedExtractions } from '../../../runtime/state/extraction-cache.mjs'; +import { extractionBatch, extractionRows, lazyExtractions, storedExtractions } from '../../../runtime/state/extraction-cache.mjs'; import * as K from '../../helpers/kernel.mjs'; after(() => K.cleanup()); @@ -31,13 +31,18 @@ test('fresh extraction pages roll back together, survive replacement and release const last = rows.at(-1); const [[, hit]] = [...extractionRows(store.db)('test', [last])]; assert.equal(hit.extraction_page, original); - assert.equal(hit.repackSlot, '63'); - write(store, [{ ...last, original: hit.repackSlot, page: hit.extraction_page }]); + const lazy = lazyExtractions(store.db); + lazy.add(last.path, 'test', { row: hit }); + assert.deepEqual(lazy.of(last.path), JSON.parse(last.json)); + assert.deepEqual(lazy.counts, { files: 1, facts: 1, pages: 1 }); + const [sparse] = lazy.repack; + assert.equal(sparse.original, '63'); + write(store, [{ ...last, original: sparse.original, page: sparse.page }]); assert.equal(pages(store), 0); assert.deepEqual([...storedExtractions(store, last.path)], [[last.path, JSON.parse(last.json)]]); }); -test('promotion checks the old payload and a prefetched member can recover when a writer replaces its page', () => { +test('promotion checks the old payload and a looked-up member is read again when a writer replaces its page', () => { const { ctx: { store } } = K.makeProject(); const other = new Store(store.file); try { @@ -49,16 +54,19 @@ test('promotion checks the old payload and a prefetched member can recover when promoting.flush(); assert.equal(pages(store), 1); assert.deepEqual([...storedExtractions(store, rows[7].path)][0][1], JSON.parse(item(7, 'competing').json)); - const sentinel = item(9); - write(store, [sentinel]); - const iter = extractionRows(store.db)('test', [sentinel, ...rows]); - assert.equal(iter.next().value[1].path, sentinel.path); - write(other, rows.map((_, i) => item(i, 'latest'))); - assert.equal(pages(store), 1); - const recovered = iter.next().value[1]; - assert.equal(recovered.blob, 'latest'); - assert.deepEqual(readExtraction(recovered.facts), JSON.parse(item(0, 'latest').json)); - iter.return(); + const current = rows.map((r, i) => (i === 7 ? item(7, 'competing') : r)); + const lost = []; + const lazy = lazyExtractions(store.db, { lost: (path) => lost.push(path) }); + for (const [f, row] of extractionRows(store.db)('test', current)) lazy.add(f.path, 'test', { row }); + // Another writer moves the same entries to a new page (the old one is released), and changes one. + write(other, current.slice(1).map((r) => ({ ...r, original: String(current.indexOf(r)), page: store.get('SELECT id FROM extraction_pages').id }))); + write(other, [item(0, 'latest')]); + const all = lazy.allFileFacts(); + assert.deepEqual([...all.keys()], current.map((r) => r.path).sort()); + for (const r of current.slice(1)) assert.deepEqual(all.get(r.path), JSON.parse(r.json)); + assert.deepEqual(all.get(rows[0].path), []); + assert.deepEqual(lost, [rows[0].path]); + assert.equal(lazy.counts.all.files, 8); } finally { other.close(); } }); diff --git a/tests/unit/graph/remap-cost.test.mjs b/tests/unit/graph/remap-cost.test.mjs index 01f838f..04baaea 100644 --- a/tests/unit/graph/remap-cost.test.mjs +++ b/tests/unit/graph/remap-cost.test.mjs @@ -274,6 +274,23 @@ test('with history on, an incremental map through a deepen and a new commit equa assert.equal(next.history.co_change_pairs, full.r.history.co_change_pairs); }); +test('a ten-file edit decodes only the changed files\' cached facts outside the step that still reads every file, and covers as a cold map does (#145)', async () => { + const tree = Object.fromEntries(Array.from({ length: 60 }, (_, i) => [`src/m${i}.js`, `export function f${i}(x) { if (x) return ${i}; return 0; }\n`])); + const p = K.makeProject({ files: tree }); + const cold = await map(p); + assert.deepEqual([cold.facts_read.files, cold.facts_read.pages], [0, 0], 'a cold map extracts, it decodes nothing'); + for (let i = 0; i < 60; i += 6) tree[`src/m${i}.js`] = `export class C${i} { a() {} }\n`; + for (let i = 0; i < 60; i += 6) writeFileSync(join(p.dir, `src/m${i}.js`), tree[`src/m${i}.js`]); + commit(p, 'ten files'); + const edit = await map(p); + assert.equal(edit.adapters.javascript.extracted, 10); + // Coverage reads the edited files only; every other file's facts are decoded by allFileFacts alone. + assert.ok(edit.facts_read.files <= 10, JSON.stringify(edit.facts_read)); + assert.ok(edit.facts_read.all.files >= 50, JSON.stringify(edit.facts_read)); + const fresh = await map(K.makeProject({ files: tree })); + assert.deepEqual([edit.coverage, edit.analysis], [fresh.coverage, fresh.analysis]); +}); + test('a changed map reuses and packs legacy extraction JSON while verification can read both representations', async () => { const { graphPair } = await import('../../../runtime/verify/checks.mjs'); const p = K.makeProject({ files: { ...files, 'src/long.js': Array.from({ length: 25 }, (_, i) => `export function café${i}() { return '測試'; }`).join('\n') } });