diff --git a/usvm-ts-fast-check/fast-check-adapter/src/admitted-statement-lines.ts b/usvm-ts-fast-check/fast-check-adapter/src/admitted-statement-lines.ts new file mode 100644 index 0000000000..b11200a40c --- /dev/null +++ b/usvm-ts-fast-check/fast-check-adapter/src/admitted-statement-lines.ts @@ -0,0 +1,182 @@ +import { generatedPositionFor, originalPositionFor, TraceMap } from '@jridgewell/trace-mapping'; +import type { Profiler } from 'node:inspector'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; + +export interface AdmittedStatementLines { + path: string; + hits: Record; + partial: boolean; +} + +/** V8 range evidence at mapped TypeScript statement starts, aggregated by source line. */ +export function admittedStatementLines( + script: Profiler.ScriptCoverage, + generatedSource: string, + sourceMapUrl: string | undefined, +): AdmittedStatementLines | undefined { + const prefix = 'data:application/json;base64,'; + if (!sourceMapUrl?.startsWith(prefix)) return undefined; + + let map: TraceMap; + try { + map = new TraceMap(Buffer.from(sourceMapUrl.slice(prefix.length), 'base64').toString(), script.url); + } catch { + return undefined; + } + const [sourceUrl] = map.resolvedSources; + const [source] = map.sourcesContent ?? []; + if (sourceUrl === undefined || map.resolvedSources.length !== 1 || + sourceUrl !== script.url || typeof source !== 'string') return undefined; + const mappedSource = sourceUrl; + + const path = fileURLToPath(sourceUrl); + const original = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true); + const generated = ts.createSourceFile('generated.js', generatedSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS); + const functionsByEnd = new Map(); + for (const fn of script.functions) { + const root = fn.ranges[0]; + if (root === undefined) continue; + + const group = functionsByEnd.get(root.endOffset) ?? []; + group.push({ fn, root }); + functionsByEnd.set(root.endOffset, group); + } + + const generatedEnd = generated.statements.at(-1)?.getEnd() ?? 0; + const scriptOwners = script.functions.filter(fn => + fn.functionName === '' && fn.ranges[0]?.startOffset === 0 && fn.ranges[0].endOffset >= generatedEnd); + const scriptCount = scopeCount(scriptOwners); + const matchedFunctions = new Set(scriptOwners); + const owners: Interval<(offset: number) => number | undefined>[] = []; + let unmatchedObservedFunction = false; + + function collectOwners(node: ts.Node): void { + if (ts.isFunctionLike(node) && 'body' in node && node.body !== undefined) { + const start = node.getStart(generated); + const bodyStart = node.body.getStart(generated); + const end = node.getEnd(); + const candidates = (functionsByEnd.get(end) ?? []) + .filter(({ root }) => root.startOffset >= start && root.startOffset <= bodyStart) + .map(({ fn }) => fn); + candidates.forEach(fn => matchedFunctions.add(fn)); + + // Absence is only evidence of zero if all observed function roots can + // be accounted for. A shifted or otherwise unmatched root is ambiguous. + const count = candidates.length === 0 + ? () => unmatchedObservedFunction ? undefined : 0 + : scopeCount(candidates); + owners.push({ start: bodyStart, end, value: count }); + } else if (ts.isClassStaticBlockDeclaration(node) || ts.isPropertyDeclaration(node)) { + const body = ts.isClassStaticBlockDeclaration(node) ? node.body : node.initializer; + const isStatic = ts.isClassStaticBlockDeclaration(node) || + node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.StaticKeyword); + if (body !== undefined) { + const classStart = node.parent.getStart(generated); + const classEnd = node.parent.getEnd(); + const start = body.getStart(generated); + const end = body.getEnd(); + const name = isStatic ? '' : ''; + const candidates = (functionsByEnd.get(classEnd) ?? []) + .filter(({ fn, root }) => fn.functionName === name && root.startOffset >= classStart && root.startOffset <= start) + .map(({ fn }) => fn); + owners.push({ start, end, value: scopeCount(candidates) }); + } + } + ts.forEachChild(node, collectOwners); + } + collectOwners(generated); + unmatchedObservedFunction = script.functions.some(fn => !matchedFunctions.has(fn) && + fn.functionName !== '' && fn.functionName !== ''); + const ownerAt = innermostAt(owners); + + const lines = new Map(); + const lineStarts = generated.getLineStarts(); + function visit(node: ts.Node): void { + const isRuntimeStatement = ts.isStatement(node) && !ts.isBlock(node) && !ts.isDeclarationStatement(node); + const isConciseArrowBody = node.parent !== undefined && ts.isArrowFunction(node.parent) && node.parent.body === node && !ts.isBlock(node); + const isAnchor = isRuntimeStatement || isConciseArrowBody || ts.isVariableStatement(node) || ts.isClassDeclaration(node); + const anchor = ts.isPropertyDeclaration(node) ? node.initializer : isAnchor ? node : undefined; + if (anchor !== undefined) { + const position = original.getLineAndCharacterOfPosition(anchor.getStart(original)); + const line = position.line + 1; + const column = position.character; + const mapped = generatedPositionFor(map, { source: mappedSource, line, column }); + let count: number | undefined; + if (mapped.line !== null && mapped.column !== null) { + const back = originalPositionFor(map, { line: mapped.line, column: mapped.column }); + if (back.source === sourceUrl && back.line === line && back.column === column) { + const lineStart = lineStarts[mapped.line - 1]; + const lineEnd = lineStarts[mapped.line] ?? generatedSource.length; + if (lineStart !== undefined && lineStart + mapped.column < lineEnd) { + const offset = lineStart + mapped.column; + const countInScope = ownerAt(offset) ?? scriptCount; + count = countInScope(offset); + } + } + } + + const previous = lines.get(line); + const mixedEvidence = previous !== undefined && count !== undefined && (previous === 0) !== (count === 0); + lines.set(line, count === undefined || lines.has(line) && (previous === undefined || mixedEvidence) + ? undefined : Math.max(previous ?? 0, count)); + } + ts.forEachChild(node, visit); + } + visit(original); + + const hits: AdmittedStatementLines['hits'] = {}; + for (const [line, count] of lines) { + if (count !== undefined) hits[line] = count; + } + return { path, hits, partial: Object.keys(hits).length !== lines.size }; +} + +function scopeCount(candidates: Profiler.FunctionCoverage[]): (offset: number) => number | undefined { + const [fn] = candidates; + if (candidates.length !== 1 || fn === undefined) return () => undefined; + if (fn.ranges[0]?.count === 0) return () => 0; + if (!fn.isBlockCoverage) return () => undefined; + + return innermostAt(fn.ranges.map(range => ({ start: range.startOffset, end: range.endOffset, value: range.count }))); +} + +interface Interval { + start: number; + end: number; + value: T; +} + +/** AST scopes and V8 block ranges are each nested or disjoint. */ +function innermostAt(intervals: Interval[]): (offset: number) => T | undefined { + const ordered = intervals.sort((left, right) => left.start - right.start || right.end - left.end); + const active: Interval[] = []; + const changes: { offset: number; value: T | undefined }[] = []; + function closeBefore(offset: number): void { + while (active.length !== 0) { + const inner = active[active.length - 1]!; + if (inner.end > offset) break; + + active.pop(); + changes.push({ offset: inner.end, value: active.at(-1)?.value }); + } + } + + for (const interval of ordered) { + closeBefore(interval.start); + active.push(interval); + changes.push({ offset: interval.start, value: interval.value }); + } + closeBefore(Infinity); + + return offset => { + let low = 0; + let high = changes.length; + while (low < high) { + const mid = Math.floor((low + high) / 2); + if (changes[mid]!.offset <= offset) low = mid + 1; + else high = mid; + } + return changes[low - 1]?.value; + }; +} 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 0f1ed38a83..4a6d5dfdb8 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,14 +1,20 @@ 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'); @@ -53,6 +59,8 @@ async function takeSnapshot(command: 'reset' | 'admit' | 'take'): Promise line.length), @@ -72,7 +92,7 @@ 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 ae613942a9..c9e5757cc5 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 @@ -119,6 +119,7 @@ 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/FastCheckDiagnosticCode.kt b/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/FastCheckDiagnosticCode.kt index a56ba2d6c1..60e3a667ab 100644 --- a/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/FastCheckDiagnosticCode.kt +++ b/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/FastCheckDiagnosticCode.kt @@ -45,6 +45,7 @@ internal object FastCheckDiagnosticCode { const val COVERAGE_COLLECTOR_NOT_FOUND = "coverage.collector.not-found" const val COVERAGE_COLLECTION_TIMEOUT = "coverage.collection.timeout" + const val COVERAGE_STATEMENT_PARTIAL = "coverage.statement.partial" const val COVERAGE_RUNTIME_UNSUPPORTED = "coverage.runtime.unsupported" const val COVERAGE_RUNTIME_VERSION_UNAVAILABLE = "coverage.runtime.version-unavailable" 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 e822f177fe..22c2b3d0e1 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 @@ -1,6 +1,7 @@ package org.usvm.ts.pbt.fastcheck import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException import kotlinx.serialization.decodeFromString import org.usvm.ts.pbt.FastCheckDiagnosticCode import org.usvm.ts.pbt.backend.BranchCoverage @@ -40,10 +41,17 @@ internal class FastCheckCoverageSession private constructor( add("--exclude-after-remap") add("--allowExternal") add("--exclude=__usvm_no_default_excludes__") - if (requireNotNull(request.coverageRequest).includeUnexecutedSources) { + val coverageRequest = requireNotNull(request.coverageRequest) + if (coverageRequest.admittedOnly) { + // Keep c8's default extensions and include tsx's other TypeScript module formats. + for (extension in listOf("js", "cjs", "mjs", "jsx") + TYPESCRIPT_EXTENSIONS) { + add("--extension=.$extension") + } + } + if (coverageRequest.includeUnexecutedSources) { add("--all") request.sourceRoots.forEach { sourceRoot -> add("--src=$sourceRoot") } - requireNotNull(request.coverageRequest).includePatterns.forEach { pattern -> + coverageRequest.includePatterns.forEach { pattern -> val include = Path.of(pattern) if (include.isAbsolute) { add("--include=$include") @@ -54,7 +62,7 @@ internal class FastCheckCoverageSession private constructor( } } } - if (CoverageScope.DEPENDENCIES in requireNotNull(request.coverageRequest).scopes) { + if (CoverageScope.DEPENDENCIES in coverageRequest.scopes) { add("--exclude-node-modules=false") } add(nodeExecutable) @@ -133,28 +141,29 @@ internal class FastCheckCoverageSession private constructor( } val branchTimeout = branchReport as? FastCheckOperationResult.TimedOut val admittedInvocations = if (coverageRequest.admittedOnly) { - val count = try { - Files.readString(workspace.rawDirectory.resolve("admitted-count.txt")).trim() - } catch (error: IOException) { - if (branchTimeout != null) return branchTimeout - throw error - } - val admittedCount = count.toIntOrNull() - if (branchTimeout != null && (admittedCount == null || admittedCount < 0)) return branchTimeout - admittedCount ?: count.toInt() + readAdmittedInvocations(branchTimedOut = branchTimeout != null) } else { null } + if (coverageRequest.admittedOnly && admittedInvocations == null && branchTimeout != null) { + return branchTimeout + } - val artifact = finalArtifact.copy( + val artifactWithDiagnostics = finalArtifact.copy( diagnostics = diagnostics, admittedInvocations = admittedInvocations, ) + val artifact = if (coverageRequest.admittedOnly) { + applyAdmittedStatementEvidence(artifactWithDiagnostics) + } else { + artifactWithDiagnostics + } + val withBranches = when (branchReport) { is FastCheckOperationResult.Completed -> appendExactBranches(artifact, branchReport.value) is FastCheckOperationResult.TimedOut -> artifact.copy( files = artifact.files.map { file -> file.copy(branches = emptyList()) }, - diagnostics = diagnostics + CoverageDiagnostic( + diagnostics = artifact.diagnostics + CoverageDiagnostic( code = FastCheckDiagnosticCode.COVERAGE_COLLECTION_TIMEOUT, message = "Exact TypeScript branch coverage unavailable: ${branchReport.message}", ), @@ -171,6 +180,54 @@ internal class FastCheckCoverageSession private constructor( } } + private fun readAdmittedInvocations(branchTimedOut: Boolean): Int? { + val count = try { + Files.readString(workspace.rawDirectory.resolve("admitted-count.txt")).trim() + } catch (error: IOException) { + if (branchTimedOut) return null + throw error + } + + if (branchTimedOut) return count.toIntOrNull()?.takeIf { it >= 0 } + return count.toInt() + } + + 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 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 (source == null || source.partial) { + diagnostics += CoverageDiagnostic( + code = FastCheckDiagnosticCode.COVERAGE_STATEMENT_PARTIAL, + message = "Some TypeScript statement lines have no unambiguous admitted-execution evidence", + path = file.path, + ) + } + + // Istanbul's entries here are source lines. Keep their ranges and IDs, + // but only use counts backed by a mapped statement in its own V8 scope. + val statements = file.statements.mapNotNull { statement -> + val hits = source?.hits?.get(statement.location.start.line) ?: return@mapNotNull null + statement.copy(hits = hits) + } + file.copy(statements = statements) + } + + return artifact.copy(files = files, diagnostics = diagnostics) + } + private fun propertyEntryPointPaths(): Set { val paths = hashSetOf() val entryPoints = listOfNotNull(request.manifest.predicate, request.manifest.precondition) @@ -491,6 +548,8 @@ internal class FastCheckCoverageSession private constructor( cause = cause, ) + private val TYPESCRIPT_EXTENSIONS = setOf("ts", "tsx", "mts", "cts") + private const val NODE_VERSION_TIMEOUT_MILLIS = 5_000L private const val VERSION_SHUTDOWN_GRACE_MILLIS = 100L private const val MAX_VERSION_OUTPUT_BYTES = 1_000 @@ -525,3 +584,10 @@ private data class CoverageWorkspace( val c8EntryPoint: Path, val adapterRoot: Path, ) + +@Serializable +private data class AdmittedStatementLines( + val path: String, + val hits: Map, + val partial: Boolean, +) 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 cf67f0fcdd..a832406af8 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 @@ -2,8 +2,10 @@ package org.usvm.ts.pbt.fastcheck 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.PropertyFailureKind +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 @@ -67,6 +69,167 @@ class FastCheckProcessClientTest { } } + @Test + fun `admitted statement lines require evidence from their own execution scope even after a branch timeout`() { + val directory = createTempDirectory(prefix = "admitted-statement-lines-") + val marker = directory.resolve("completed") + val source = """ + import { writeFileSync } from 'node:fs'; + class Subject { + select(trace: string[]): void { + const invoke = () => { + trace.push('called nested body'); + }; + const skip = () => { + trace.push('uncalled nested body'); + }; + invoke(); + trace.push('before guard'); + if (trace.length === 2) { + trace.push('taken arm'); + } else { + trace.push('untaken arm'); + } + if (trace.length === 0) trace.push('same line, untaken'); + } + + clear(trace: string[]): void { + trace.push('uncalled method body'); + } + } + + export function predicate(_value: boolean): boolean { + const trace: string[] = []; + new Subject().select(trace); + writeFileSync(${marker.toJavaScriptStringLiteral()}, trace.join(';')); + return trace.join(';') === 'called nested body;before guard;taken arm'; + } + """.trimIndent() + directory.resolve("property.ts").writeText(source) + val client = FastCheckProcessClient(adapterEntryPoint = FastCheckRuntime.executionEntryPoint()) + val backend = FastCheckBackend(sourceRoots = listOf(directory)) + val coverageRequest = PropertyCoverageRequest( + scopes = setOf(CoverageScope.PROPERTY_ENTRY_POINTS), + admittedOnly = true, + ) + val configuration = PropertyRunConfiguration( + seed = 42, + numRuns = 1, + timeoutMillis = 5_000, + coverageRequest = coverageRequest, + ) + val request = validRequest.copy( + sourceRoots = listOf(directory.toRealPath().toString()), + numRuns = configuration.numRuns, + timeoutMillis = configuration.timeoutMillis, + coverageRequest = coverageRequest, + admittedCoverage = true, + ) + + try { + for (expireBeforeBranchConversion in listOf(false, true)) { + marker.deleteIfExists() + val result = if (expireBeforeBranchConversion) { + var startedReadingReport = false + client.check(request = request, remainingMillis = { + if (Files.exists(marker) && startedReadingReport) { + 0L + } else { + startedReadingReport = Files.exists(marker) + 10_000L + } + }) + } else { + backend.run(property, configuration) + } + + assertEquals(PropertyRunStatus.SUCCESS, result.status) + assertEquals("called nested body;before guard;taken arm", marker.readText()) + val coverage = assertNotNull(result.coverage) + assertEquals(1, coverage.admittedInvocations) + val file = coverage.files.single() + val hits = file.statements.associate { statement -> statement.location.start.line to statement.hits } + assertScopedStatementHits(source, hits) + assertTrue(coverage.diagnostics.any { it.code == FastCheckDiagnosticCode.COVERAGE_STATEMENT_PARTIAL }) + val branchTimedOut = coverage.diagnostics.any { + it.code == FastCheckDiagnosticCode.COVERAGE_COLLECTION_TIMEOUT + } + assertEquals(expireBeforeBranchConversion, branchTimedOut) + if (expireBeforeBranchConversion) assertTrue(file.branches.isEmpty()) + } + } finally { + directory.toFile().deleteRecursively() + } + } + + private fun assertScopedStatementHits(source: String, hits: Map) { + val lines = source.lines().map { it.trim() } + val expectedHits = mapOf( + "trace.push('called nested body');" to 1L, + "trace.push('uncalled nested body');" to 0L, + "trace.push('before guard');" to 1L, + "if (trace.length === 2) {" to 1L, + "trace.push('taken arm');" to 1L, + "trace.push('untaken arm');" to 0L, + "trace.push('uncalled method body');" to 0L, + ) + for ((statement, expected) in expectedHits) { + val line = lines.indexOf(statement) + 1 + assertTrue(line > 0, statement) + assertEquals(expected, hits[line], statement) + } + val mixedLine = lines.indexOf("if (trace.length === 0) trace.push('same line, untaken');") + 1 + assertTrue(mixedLine > 0) + assertFalse(mixedLine in hits) + } + + @Test + fun `admitted statement evidence omits mixed field and method lines in every TypeScript module format`() { + val directory = createTempDirectory(prefix = "admitted-mixed-statement-lines-") + val backend = FastCheckBackend(sourceRoots = listOf(directory)) + val configuration = PropertyRunConfiguration( + seed = 42, + numRuns = 1, + timeoutMillis = 5_000, + coverageRequest = PropertyCoverageRequest( + scopes = setOf(CoverageScope.PROPERTY_ENTRY_POINTS), + admittedOnly = true, + ), + ) + + try { + for (extension in listOf("ts", "mts", "cts", "tsx")) { + val module = "mixed.$extension" + directory.resolve(module).writeText( + """ + let trace = ''; + class Subject { + value = (trace += 'field', 1); skip() { trace += 'unexpected'; } + } + export function predicate(_value: boolean) { + const subject = new Subject(); + return subject.value === 1 && trace === 'field'; + } + """.trimIndent() + ) + val definition = property.copy( + predicate = TypeScriptEntryPoint(module = module, exportName = "predicate"), + ) + + val result = backend.run(definition, configuration) + + assertEquals(PropertyRunStatus.SUCCESS, result.status, module) + val coverage = assertNotNull(result.coverage) + val hits = coverage.files.single().statements.associate { it.location.start.line to it.hits } + assertFalse(3 in hits, module) + assertEquals(1L, hits[7], module) + assertTrue(coverage.diagnostics.any { it.code == FastCheckDiagnosticCode.COVERAGE_STATEMENT_PARTIAL }) + } + } finally { + directory.toFile().deleteRecursively() + } + } + @Test fun `interrupted coverage version probe terminates its process and preserves interruption`() { val runtime = createTempDirectory(prefix = "interrupted-version-probe-") 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 d56493f127..4ad881928e 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,6 +139,8 @@ 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}]""") readingReport = true val result = it.readArtifact() @@ -150,6 +152,19 @@ class FastCheckWitnessTimeoutTest { assertTrue(file.branches.isEmpty()) assertEquals(FastCheckDiagnosticCode.COVERAGE_COLLECTION_TIMEOUT, artifact.diagnostics.single().code) + Files.delete(statementEvidence) + budgetReads = 0 + + val legacyResult = it.readArtifact() + val legacyArtifact = assertIs>( + legacyResult + ).value + assertTrue(legacyArtifact.files.single().statements.isEmpty()) + val hasPartialStatements = legacyArtifact.diagnostics.any { diagnostic -> + diagnostic.code == FastCheckDiagnosticCode.COVERAGE_STATEMENT_PARTIAL + } + assertTrue(hasPartialStatements) + Files.delete(admittedCount) budgetReads = 0