From b0a176347e6e932ea152c5a6fe9d99a0a7883363 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Wed, 2 Dec 2026 21:10:40 +0100 Subject: [PATCH] Compare sparse lifecycle returns by own indices in Node --- .../calls/CallsClassReturnedCallableReplay.kt | 124 +++++++++++++++--- .../CallsClassReturnedCallableReplayTest.kt | 100 ++++++++++++++ 2 files changed, 209 insertions(+), 15 deletions(-) diff --git a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplay.kt b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplay.kt index c1feed0887..816dd749ee 100644 --- a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplay.kt +++ b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplay.kt @@ -56,6 +56,7 @@ internal data class CallsClassGeneratedReplayEntry( private data class CallsReturnedCallableReplayInput( val heap: CallsConcreteHeap, val methodCalls: List, + val arrayReturn: CallsConcreteReturnedValue? = null, ) internal fun replayClassLifecycle(args: List) { @@ -157,7 +158,10 @@ internal fun replayReturnedCallable( require(scenario.sourceFile == case.sourceFile && scenario.className == case.className) { "Factory owner differs from the frozen target class" } - val replayInput = prepareReplayInput(candidate, scenario, generatedInputDouble) + val predictedReturn = candidate.predictedReturn + val prediction = predictedReturn?.asReplayPrediction() + val arrayReturn = predictedReturn.takeIf { prediction?.containsArrays == true } + val replayInput = prepareReplayInput(candidate, scenario, generatedInputDouble).copy(arrayReturn = arrayReturn) val replay = runReturnedCallableReplay( case = case, sourceRoot = sourceRoot, @@ -172,6 +176,7 @@ internal fun replayReturnedCallable( replay = replay, generatedInputDouble = generatedInputDouble, methodCallCount = replayInput.methodCalls.size, + prediction = prediction, ) } @@ -251,6 +256,7 @@ private fun runReturnedCallableReplay( "phase", "completion", "returnPayload", + "arrayReturnMatches", "diagnostic", "consumedInputMethodCalls", "inputTranscriptMatched", @@ -273,8 +279,8 @@ private fun observeReturnedCallableReplay( replay: CallsClassReplayObservation, generatedInputDouble: Boolean, methodCallCount: Int, + prediction: CallsReplayPrediction?, ): CallsReturnedCallableReplayResult { - val predictedValue = candidate.predictedReturn?.asReplayPrediction() val observation = replay.observation check(observation.representable && observation.completion == CallsCoverageCompletion.RETURNED) { observation.diagnostic ?: "Native lifecycle replay produced no phase evidence" @@ -283,6 +289,7 @@ private fun observeReturnedCallableReplay( val completion = CallsCoverageCompletion.valueOf(observation.requiredText("completion")) val returnPayload = observation.optionalText("returnPayload") val returnedValue = returnPayload?.let { CallsExperimentJson.json.decodeFromString(it) } + val arrayReturnMatches = observation.optionalText("arrayReturnMatches")?.toBooleanStrict() val consumedCalls = observation.requiredText("consumedInputMethodCalls").toInt() val transcriptMatched = observation.optionalText("inputTranscriptMatched")?.toBooleanStrict() val transcriptDiagnostic = observation.optionalText("inputTranscriptDiagnostic") @@ -295,10 +302,12 @@ private fun observeReturnedCallableReplay( val completionMatches = symbolicCompletion?.let { phase == CallsReturnedCallableReplayPhase.CALLABLE && it == completion } + val predictedValue = prediction?.takeUnless { it.hasSparseArray }?.value val comparesReturnValue = replayedAllResiduals && completionMatches == true && completion == CallsCoverageCompletion.RETURNED val returnValueMatches = when { !comparesReturnValue -> null + prediction?.containsArrays == true -> arrayReturnMatches returnedValue != null && predictedValue != null -> returnedValue == predictedValue else -> null } @@ -339,7 +348,7 @@ private fun verifyInputMethodCalls(heap: CallsConcreteHeap, calls: List error("Invalid native replay value $name") } -private fun CallsConcreteReturnedValue.asReplayPrediction(): JsConcreteValue? { +private data class CallsReplayPrediction( + val value: JsConcreteValue, + val hasSparseArray: Boolean, + val containsArrays: Boolean, +) + +/** Sparse arrays use their graph for comparison because the observation codec only represents dense arrays. */ +private fun CallsConcreteReturnedValue.asReplayPrediction(): CallsReplayPrediction? { val nodes = objects.associateBy { it.id } if (nodes.size != objects.size) return null val seen = mutableSetOf() + var hasSparseArray = false + var containsArrays = false fun resolve(slot: CallsConcreteHeapValue): JsConcreteValue? { val primitive = slot.primitive if (primitive != null) return primitive @@ -382,7 +400,15 @@ private fun CallsConcreteReturnedValue.asReplayPrediction(): JsConcreteValue? { val elements = node.elements if (elements != null) { - val values = elements.map { resolve(it) ?: return null } + containsArrays = true + val values = elements.map { element -> + if (element == null) { + hasSparseArray = true + JsConcreteValue.Undefined + } else { + resolve(element) ?: return null + } + } return JsConcreteValue.Array(values) } val fields = linkedMapOf() @@ -395,7 +421,9 @@ private fun CallsConcreteReturnedValue.asReplayPrediction(): JsConcreteValue? { } val result = resolve(value) ?: return null - return result.takeIf { seen.size == nodes.size } + if (seen.size != nodes.size) return null + + return CallsReplayPrediction(value = result, hasSparseArray = hasSparseArray, containsArrays = containsArrays) } private fun returnedCallableDriver( @@ -430,11 +458,13 @@ private fun returnedCallableDriver( return """ $imports + import { types as nodeTypes } from 'node:util'; import { decodeJsValue, encodeJsValue } from $valueCodec; import { stringifyProtocolJson } from $protocolJson; ${callsConcreteHeapRestoreSource()} ${callsInputMethodDoubleSource()} + ${arrayReturnComparisonSource()} function requireClass(module: any, name: string): any { const value = module[name]; @@ -460,7 +490,7 @@ private fun returnedCallableDriver( installCallsInputMethodDouble(input.methodCalls, restored); function observed(result: object) { const evidence = transcript?.(); - return { ...result, + return { arrayReturnMatches: undefined, ...result, consumedInputMethodCalls: String(evidence?.consumedInputMethodCalls ?? 0), inputTranscriptMatched: evidence === undefined ? undefined : String(evidence.inputTranscriptMatched), inputTranscriptDiagnostic: evidence?.inputTranscriptDiagnostic }; @@ -485,18 +515,82 @@ private fun returnedCallableDriver( return observed(threw('CALLABLE', error)); } - let returnPayload: string | undefined; - try { - returnPayload = stringifyProtocolJson(encodeJsValue(value)); - } catch { - // The observation protocol cannot encode every JavaScript value. - } - const diagnostic = returnPayload !== undefined ? undefined : 'Unrepresentable return value'; - return observed({ phase: 'CALLABLE', completion: 'RETURNED', returnPayload, diagnostic }); + ${recordReturnedValueSource()} } """.trimIndent() + "\n" } +private fun recordReturnedValueSource(): String = """ + let returnPayload: string | undefined; + let arrayReturnMatches: string | undefined; + if (input.arrayReturn != null) { + const graph = { arguments: [input.arrayReturn.value], objects: input.arrayReturn.objects }; + const expected = restoreCallsConcreteHeap(graph, prototypes, decodeJsValue).arguments[0]; + try { + arrayReturnMatches = String(compareArrayReturn(value, expected)); + } catch { + // Non-ordinary or aliased native data cannot be compared by value. + } + } + try { + returnPayload = stringifyProtocolJson(encodeJsValue(value)); + } catch { + // The regular payload has no representation for holes. + } + const representable = input.arrayReturn != null ? arrayReturnMatches !== undefined : returnPayload !== undefined; + const diagnostic = representable ? undefined : 'Unrepresentable return value'; + return observed({ phase: 'CALLABLE', completion: 'RETURNED', returnPayload, arrayReturnMatches, diagnostic }); +""".trimIndent() + +private fun arrayReturnComparisonSource(): String = """ + function compareArrayReturn(actual: unknown, expected: unknown): boolean { + const seen = new WeakSet(); + let matches = true; + + function visit(actual: unknown, expected: unknown) { + if (actual === null || typeof actual !== 'object') { + encodeJsValue(actual); + if (!Object.is(actual, expected)) matches = false; + return; + } + + if (nodeTypes.isProxy(actual) || seen.has(actual)) throw new Error('Unsupported returned object'); + const array = Array.isArray(actual); + const prototype = array ? Array.prototype : Object.prototype; + if (Object.getPrototypeOf(actual) !== prototype || Object.getOwnPropertySymbols(actual).length !== 0) { + throw new Error('Unsupported returned prototype or property symbol'); + } + seen.add(actual); + + const sameContainerKind = expected !== null && typeof expected === 'object' && Array.isArray(expected) === array; + const keys = Object.getOwnPropertyNames(actual); + if (!sameContainerKind || keys.length !== Object.getOwnPropertyNames(expected).length || + (array && actual.length !== (expected as any[]).length)) { + matches = false; + } + + for (const key of keys) { + if (array && key === 'length') continue; + + const index = Number(key); + const validKey = array ? Number.isInteger(index) && index >= 0 && index < actual.length && String(index) === key : + !['__proto__', 'constructor', 'prototype'].includes(key); + const descriptor = Object.getOwnPropertyDescriptor(actual, key); + if (!validKey || !descriptor?.enumerable || !('value' in descriptor)) { + throw new Error('Unsupported returned property'); + } + + const predicted = sameContainerKind ? Object.getOwnPropertyDescriptor(expected, key) : undefined; + if (predicted === undefined) matches = false; + visit(descriptor.value, predicted?.value); + } + } + + visit(actual, expected); + return matches; + } +""".trimIndent() + private fun replayLiteral(value: String): String = CallsExperimentJson.json.encodeToUtf8SafeString(value) private const val RETURNED_CALLABLE_REPLAY_FILE = ".usvm-returned-callable-replay.ts" diff --git a/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplayTest.kt b/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplayTest.kt index 0a895c5d74..46f495bb92 100644 --- a/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplayTest.kt +++ b/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplayTest.kt @@ -1,6 +1,8 @@ package org.usvm.ts.calls import org.junit.jupiter.api.io.TempDir +import org.usvm.api.TsParametersState +import org.usvm.api.TsTestValue import org.usvm.ts.pbt.model.JsConcreteValue import java.nio.file.Files import java.nio.file.Path @@ -69,6 +71,104 @@ class CallsClassReturnedCallableReplayTest { assertTrue(replay.nativeReplayValidated) } + @Test + fun `native caller preserves sparse indices own undefined and cyclic aliases`() { + val case = sourceCase( + """ + export class Target { + static make(values: any[]) { + return (alias: any[]): number => { + return values === alias && values.length === 5 && !Object.hasOwn(values, 0) && + Object.hasOwn(values, 1) && values[1] === undefined && + values[2] === null && values[3] === values && + !Object.hasOwn(values, 4) ? 17 : 99; + }; + } + } + """.trimIndent(), + ) + val slots = mutableListOf( + TsTestValue.TsUndefined, + TsTestValue.TsUndefined, + TsTestValue.TsNull, + TsTestValue.TsUndefined, + TsTestValue.TsUndefined, + ) + val array = TsTestValue.TsArray(values = slots, holeIndices = setOf(0, 4)) + slots[3] = array + val heap = concreteCallsInputHeap( + inputs = TsParametersState(thisInstance = null, parameters = listOf(array, array), globals = emptyMap()), + prototypes = emptyMap(), + ) + val serialized = encodeCallsArtifact(heap) + val restored = CallsExperimentJson.json.decodeFromString(serialized) + val candidate = candidate(restored, isStatic = true, predicted = number(17.0)) + + val replay = replayReturnedCallable(case, directory, candidate, timeoutMillis = 10_000) + + val elements = requireNotNull(restored.objects.single().elements) + assertEquals(5, elements.size) + assertNull(elements[0]) + assertEquals(JsConcreteValue.Undefined, elements[1]?.primitive) + assertEquals(JsConcreteValue.Null, elements[2]?.primitive) + assertEquals(restored.arguments[0], elements[3]) + assertNull(elements[4]) + assertEquals(JsConcreteValue.number(17.0), replay.returnedValue) + assertTrue(replay.nativeReplayValidated) + } + + @Test + fun `native sparse returns match own indices and length`() { + val case = sourceCase( + """ + export class Target { + static make(mode: number) { + return (base: number) => { + const values: (number | undefined)[] = [base, 7]; + if (mode === 0) delete values[1]; + if (mode === 2) values[1] = undefined; + return values; + }; + } + } + """.trimIndent(), + ) + val sparseValue = TsTestValue.TsArray( + values = listOf(TsTestValue.TsNumber.TsInteger(value = 2), TsTestValue.TsUndefined), + holeIndices = setOf(1), + ) + val denseValue = TsTestValue.TsArray( + values = listOf(TsTestValue.TsNumber.TsInteger(value = 2), TsTestValue.TsNumber.TsInteger(value = 7)), + ) + + fun replay(mode: Int, prediction: TsTestValue.TsArray<*>): CallsReturnedCallableReplayResult { + val heap = CallsConcreteHeap( + receiver = null, + arguments = listOf(number(mode.toDouble()), number(2.0)), + objects = emptyList(), + ) + val predicted = concreteCallsReturnedValue(value = prediction, prototypes = emptyMap()) + val candidate = candidate(heap, isStatic = true, predicted = predicted.value) + .copy(predictedReturn = predicted) + val encoded = encodeCallsArtifact(candidate) + val saved = CallsExperimentJson.json.decodeFromString(encoded) + + return replayReturnedCallable(case, directory, saved, timeoutMillis = 10_000) + } + + val sparse = replay(mode = 0, prediction = sparseValue) + val dense = replay(mode = 1, prediction = sparseValue) + val ownUndefined = replay(mode = 2, prediction = sparseValue) + val expectedDense = replay(mode = 0, prediction = denseValue) + + assertEquals(true, sparse.returnValueMatches) + assertTrue(sparse.nativeReplayValidated) + assertNull(sparse.diagnostic) + assertEquals(false, dense.returnValueMatches) + assertEquals(false, ownUndefined.returnValueMatches) + assertEquals(false, expectedDense.returnValueMatches) + } + @Test fun `native closure exception is retained as a callable mismatch`() { val case = sourceCase(