Skip to content
Draft
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
Expand Up @@ -56,6 +56,7 @@ internal data class CallsClassGeneratedReplayEntry(
private data class CallsReturnedCallableReplayInput(
val heap: CallsConcreteHeap,
val methodCalls: List<CallsConcreteInputMethodCall>,
val arrayReturn: CallsConcreteReturnedValue? = null,
)

internal fun replayClassLifecycle(args: List<String>) {
Expand Down Expand Up @@ -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,
Expand All @@ -172,6 +176,7 @@ internal fun replayReturnedCallable(
replay = replay,
generatedInputDouble = generatedInputDouble,
methodCallCount = replayInput.methodCalls.size,
prediction = prediction,
)
}

Expand Down Expand Up @@ -251,6 +256,7 @@ private fun runReturnedCallableReplay(
"phase",
"completion",
"returnPayload",
"arrayReturnMatches",
"diagnostic",
"consumedInputMethodCalls",
"inputTranscriptMatched",
Expand All @@ -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"
Expand All @@ -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<JsConcreteValue>(it) }
val arrayReturnMatches = observation.optionalText("arrayReturnMatches")?.toBooleanStrict()
val consumedCalls = observation.requiredText("consumedInputMethodCalls").toInt()
val transcriptMatched = observation.optionalText("inputTranscriptMatched")?.toBooleanStrict()
val transcriptDiagnostic = observation.optionalText("inputTranscriptDiagnostic")
Expand All @@ -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
}
Expand Down Expand Up @@ -339,7 +348,7 @@ private fun verifyInputMethodCalls(heap: CallsConcreteHeap, calls: List<CallsCon

val node = requireNotNull(nodes[id]) { "Missing input heap object $id" }
val values = node.elements ?: node.fields.orEmpty().values
values.mapNotNullTo(pending) { it.objectId }
values.mapNotNullTo(pending) { it?.objectId }
}
for (call in calls) {
val receiver = nodes[call.receiverObjectId]
Expand Down Expand Up @@ -367,11 +376,20 @@ private fun CallsClassObservation.optionalText(name: String): String? = when (va
else -> 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<Int>()
var hasSparseArray = false
var containsArrays = false
fun resolve(slot: CallsConcreteHeapValue): JsConcreteValue? {
val primitive = slot.primitive
if (primitive != null) return primitive
Expand All @@ -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<String, JsConcreteValue>()
Expand All @@ -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(
Expand Down Expand Up @@ -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];
Expand All @@ -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 };
Expand All @@ -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<object>();
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"
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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>(
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<CallsConcreteHeap>(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<CallsClassInputCandidate>(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(
Expand Down
Loading