From eb3aaf64aad8a33137c58aa3165a13a4a5a43879 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Fri, 4 Dec 2026 06:57:08 +0100 Subject: [PATCH 1/2] [TS PBT] Convert admitted statement coverage after property execution --- .../src/admitted-statement-converter.ts | 44 ++++++++ .../src/execution-coverage-worker.ts | 30 ++--- .../src/execution-coverage.ts | 3 +- .../pbt/fastcheck/FastCheckCoverageSession.kt | 106 ++++++++++++++---- .../fastcheck/FastCheckProcessClientTest.kt | 9 +- .../FastCheckStatementConversionTest.kt | 106 ++++++++++++++++++ .../fastcheck/FastCheckWitnessTimeoutTest.kt | 5 +- 7 files changed, 251 insertions(+), 52 deletions(-) create mode 100644 usvm-ts-fast-check/fast-check-adapter/src/admitted-statement-converter.ts create mode 100644 usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckStatementConversionTest.kt diff --git a/usvm-ts-fast-check/fast-check-adapter/src/admitted-statement-converter.ts b/usvm-ts-fast-check/fast-check-adapter/src/admitted-statement-converter.ts new file mode 100644 index 0000000000..3a6b302d43 --- /dev/null +++ b/usvm-ts-fast-check/fast-check-adapter/src/admitted-statement-converter.ts @@ -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'); +} diff --git a/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage-worker.ts b/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage-worker.ts index 4a6d5dfdb8..c28005f484 100644 --- a/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage-worker.ts +++ b/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage-worker.ts @@ -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; } -// 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'); @@ -59,8 +55,9 @@ async function takeSnapshot(command: 'reset' | 'admit' | 'take'): Promise(method: string, params: object = {}): Promise { diff --git a/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage.ts b/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage.ts index c9e5757cc5..22ade7b61b 100644 --- a/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage.ts +++ b/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage.ts @@ -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; @@ -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)); }, diff --git a/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckCoverageSession.kt b/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckCoverageSession.kt index 22c2b3d0e1..5fcddccd9b 100644 --- a/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckCoverageSession.kt +++ b/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckCoverageSession.kt @@ -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 @@ -132,7 +133,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()) ) @@ -149,15 +157,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) @@ -193,25 +193,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>(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, ) } @@ -228,6 +224,71 @@ 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? { + 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 { + val report = workspace.rawDirectory.resolve("admitted-statement-lines.ndjson") + if (Files.isRegularFile(report)) { + return Files.newBufferedReader(report).useLines { lines -> + lines.mapNotNull { line -> + // A timed-out converter may leave an incomplete final record. + try { + PropertyManifestJson.json.decodeFromString(line) + } catch (_: SerializationException) { + null + } + }.toList() + } + } + + val legacyReport = workspace.rawDirectory.resolve("admitted-statement-lines.txt") + return try { + PropertyManifestJson.json.decodeFromString>(Files.readString(legacyReport)) + } catch (_: IOException) { + emptyList() + } catch (_: SerializationException) { + emptyList() + } + } + private fun propertyEntryPointPaths(): Set { val paths = hashSetOf() val entryPoints = listOfNotNull(request.manifest.predicate, request.manifest.precondition) @@ -554,6 +615,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 diff --git a/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckProcessClientTest.kt b/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckProcessClientTest.kt index a832406af8..a14d663b35 100644 --- a/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckProcessClientTest.kt +++ b/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckProcessClientTest.kt @@ -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) diff --git a/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckStatementConversionTest.kt b/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckStatementConversionTest.kt new file mode 100644 index 0000000000..4d85bff2b3 --- /dev/null +++ b/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckStatementConversionTest.kt @@ -0,0 +1,106 @@ +package org.usvm.ts.pbt.fastcheck + +import kotlinx.serialization.json.JsonPrimitive +import org.junit.jupiter.api.Test +import org.usvm.ts.pbt.FastCheckDiagnosticCode +import org.usvm.ts.pbt.backend.CoverageScope +import org.usvm.ts.pbt.backend.PropertyCoverageRequest +import org.usvm.ts.pbt.backend.PropertyRunConfiguration +import org.usvm.ts.pbt.backend.PropertyRunStatus +import org.usvm.ts.pbt.manifest.toManifest +import org.usvm.ts.pbt.model.BooleanDomain +import org.usvm.ts.pbt.model.PropertyDefinition +import org.usvm.ts.pbt.model.PropertyId +import org.usvm.ts.pbt.model.PropertyInput +import org.usvm.ts.pbt.model.TypeScriptEntryPoint +import java.nio.file.Files +import kotlin.io.path.createTempDirectory +import kotlin.io.path.deleteIfExists +import kotlin.io.path.readText +import kotlin.io.path.writeText +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +class FastCheckStatementConversionTest { + @Test + fun `large TypeScript statement reports use the remaining coverage budget`() { + val directory = createTempDirectory(prefix = "large-admitted-statements-") + val marker = directory.resolve("completed") + val increments = 20_000 + val largeFunction = " count++;\n".repeat(increments) + val source = """ + import { writeFileSync } from 'node:fs'; + function unused(): number { + return -1; + } + export function predicate(_value: boolean): boolean { + let count = 0; + ${largeFunction.trimEnd()} + writeFileSync(${JsonPrimitive(marker.toString())}, String(count)); + return count === $increments; + } + """.trimIndent() + directory.resolve("property.ts").writeText(source) + val coverageRequest = PropertyCoverageRequest( + scopes = setOf(CoverageScope.PROPERTY_ENTRY_POINTS), + admittedOnly = true, + ) + val configuration = PropertyRunConfiguration( + seed = 42, + numRuns = 1, + timeoutMillis = 10_000, + coverageRequest = coverageRequest, + ) + val property = PropertyDefinition( + id = PropertyId("example.large-statements"), + inputs = listOf(PropertyInput(name = "value", domain = BooleanDomain)), + predicate = TypeScriptEntryPoint(module = "property.ts", exportName = "predicate"), + ) + val backend = FastCheckBackend(sourceRoots = listOf(directory)) + val client = FastCheckProcessClient(adapterEntryPoint = FastCheckRuntime.executionEntryPoint()) + val request = FastCheckExecutionRequest( + manifest = property.toManifest(), + seed = configuration.seed, + sourceRoots = listOf(directory.toRealPath().toString()), + numRuns = configuration.numRuns, + timeoutMillis = configuration.timeoutMillis, + coverageRequest = coverageRequest, + admittedCoverage = true, + ) + + try { + val completed = backend.run(property, configuration) + + assertEquals(PropertyRunStatus.SUCCESS, completed.status) + assertEquals(increments.toString(), marker.readText()) + val hits = assertNotNull(completed.coverage).files.single().statements + val lines = source.lines().map(String::trim) + val coveredIncrements = hits.count { statement -> + lines[statement.location.start.line - 1] == "count++;" && statement.hits == 1L + } + assertEquals(increments, coveredIncrements) + val uncalledLine = lines.indexOf("return -1;") + 1 + assertEquals(0L, hits.single { it.location.start.line == uncalledLine }.hits) + + marker.deleteIfExists() + var readsAfterProperty = 0 + val partial = client.check(request = request, remainingMillis = { + if (Files.exists(marker) && readsAfterProperty++ >= 1) 0L else 20_000L + }) + + assertEquals(PropertyRunStatus.SUCCESS, partial.status) + assertEquals(1, partial.numRuns) + assertEquals(increments.toString(), marker.readText()) + val coverage = assertNotNull(partial.coverage) + assertEquals(1, coverage.admittedInvocations) + assertTrue(coverage.files.single().statements.isEmpty()) + val hasPartialStatements = coverage.diagnostics.any { diagnostic -> + diagnostic.code == FastCheckDiagnosticCode.COVERAGE_STATEMENT_PARTIAL + } + assertTrue(hasPartialStatements) + } finally { + directory.toFile().deleteRecursively() + } + } +} diff --git a/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckWitnessTimeoutTest.kt b/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckWitnessTimeoutTest.kt index 4ad881928e..076ae6383b 100644 --- a/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckWitnessTimeoutTest.kt +++ b/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckWitnessTimeoutTest.kt @@ -139,8 +139,9 @@ class FastCheckWitnessTimeoutTest { rawDirectory.resolve("coverage-1-1-1.json").writeText("""{"result":[]}""") val admittedCount = rawDirectory.resolve("admitted-count.txt") admittedCount.writeText("3") - val statementEvidence = rawDirectory.resolve("admitted-statement-lines.txt") - statementEvidence.writeText("""[{"path":$path,"hits":{"1":3},"partial":false}]""") + val statementEvidence = rawDirectory.resolve("admitted-statement-lines.ndjson") + val completedFile = """{"path":$path,"hits":{"1":3},"partial":false}""" + statementEvidence.writeText(completedFile + "\n" + """{"path":""") readingReport = true val result = it.readArtifact() From 0b67b515b35aa958d13e07481220674917205288 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Fri, 4 Dec 2026 07:23:05 +0100 Subject: [PATCH 2/2] [TS PBT] Preserve results when optional statement coverage I/O fails --- .../src/execution-coverage-worker.ts | 33 +++++++++++++------ .../test/execution-cli.test.ts | 29 +++++++++++++++- .../pbt/fastcheck/FastCheckCoverageSession.kt | 33 ++++++++++++++----- .../fastcheck/FastCheckWitnessTimeoutTest.kt | 3 +- 4 files changed, 77 insertions(+), 21 deletions(-) diff --git a/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage-worker.ts b/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage-worker.ts index c28005f484..428307b24f 100644 --- a/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage-worker.ts +++ b/usvm-ts-fast-check/fast-check-adapter/src/execution-coverage-worker.ts @@ -57,19 +57,32 @@ async function takeSnapshot(command: 'reset' | 'admit' | 'take'): Promise( - 'Debugger.getScriptSource', { scriptId: scriptIds.get(script.url) ?? script.scriptId }, - ); - const sourceMapUrl = parsedScripts.get(scriptIds.get(script.url) ?? script.scriptId)?.sourceMapURL; - if (collectStatementInputs && /\.(?:ts|tsx|mts|cts)$/u.test(script.url)) { - // Persist the actual generated code while the inspector is still attached. - // The consumer converts it only after the property result is available. - const input = { url: script.url, source: scriptSource, sourceMapUrl }; - appendFileSync(path.join(rawDirectory, 'statement-inputs.ndjson'), JSON.stringify(input) + '\n'); + const scriptId = scriptIds.get(script.url) ?? script.scriptId; + const source = await post('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] = { diff --git a/usvm-ts-fast-check/fast-check-adapter/test/execution-cli.test.ts b/usvm-ts-fast-check/fast-check-adapter/test/execution-cli.test.ts index 5bad9fd5cf..57fcba098e 100644 --- a/usvm-ts-fast-check/fast-check-adapter/test/execution-cli.test.ts +++ b/usvm-ts-fast-check/fast-check-adapter/test/execution-cli.test.ts @@ -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'; @@ -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 { diff --git a/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckCoverageSession.kt b/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckCoverageSession.kt index 5fcddccd9b..567cd0843d 100644 --- a/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckCoverageSession.kt +++ b/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckCoverageSession.kt @@ -19,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 @@ -267,16 +269,17 @@ internal class FastCheckCoverageSession private constructor( private fun readAdmittedStatementLines(): List { val report = workspace.rawDirectory.resolve("admitted-statement-lines.ndjson") if (Files.isRegularFile(report)) { - return Files.newBufferedReader(report).useLines { lines -> - lines.mapNotNull { line -> - // A timed-out converter may leave an incomplete final record. - try { - PropertyManifestJson.json.decodeFromString(line) - } catch (_: SerializationException) { - null - } - }.toList() + val records = mutableListOf() + 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") @@ -289,6 +292,18 @@ internal class FastCheckCoverageSession private constructor( } } + 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(record) + } catch (_: CharacterCodingException) { + null + } catch (_: SerializationException) { + null + } + } + private fun propertyEntryPointPaths(): Set { val paths = hashSetOf() val entryPoints = listOfNotNull(request.manifest.predicate, request.manifest.precondition) diff --git a/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckWitnessTimeoutTest.kt b/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckWitnessTimeoutTest.kt index 076ae6383b..48748f866f 100644 --- a/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckWitnessTimeoutTest.kt +++ b/usvm-ts-fast-check/src/test/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckWitnessTimeoutTest.kt @@ -141,7 +141,8 @@ class FastCheckWitnessTimeoutTest { admittedCount.writeText("3") val statementEvidence = rawDirectory.resolve("admitted-statement-lines.ndjson") val completedFile = """{"path":$path,"hits":{"1":3},"partial":false}""" - statementEvidence.writeText(completedFile + "\n" + """{"path":""") + val cutOffPath = """{"path":"/tmp/café""".encodeToByteArray().dropLast(1).toByteArray() + Files.write(statementEvidence, (completedFile + "\n").encodeToByteArray() + cutOffPath) readingReport = true val result = it.readArtifact()