Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions runtime/diagnose/analysis-coverage.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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);
}
Expand Down
139 changes: 91 additions & 48 deletions runtime/graph/builder.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}
Expand All @@ -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);
Expand Down Expand Up @@ -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++;
Expand All @@ -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;
Expand Down Expand Up @@ -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`);
Expand Down Expand Up @@ -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 },
Expand All @@ -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);
Expand Down
Loading
Loading