diff --git a/runtime/diagnose/analysis-coverage.mjs b/runtime/diagnose/analysis-coverage.mjs index 3dae8c2e..ae73600e 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 a7bb34a3..62c3af58 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 70dac040..05bfd9a6 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 3b3c4572..bdc02d6e 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 644ea043..29bb0e67 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 5978cc51..7fe12c36 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 01f838f8..04baaea8 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') } });