Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { createReadStream } from 'node:fs';
import { appendFile, readdir, readFile } from 'node:fs/promises';
import type { Profiler } from 'node:inspector';
import path from 'node:path';
import { createInterface } from 'node:readline';
import { fileURLToPath } from 'node:url';
import { admittedStatementLines } from './admitted-statement-lines.js';

interface StatementInput {
url: string;
source: string;
sourceMapUrl?: string;
}

const rawDirectory = process.argv[2];
if (rawDirectory === undefined) throw new Error('Statement conversion requires a coverage directory');

const request: Buffer[] = [];
for await (const chunk of process.stdin) request.push(chunk as Buffer);
const selectedFiles = new Set(JSON.parse(Buffer.concat(request).toString('utf8')) as string[]);

const names = (await readdir(rawDirectory)).filter(name => name.endsWith('-usvm.json'));
if (names.length !== 1 || names[0] === undefined) throw new Error('Expected one admitted V8 report');

const rawReport = JSON.parse(await readFile(path.join(rawDirectory, names[0]), 'utf8')) as {
result: Profiler.ScriptCoverage[];
};
const scripts = new Map(rawReport.result.map(script => [script.url, script]));
const output = path.join(rawDirectory, 'admitted-statement-lines.ndjson');
const inputs = createInterface({
input: createReadStream(path.join(rawDirectory, 'statement-inputs.ndjson')),
crlfDelay: Infinity,
});

for await (const line of inputs) {
const input = JSON.parse(line) as StatementInput;
if (!selectedFiles.has(fileURLToPath(input.url))) continue;

const script = scripts.get(input.url);
if (script === undefined) continue;

const evidence = admittedStatementLines(script, input.source, input.sourceMapUrl);
if (evidence !== undefined) await appendFile(output, JSON.stringify(evidence) + '\n');
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import { appendFileSync, mkdirSync } from 'node:fs';
import path from 'node:path';
import { Session, type Debugger, type Profiler } from 'node:inspector';
import { parentPort, workerData } from 'node:worker_threads';
import { mergeProcessCovs } from '@bcoe/v8-coverage';
import type { AdmittedStatementLines } from './admitted-statement-lines.js';

export interface ExecutionCoverageSnapshot {
kind: 'coverage';
admittedInvocations: number;
result: Profiler.ScriptCoverage[];
statementLines: AdmittedStatementLines[];
scripts: Record<string, { lineLengths: number[]; sourceMapUrl?: string }>;
}

// The statement pass is supplementary and runs before c8 publishes its report.
// Bound the amount of generated source and inline map it can parse per run.
const MAX_STATEMENT_MAP_CHARACTERS = 256 * 1024;

const port = parentPort;
if (port === null) throw new Error('Coverage collector requires a worker');

Expand Down Expand Up @@ -59,25 +55,34 @@ async function takeSnapshot(command: 'reset' | 'admit' | 'take'): Promise<Execut
}
const result = command === 'take' && workerData.admittedOnly === true ? admitted : coverage.result;
const scripts: ExecutionCoverageSnapshot['scripts'] = Object.create(null);
const statementLines: AdmittedStatementLines[] = [];
let statementCharactersRemaining = MAX_STATEMENT_MAP_CHARACTERS;
const collectStatementInputs = command === 'take' && workerData.admittedOnly === true;
const rawDirectory: string = workerData.rawDirectory;
let canWriteStatementInputs = collectStatementInputs;
let statementInputPath: string | undefined;
for (const script of command === 'take' ? result : []) {
if (!script.url.startsWith('file:')) continue;

const { scriptSource } = await post<Debugger.GetScriptSourceReturnType>(
'Debugger.getScriptSource', { scriptId: scriptIds.get(script.url) ?? script.scriptId },
);
const sourceMapUrl = parsedScripts.get(scriptIds.get(script.url) ?? script.scriptId)?.sourceMapURL;
// Work from the actual generated script in the passive isolate, before c8
// turns the report into a line map and before the separate branch converter.
const isTypeScript = /\.(?:ts|tsx|mts|cts)$/u.test(script.url);
const statementCharacters = scriptSource.length + (sourceMapUrl?.length ?? 0);
const fitsStatementBudget = statementCharacters <= statementCharactersRemaining;
if (workerData.admittedOnly === true && isTypeScript && fitsStatementBudget) {
statementCharactersRemaining -= statementCharacters;
const { admittedStatementLines } = await import('./admitted-statement-lines.js');
const evidence = admittedStatementLines(script, scriptSource, sourceMapUrl);
if (evidence !== undefined) statementLines.push(evidence);
const scriptId = scriptIds.get(script.url) ?? script.scriptId;
const source = await post<Debugger.GetScriptSourceReturnType>('Debugger.getScriptSource', { scriptId })
.catch(() => undefined);
// Raw counters remain useful when Inspector cannot supply a script's optional metadata.
if (source === undefined) continue;

const { scriptSource } = source;
const sourceMapUrl = parsedScripts.get(scriptId)?.sourceMapURL;
if (canWriteStatementInputs && /\.(?:ts|tsx|mts|cts)$/u.test(script.url)) {
// Stop after a failed append. The last record may be partial; appending again
// could corrupt the following record. Raw V8 and earlier records remain usable.
try {
if (statementInputPath === undefined) {
mkdirSync(rawDirectory, { recursive: true });
statementInputPath = path.join(rawDirectory, 'statement-inputs.ndjson');
}
const input = { url: script.url, source: scriptSource, sourceMapUrl };
appendFileSync(statementInputPath, JSON.stringify(input) + '\n');
} catch {
canWriteStatementInputs = false;
}
}

scripts[script.url] = {
Expand All @@ -92,7 +97,7 @@ async function takeSnapshot(command: 'reset' | 'admit' | 'take'): Promise<Execut
session.disconnect();
}

return { kind: 'coverage', result, scripts, admittedInvocations, statementLines };
return { kind: 'coverage', result, scripts, admittedInvocations };
}

function post<T = unknown>(method: string, params: object = {}): Promise<T> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export async function startExecutionCoverage(admittedOnly = false, timeoutMillis
const completion = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
const worker = new Worker(new URL('./execution-coverage-worker.js', import.meta.url), {
env: { ...process.env, NODE_V8_COVERAGE: '' },
workerData: { admittedOnly, completion: completion.buffer },
workerData: { admittedOnly, rawDirectory, completion: completion.buffer },
});
let workerFailure: Error | undefined;
let workerExited = false;
Expand Down Expand Up @@ -119,7 +119,6 @@ export async function startExecutionCoverage(admittedOnly = false, timeoutMillis
mkdirSync(rawDirectory, { recursive: true });
if (admittedOnly) {
writeFileSync(path.join(rawDirectory, 'admitted-count.txt'), String(reportSnapshot.admittedInvocations));
writeFileSync(path.join(rawDirectory, 'admitted-statement-lines.txt'), stringifyProtocolJson(reportSnapshot.statementLines));
}
writeFileSync(path.join(rawDirectory, `coverage-${process.pid}-usvm.json`), stringifyProtocolJson(report));
},
Expand Down
29 changes: 28 additions & 1 deletion usvm-ts-fast-check/fast-check-adapter/test/execution-cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import type { Readable } from 'node:stream';
Expand Down Expand Up @@ -56,6 +56,33 @@ export function predicate(_value: boolean): boolean { return helper(false) === 2
}
});

test('a failed optional statement spool preserves the property result and raw coverage', async () => {
const sourceRoot = await realpath(await mkdtemp(path.join(tmpdir(), 'usvm-statement-spool-')));
const raw = path.join(sourceRoot, 'raw');
try {
await writeFile(path.join(sourceRoot, 'property.ts'), 'export function predicate(value: boolean) { return value; }');
await mkdir(path.join(raw, 'statement-inputs.ndjson'), { recursive: true });
const request = executionRequest(sourceRoot);
request.admittedCoverage = true;
request.timeoutMillis = 5_000;

const invocation = await invokeCli(JSON.stringify(request), { coverageDirectory: raw, timeoutMillis: 10_000 });

assert.equal(invocation.exitCode, 0, invocation.stderr);
const response = JSON.parse(invocation.stdout) as { status: string; result: { status: string; numRuns: number } };
assert.equal(response.status, 'ok');
assert.equal(response.result.status, 'success');
assert.equal(response.result.numRuns, 1);
assert.equal(await readFile(path.join(raw, 'admitted-count.txt'), 'utf8'), '1');
const reportName = (await readdir(raw)).find(name => name.endsWith('-usvm.json'));
assert.ok(reportName);
const report = JSON.parse(await readFile(path.join(raw, reportName), 'utf8')) as { result: { url: string }[] };
assert.ok(report.result.some(script => script.url.endsWith('/property.ts')));
} finally {
await rm(sourceRoot, { recursive: true, force: true });
}
});

test('admitted snapshots merge both branch outcomes without counting shrink trials', async () => {
const sourceRoot = await realpath(await mkdtemp(path.join(tmpdir(), 'usvm-admitted-merge-')));
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package org.usvm.ts.pbt.fastcheck
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import org.usvm.ts.pbt.FastCheckDiagnosticCode
import org.usvm.ts.pbt.backend.BranchCoverage
import org.usvm.ts.pbt.backend.CoverageDiagnostic
Expand All @@ -18,6 +19,8 @@ import org.usvm.ts.pbt.coverage.mergeCoverageDiagnostics
import org.usvm.ts.pbt.manifest.PropertyManifestJson
import org.usvm.ts.pbt.model.PropertyId
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.charset.CharacterCodingException
import java.nio.file.Files
import java.nio.file.Path

Expand Down Expand Up @@ -132,7 +135,14 @@ internal class FastCheckCoverageSession private constructor(
rawDiagnostics = rawDiagnostics,
)

val branchReport = if (finalArtifact.files.isEmpty()) {
val artifactWithDiagnostics = finalArtifact.copy(diagnostics = diagnostics)
val coveredArtifact = if (coverageRequest.admittedOnly) {
applyAdmittedStatementEvidence(artifactWithDiagnostics)
} else {
artifactWithDiagnostics
}

val branchReport = if (coveredArtifact.files.isEmpty()) {
FastCheckOperationResult.Completed(
value = RawBranchReport(files = emptyList(), diagnostics = emptyList())
)
Expand All @@ -149,15 +159,7 @@ internal class FastCheckCoverageSession private constructor(
return branchTimeout
}

val artifactWithDiagnostics = finalArtifact.copy(
diagnostics = diagnostics,
admittedInvocations = admittedInvocations,
)
val artifact = if (coverageRequest.admittedOnly) {
applyAdmittedStatementEvidence(artifactWithDiagnostics)
} else {
artifactWithDiagnostics
}
val artifact = coveredArtifact.copy(admittedInvocations = admittedInvocations)

val withBranches = when (branchReport) {
is FastCheckOperationResult.Completed -> appendExactBranches(artifact, branchReport.value)
Expand Down Expand Up @@ -193,25 +195,21 @@ internal class FastCheckCoverageSession private constructor(
}

private fun applyAdmittedStatementEvidence(artifact: PropertyCoverageArtifact): PropertyCoverageArtifact {
val report = workspace.rawDirectory.resolve("admitted-statement-lines.txt")
val records = try {
PropertyManifestJson.json.decodeFromString<List<AdmittedStatementLines>>(Files.readString(report))
} catch (_: IOException) {
emptyList()
} catch (_: SerializationException) {
emptyList()
}
val evidence = records.groupBy { it.path }
val sourceFiles = artifact.files.map { it.path }.filter(::isTypeScript)
if (sourceFiles.isEmpty()) return artifact

val converterFailure = convertAdmittedStatements(sourceFiles)
val evidence = readAdmittedStatementLines().groupBy { it.path }
val diagnostics = artifact.diagnostics.toMutableList()
val files = artifact.files.map { file ->
val isTypeScript = file.path.substringAfterLast('.', missingDelimiterValue = "") in TYPESCRIPT_EXTENSIONS
val source = evidence[file.path]?.singleOrNull()
val hasUnverifiedHits = file.statements.any { it.hits > 0 }
if (!isTypeScript || source == null && !hasUnverifiedHits) return@map file
if (!isTypeScript(file.path) || source == null && !hasUnverifiedHits) return@map file
if (source == null || source.partial) {
diagnostics += CoverageDiagnostic(
code = FastCheckDiagnosticCode.COVERAGE_STATEMENT_PARTIAL,
message = "Some TypeScript statement lines have no unambiguous admitted-execution evidence",
message = converterFailure
?: "Some TypeScript statement lines have no unambiguous admitted-execution evidence",
path = file.path,
)
}
Expand All @@ -228,6 +226,84 @@ internal class FastCheckCoverageSession private constructor(
return artifact.copy(files = files, diagnostics = diagnostics)
}

private fun isTypeScript(path: String): Boolean =
path.substringAfterLast('.', missingDelimiterValue = "") in TYPESCRIPT_EXTENSIONS

private fun convertAdmittedStatements(sourceFiles: List<String>): String? {
val input = workspace.rawDirectory.resolve("statement-inputs.ndjson")
if (!Files.isRegularFile(input)) return null

val timeoutMillis = remainingMillis?.invoke() ?: DEFAULT_STATEMENT_CONVERSION_TIMEOUT_MILLIS
if (timeoutMillis <= 0) return "Coverage deadline expired before TypeScript statement conversion"

val converter = workspace.adapterRoot.resolve("dist/src/admitted-statement-converter.js")
val transport = FastCheckProcessTransport(
nodeExecutable = nodeExecutable,
maxRequestBytes = MAX_BRANCH_REPORT_BYTES,
maxStdoutBytes = 1,
maxStderrBytes = MAX_BRANCH_ERROR_BYTES,
shutdownGraceMillis = BRANCH_SHUTDOWN_GRACE_MILLIS,
)
val result = try {
transport.invokeWithResult(
command = listOf(nodeExecutable, converter.toString(), workspace.rawDirectory.toString()),
request = PropertyManifestJson.json.encodeToString(sourceFiles),
timeoutMillis = timeoutMillis,
reportedTimeoutMillis = timeoutMillis,
description = "TypeScript statement converter",
)
} catch (error: FastCheckTransportException) {
return "Cannot convert TypeScript statements: ${error.message}"
}

return when (result) {
is FastCheckOperationResult.TimedOut -> result.message
is FastCheckOperationResult.Completed -> if (result.value.exitCode == 0) {
null
} else {
"TypeScript statement conversion failed: ${result.value.stderr.trim()}"
}
}
}

private fun readAdmittedStatementLines(): List<AdmittedStatementLines> {
val report = workspace.rawDirectory.resolve("admitted-statement-lines.ndjson")
if (Files.isRegularFile(report)) {
val records = mutableListOf<AdmittedStatementLines>()
try {
// Split on the ASCII line delimiter before decoding UTF-8. A truncated
// multibyte character must only invalidate its own record.
Files.newBufferedReader(report, Charsets.ISO_8859_1).useLines { lines ->
lines.mapNotNull(::decodeStatementLine).toCollection(records)
}
} catch (_: IOException) {
// Retain records read before the I/O error.
}
return records
}

val legacyReport = workspace.rawDirectory.resolve("admitted-statement-lines.txt")
return try {
PropertyManifestJson.json.decodeFromString<List<AdmittedStatementLines>>(Files.readString(legacyReport))
} catch (_: IOException) {
emptyList()
} catch (_: SerializationException) {
emptyList()
}
}

private fun decodeStatementLine(line: String): AdmittedStatementLines? {
return try {
val bytes = ByteBuffer.wrap(line.toByteArray(Charsets.ISO_8859_1))
val record = Charsets.UTF_8.newDecoder().decode(bytes).toString()
PropertyManifestJson.json.decodeFromString<AdmittedStatementLines>(record)
} catch (_: CharacterCodingException) {
null
} catch (_: SerializationException) {
null
}
}

private fun propertyEntryPointPaths(): Set<String> {
val paths = hashSetOf<String>()
val entryPoints = listOfNotNull(request.manifest.predicate, request.manifest.precondition)
Expand Down Expand Up @@ -554,6 +630,7 @@ internal class FastCheckCoverageSession private constructor(
private const val VERSION_SHUTDOWN_GRACE_MILLIS = 100L
private const val MAX_VERSION_OUTPUT_BYTES = 1_000

private const val DEFAULT_STATEMENT_CONVERSION_TIMEOUT_MILLIS = 60_000L
private const val BRANCH_CONVERSION_TIMEOUT_MILLIS = 10_000L
private const val BRANCH_SHUTDOWN_GRACE_MILLIS = 500L
private const val MAX_BRANCH_REPORT_BYTES = 10_000_000
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,14 +130,9 @@ class FastCheckProcessClientTest {
for (expireBeforeBranchConversion in listOf(false, true)) {
marker.deleteIfExists()
val result = if (expireBeforeBranchConversion) {
var startedReadingReport = false
var readsAfterProperty = 0
client.check(request = request, remainingMillis = {
if (Files.exists(marker) && startedReadingReport) {
0L
} else {
startedReadingReport = Files.exists(marker)
10_000L
}
if (Files.exists(marker) && readsAfterProperty++ >= 2) 0L else 10_000L
})
} else {
backend.run(property, configuration)
Expand Down
Loading
Loading