-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodeEvidence.ts
More file actions
472 lines (450 loc) · 16.7 KB
/
Copy pathcodeEvidence.ts
File metadata and controls
472 lines (450 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import type { DeadCodeExplanation } from './analysisModel.ts';
import { sha256Hex } from './guards.ts';
import { diagnosticsFromStoredSnapshot, type DiagnosticRecord } from './lint.ts';
import type {
ContextFreshness,
ContextSnapshot,
StoredContextSnapshot,
TestExecutionFacet,
TestExecutionLocation,
TestFacet,
} from './model.ts';
import { normalizeModuleSelector, toWorkspacePath } from './paths.ts';
import { explainAnalysisModule, loadAnalysis } from './queries.ts';
import { assessSnapshotFreshness } from './source.ts';
import { readContextSnapshotById, readContextSnapshots } from './store.ts';
type CodeEvidenceQuery = {
path: string;
line?: number;
contextId?: string;
dataFile?: string;
module?: string;
testSnapshotId?: string;
lintSnapshotId?: string;
maxDepth?: number;
};
type SnapshotEvidence = {
snapshotId: string;
contextId: string;
observedAt: string;
status: ContextSnapshot['status'];
completeness: ContextSnapshot['completeness'];
freshness: ContextFreshness;
packageRoot: string;
unreadableInputs?: string[];
};
type ExecutionCoverageEvidence = {
state: 'observed' | 'not-observed' | 'unknown' | 'unavailable';
reason?:
| 'no-test-snapshot'
| 'not-captured'
| 'provider-unavailable'
| 'path-not-reported'
| 'digest-unavailable'
| 'digest-mismatch'
| 'partial-universe'
| 'no-overlapping-locations';
relevantLocations: number;
observedLocations: number;
fileDigest?: string;
};
type TestOutcomeEvidence = {
state: 'failed' | 'passed' | 'not-run' | 'unknown';
basis?: 'exact-path' | 'related-selection';
reason?: 'no-exact-test-record' | 'related-tests-not-reported';
matchingFiles: number;
matchingTests: number;
};
type TestRelationEvidence = {
state: 'related' | 'unrelated' | 'unknown' | 'unavailable';
reason?: 'no-test-snapshot' | 'not-captured' | 'source-not-selected' | 'selection-not-isolated';
testFiles: string[];
};
type CodeDiagnosticEvidence = {
total: number;
returned: number;
truncated: boolean;
items: DiagnosticRecord[];
};
type CodeEvidenceResult = {
path: string;
line?: number;
executionCoverage: ExecutionCoverageEvidence;
testRelation: TestRelationEvidence;
testOutcome: TestOutcomeEvidence;
diagnostics: CodeDiagnosticEvidence;
module?: DeadCodeExplanation;
provenance: { test?: SnapshotEvidence; lint?: SnapshotEvidence };
bounds: string[];
};
const normalizeSourcePath = (workspaceRoot: string, value: string): string => {
const portable = value.replaceAll('\\', '/');
if (portable.length === 0 || path.posix.isAbsolute(portable)) {
throw new Error('path must be a non-empty checkout-relative source path.');
}
const normalized = normalizeModuleSelector(value);
const relative = toWorkspacePath(workspaceRoot, normalized);
if (relative.length === 0 || relative === '..' || relative.startsWith('../')) {
throw new Error('path must be a non-empty checkout-relative source path.');
}
return relative;
};
const packageContainsPath = (packageRoot: string, sourcePath: string): boolean => {
const normalizedRoot = path.posix.normalize(packageRoot.replaceAll('\\', '/'));
return (
normalizedRoot === '.' ||
sourcePath === normalizedRoot ||
sourcePath.startsWith(`${normalizedRoot}/`)
);
};
const lintSnapshotCapturedPath = (stored: StoredContextSnapshot, sourcePath: string): boolean =>
stored.snapshot.source?.inputs?.some((input) => input.path === sourcePath) === true ||
diagnosticsFromStoredSnapshot(stored).some((diagnostic) => diagnostic.path === sourcePath);
const selectSnapshot = async (
workspaceRoot: string,
producer: 'rstest' | 'rslint',
sourcePath: string,
snapshotId: string | undefined,
): Promise<StoredContextSnapshot | undefined> => {
if (snapshotId !== undefined) {
const selected = await readContextSnapshotById(workspaceRoot, snapshotId);
if (selected === undefined || selected.run.producer !== producer) {
throw new Error(`${producer === 'rstest' ? 'Rstest' : 'Rslint'} snapshot not found.`);
}
if (!packageContainsPath(selected.context.packageRoot, sourcePath)) {
throw new Error(
`Selected ${producer === 'rstest' ? 'Rstest' : 'Rslint'} snapshot package root does not contain the source path.`,
);
}
if (producer === 'rslint' && !lintSnapshotCapturedPath(selected, sourcePath)) {
throw new Error('Selected Rslint snapshot did not capture the source path.');
}
return selected;
}
return (await readContextSnapshots(workspaceRoot, { producer })).find(
(stored) =>
packageContainsPath(stored.context.packageRoot, sourcePath) &&
(producer !== 'rstest' || stored.snapshot.completeness.test === 'complete') &&
stored.snapshot.facets[producer === 'rstest' ? 'test' : 'lint'] !== undefined &&
(producer !== 'rslint' || lintSnapshotCapturedPath(stored, sourcePath)),
);
};
const snapshotEvidence = async (
workspaceRoot: string,
stored: StoredContextSnapshot,
): Promise<SnapshotEvidence> => ({
snapshotId: stored.snapshot.snapshotId,
contextId: stored.snapshot.contextId,
observedAt: stored.snapshot.observedAt,
status: stored.snapshot.status,
completeness: stored.snapshot.completeness,
freshness: await assessSnapshotFreshness(workspaceRoot, stored.snapshot),
packageRoot: stored.context.packageRoot,
...(stored.snapshot.source?.unreadableInputs === undefined
? {}
: { unreadableInputs: [...stored.snapshot.source.unreadableInputs] }),
});
const locationOverlapsLine = (location: TestExecutionLocation, line: number | undefined): boolean =>
line === undefined || (location.start.line <= line && location.end.line >= line);
const readCurrentDigest = async (
workspaceRoot: string,
sourcePath: string,
): Promise<string | undefined> => {
try {
return sha256Hex(await readFile(path.resolve(workspaceRoot, sourcePath)));
} catch {
return undefined;
}
};
const executionCoverage = async (
workspaceRoot: string,
sourcePath: string,
line: number | undefined,
stored: StoredContextSnapshot | undefined,
): Promise<ExecutionCoverageEvidence> => {
const empty = { relevantLocations: 0, observedLocations: 0 };
if (stored === undefined) return { state: 'unavailable', reason: 'no-test-snapshot', ...empty };
const facet = stored.snapshot.facets.execution as unknown as TestExecutionFacet | undefined;
if (facet === undefined) return { state: 'unavailable', reason: 'not-captured', ...empty };
if (facet.availability !== 'available') {
return { state: 'unavailable', reason: 'provider-unavailable', ...empty };
}
const file = facet.files.find((entry) => entry.path === sourcePath);
if (file === undefined) return { state: 'unknown', reason: 'path-not-reported', ...empty };
const digest = await readCurrentDigest(workspaceRoot, sourcePath);
if (digest === undefined || file.digest === undefined) {
return { state: 'unknown', reason: 'digest-unavailable', fileDigest: file.digest, ...empty };
}
if (digest !== file.digest) {
return { state: 'unknown', reason: 'digest-mismatch', fileDigest: file.digest, ...empty };
}
const hits = [
...file.statements
.filter(({ location }) => locationOverlapsLine(location, line))
.map(({ hits }) => hits),
...file.functions
.filter(({ location }) => locationOverlapsLine(location, line))
.map(({ hits }) => hits),
...file.branches.flatMap(({ arms }) =>
arms.filter(({ location }) => locationOverlapsLine(location, line)).map(({ hits }) => hits),
),
];
const observedLocations = hits.filter((value) => value > 0).length;
const counts = { relevantLocations: hits.length, observedLocations, fileDigest: file.digest };
if (hits.length === 0) {
return { state: 'unknown', reason: 'no-overlapping-locations', ...counts };
}
if (observedLocations > 0) return { state: 'observed', ...counts };
if (
stored.snapshot.completeness.execution !== 'complete' ||
facet.universe.completeness !== 'complete' ||
facet.truncated.files > 0 ||
facet.truncated.locations > 0
) {
return { state: 'unknown', reason: 'partial-universe', ...counts };
}
return { state: 'not-observed', ...counts };
};
const testOutcome = (
sourcePath: string,
stored: StoredContextSnapshot | undefined,
): TestOutcomeEvidence => {
if (stored === undefined) return { state: 'unknown', matchingFiles: 0, matchingTests: 0 };
const facet = stored.snapshot.facets.test as unknown as TestFacet | undefined;
if (facet === undefined) return { state: 'unknown', matchingFiles: 0, matchingTests: 0 };
const files = facet.files.filter((file) => file.path === sourcePath);
const tests = facet.files
.flatMap((file) => file.tests)
.filter((test) => test.path === sourcePath);
let basis: TestOutcomeEvidence['basis'] = 'exact-path';
let matchingFiles = files;
let matchingTests = tests;
if (files.length === 0 && tests.length === 0) {
const relation = facet.relation;
if (
relation === undefined ||
relation.sources.length !== 1 ||
relation.sources[0] !== sourcePath
) {
return {
state: 'unknown',
reason: 'no-exact-test-record',
matchingFiles: 0,
matchingTests: 0,
};
}
const selectedPaths = new Set(relation.testFiles);
matchingFiles = facet.files.filter((file) => selectedPaths.has(file.path));
matchingTests = matchingFiles.flatMap((file) => file.tests);
basis = 'related-selection';
if (relation.testFiles.length > 0 && matchingFiles.length === 0) {
return {
state: 'unknown',
basis,
reason: 'related-tests-not-reported',
matchingFiles: 0,
matchingTests: 0,
};
}
}
if (
// A run-level unhandled error is global to the snapshot, so it only attributes to this source
// when the run was provably isolated to it. An exact test-file record reports its own outcome.
(basis === 'related-selection' && facet.unhandledErrors.length > 0) ||
matchingFiles.some((file) => file.status === 'fail' || (file.errors?.length ?? 0) > 0) ||
matchingTests.some((test) => test.status === 'fail')
) {
return {
state: 'failed',
basis,
matchingFiles: matchingFiles.length,
matchingTests: matchingTests.length,
};
}
if (
matchingFiles.some((file) => file.status === 'pass') ||
matchingTests.some((test) => test.status === 'pass')
) {
return {
state: 'passed',
basis,
matchingFiles: matchingFiles.length,
matchingTests: matchingTests.length,
};
}
return {
state: 'not-run',
basis,
matchingFiles: matchingFiles.length,
matchingTests: matchingTests.length,
};
};
const testRelation = (
sourcePath: string,
stored: StoredContextSnapshot | undefined,
): TestRelationEvidence => {
if (stored === undefined) {
return { state: 'unavailable', reason: 'no-test-snapshot', testFiles: [] };
}
const facet = stored.snapshot.facets.test as unknown as TestFacet | undefined;
if (facet?.relation === undefined) {
return { state: 'unavailable', reason: 'not-captured', testFiles: [] };
}
if (!facet.relation.sources.includes(sourcePath)) {
return { state: 'unknown', reason: 'source-not-selected', testFiles: [] };
}
if (facet.relation.sources.length !== 1) {
return {
state: 'unknown',
reason: 'selection-not-isolated',
testFiles: [...facet.relation.testFiles],
};
}
return {
state: facet.relation.testFiles.length > 0 ? 'related' : 'unrelated',
testFiles: [...facet.relation.testFiles],
};
};
const compareDiagnostics = (left: DiagnosticRecord, right: DiagnosticRecord): number =>
left.producer.localeCompare(right.producer) ||
(left.line ?? 0) - (right.line ?? 0) ||
(left.column ?? 0) - (right.column ?? 0) ||
left.message.localeCompare(right.message);
const moduleEvidence = async (
workspaceRoot: string,
query: Required<Pick<CodeEvidenceQuery, 'contextId' | 'dataFile'>> &
Pick<CodeEvidenceQuery, 'maxDepth' | 'module'> & { path: string },
): Promise<DeadCodeExplanation> => {
// The Rsdoctor artifact is read and normalized once per call; every module axis below reuses it.
const analysis = await loadAnalysis(workspaceRoot, query);
if (query.module !== undefined) {
return explainAnalysisModule(analysis, { module: query.module, maxDepth: query.maxDepth });
}
const { product } = analysis;
const packageRelativePath =
product.packageRoot === '.'
? query.path
: query.path.startsWith(`${product.packageRoot}/`)
? query.path.slice(product.packageRoot.length + 1)
: query.path;
const insufficientEvidence = (): DeadCodeExplanation => ({
provenance: analysis.provenance,
classification: 'insufficient-evidence',
state: {
productionReachability: 'unknown',
publicContract: 'unknown',
shipped: 'unknown',
optimizerRetention: 'unknown',
},
paths: [],
evidence: ['No unique artifact module matched the exact source path.'],
analysisTruncated: false,
bounds: [...product.bounds, 'source-path-module-match-unavailable'],
});
try {
return explainAnalysisModule(analysis, { module: query.path, maxDepth: query.maxDepth });
} catch (error) {
if (error instanceof Error && /^Ambiguous module selector:/u.test(error.message)) {
return insufficientEvidence();
}
if (!(error instanceof Error) || !/^Unknown module selector:/u.test(error.message)) throw error;
if (packageRelativePath !== query.path) {
try {
return explainAnalysisModule(analysis, {
module: packageRelativePath,
maxDepth: query.maxDepth,
});
} catch (fallbackError) {
if (
!(fallbackError instanceof Error) ||
!/^(?:Unknown|Ambiguous) module selector:/u.test(fallbackError.message)
) {
throw fallbackError;
}
}
}
return insufficientEvidence();
}
};
const readCodeEvidence = async (
workspaceRoot: string,
query: CodeEvidenceQuery,
): Promise<CodeEvidenceResult> => {
if ((query.contextId === undefined) !== (query.dataFile === undefined)) {
throw new Error('contextId and dataFile must be supplied together.');
}
if (query.module !== undefined && query.contextId === undefined) {
throw new Error('module requires contextId and dataFile.');
}
if (query.line !== undefined && (!Number.isInteger(query.line) || query.line < 1)) {
throw new Error('line must be a positive integer.');
}
const sourcePath = normalizeSourcePath(workspaceRoot, query.path);
const [testSnapshot, lintSnapshot] = await Promise.all([
selectSnapshot(workspaceRoot, 'rstest', sourcePath, query.testSnapshotId),
selectSnapshot(workspaceRoot, 'rslint', sourcePath, query.lintSnapshotId),
]);
const matchingDiagnostics = [
...(lintSnapshot === undefined ? [] : diagnosticsFromStoredSnapshot(lintSnapshot)),
...(testSnapshot === undefined ? [] : diagnosticsFromStoredSnapshot(testSnapshot)),
]
.filter((diagnostic) => diagnostic.path === sourcePath)
.sort(compareDiagnostics);
const diagnosticItems = matchingDiagnostics.slice(0, 200);
const diagnostics: CodeDiagnosticEvidence = {
total: matchingDiagnostics.length,
returned: diagnosticItems.length,
truncated: diagnosticItems.length < matchingDiagnostics.length,
items: diagnosticItems,
};
const module =
query.contextId === undefined || query.dataFile === undefined
? undefined
: await moduleEvidence(workspaceRoot, {
path: sourcePath,
contextId: query.contextId,
dataFile: query.dataFile,
module: query.module,
maxDepth: query.maxDepth,
});
const provenance = {
...(testSnapshot === undefined
? {}
: { test: await snapshotEvidence(workspaceRoot, testSnapshot) }),
...(lintSnapshot === undefined
? {}
: { lint: await snapshotEvidence(workspaceRoot, lintSnapshot) }),
};
const bounds = [
'aggregate-execution-no-test-attribution',
'test-relation-static-build-graph',
'test-outcome-exact-path-or-isolated-related-selection',
'diagnostics-exact-path-only',
...(module !== undefined && module.provenance.artifactBinding !== 'exact'
? ['artifact-binding-not-exact']
: []),
];
return {
path: sourcePath,
...(query.line === undefined ? {} : { line: query.line }),
executionCoverage: await executionCoverage(workspaceRoot, sourcePath, query.line, testSnapshot),
testRelation: testRelation(sourcePath, testSnapshot),
testOutcome: testOutcome(sourcePath, testSnapshot),
diagnostics,
...(module === undefined ? {} : { module }),
provenance,
bounds,
};
};
export { readCodeEvidence };
export type {
CodeDiagnosticEvidence,
CodeEvidenceQuery,
CodeEvidenceResult,
ExecutionCoverageEvidence,
SnapshotEvidence,
TestOutcomeEvidence,
TestRelationEvidence,
};