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
133 changes: 133 additions & 0 deletions usvm-ts-calls/scripts/test_missing_input_method.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
'use strict';

const assert = require('node:assert/strict');
const { execFileSync } = require('node:child_process');
const fs = require('node:fs');
const path = require('node:path');
const { test } = require('node:test');
const { types } = require('node:util');
const vm = require('node:vm');

const sourcePath = path.join(__dirname, '../src/main/resources/org/usvm/ts/calls/missing-input-method.js');
const source = fs.readFileSync(sourcePath, 'utf8');
const { examineStructuralInput, observeMissingInputMethod } = vm.runInThisContext(
source + '\n({ examineStructuralInput, observeMissingInputMethod });',
);

function fixture() {
class Fixture {
invoke() {
assert.equal(this.service, this.alias);
assert.equal(0 in this.values, false);
assert.equal(1 in this.values, true);
return this.service.missing();
}
}
const owner = {};
const values = [, undefined];
const receiver = Object.assign(Object.create(Fixture.prototype), { service: owner, alias: owner, values });
const objects = new Map([[0, receiver], [1, owner], [2, values]]);
const graph = {
receiver: { objectId: 0 },
objects: [
{
id: 0, className: 'Fixture', classSignature: 'Fixture', classSourceFile: 'fixture.ts',
fields: { service: { objectId: 1 }, alias: { objectId: 1 }, values: { objectId: 2 } },
},
{ id: 1, fields: {} },
{ id: 2, elements: [null, { primitive: { kind: 'undefined' } }] },
],
};
return { candidate: { invocationKind: 'INSTANCE_METHOD', inputs: graph }, owner, restored: { receiver, objects } };
}

test('one own method on the same object, with independent original and alternative runs', async () => {
const original = fixture();
const alternative = fixture();
const originalGraph = structuredClone(original.candidate.inputs);
const encode = value => ({ kind: typeof value });
original.candidate.structural = { fields: ['service', 'missing'], install: false };
alternative.candidate.structural = { fields: ['service', 'missing'], install: true };

const before = await observeMissingInputMethod(
original.candidate, original.restored, () => original.restored.receiver.invoke(), encode, types.isPromise,
);
const after = await observeMissingInputMethod(
alternative.candidate, alternative.restored, () => alternative.restored.receiver.invoke(), encode, types.isPromise,
);
const trace = JSON.parse(after.missingMethod);

assert.equal(before.completion, 'THREW');
assert.equal(JSON.parse(before.missingMethod).typeError, true);
assert.equal(after.completion, 'RETURNED');
assert.equal(after.returnValue, '{"kind":"undefined"}');
assert.deepEqual(trace.atCompletion, {
status: 'ELIGIBLE', installed: true, calls: 1, ownerCalls: 1, ownerId: 1, method: 'missing',
});
assert.deepEqual(trace.unhandledRejections, []);
assert.deepEqual(Object.keys(alternative.owner), ['missing']);
assert.deepEqual(Object.keys(original.owner), []);
assert.equal(Object.getPrototypeOf(alternative.owner), Object.prototype);
assert.deepEqual(alternative.candidate.inputs, originalGraph);
});

test('guard refuses existing methods, prototype roots, accessors and primitive owners', () => {
const cases = [
['own non-callable', f => { f.owner.missing = undefined; }, 'METHOD_ALREADY_PRESENT'],
['own accessor', f => {
Object.defineProperty(f.owner, 'missing', { get() { throw Error('must not run'); } });
}, 'METHOD_ALREADY_PRESENT'],
['inherited name', f => { f.candidate.structural.fields[1] = 'toString'; }, 'METHOD_ALREADY_PRESENT'],
['missing link', f => { f.candidate.structural.fields[0] = 'unrecorded'; }, 'PATH_NOT_OWN_GRAPH_REFERENCE'],
['intermediate accessor', f => {
Object.defineProperty(f.restored.receiver, 'service', { get() { throw Error('must not run'); } });
}, 'PATH_NOT_OWN_GRAPH_REFERENCE'],
['array owner', f => { f.candidate.structural.fields[0] = 'values'; }, 'OWNER_NOT_ORDINARY_PLAIN_OBJECT'],
['custom prototype', f => { Object.setPrototypeOf(f.owner, {}); }, 'OWNER_NOT_ORDINARY_PLAIN_OBJECT'],
['class-tagged owner', f => { f.candidate.inputs.objects[1].className = 'Custom'; }, 'OWNER_NOT_ORDINARY_PLAIN_OBJECT'],
['unqualified path token', f => { f.candidate.structural.fields[1] = 'a.b'; }, 'UNSUPPORTED_METHOD_PATH'],
['non-extensible owner', f => { Object.freeze(f.owner); }, 'OWNER_NOT_EXTENSIBLE'],
['primitive link', f => {
f.candidate.inputs.objects[0].fields.service = { primitive: { kind: 'boolean', value: false } };
f.restored.receiver.service = false;
}, 'PATH_NOT_OWN_GRAPH_REFERENCE'],
];
for (const [name, prepare, status] of cases) {
const f = fixture();
f.candidate.structural = { fields: ['service', 'missing'], install: true };
prepare(f);

const result = examineStructuralInput(f.candidate, f.restored);

assert.equal(result.status, status, name);
assert.equal(result.installed, false, name);
}
});

test('separates a return from a later unhandled rejection in the native process', () => {
const script = source + `
const candidate = {
invocationKind: 'INSTANCE_METHOD',
structural: { fields: ['missing'], install: true },
inputs: { receiver: { objectId: 0 }, objects: [{ id: 0, fields: {} }] },
};
const receiver = {};
const restored = { receiver, objects: new Map([[0, receiver]]) };
observeMissingInputMethod(candidate, restored, () => {
receiver.missing();
Promise.reject(new Error('later'));
return 7;
}, value => value, require('node:util').types.isPromise).then(result => {
process.stdout.write(JSON.stringify(result));
});
`;

const result = JSON.parse(execFileSync(process.execPath, ['--unhandled-rejections=throw', '-e', script], {
encoding: 'utf8', timeout: 10000,
}));
const trace = JSON.parse(result.missingMethod);

assert.equal(result.completion, 'RETURNED');
assert.equal(trace.atCompletion.ownerCalls, 1);
assert.deepEqual(trace.unhandledRejections, [{ errorType: 'Error', message: 'later', handledWithinWindow: false }]);
});
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import org.usvm.ts.pbt.fastcheck.TypeScriptLocalSourceClosure
import org.usvm.ts.pbt.model.ArrayDomain
import org.usvm.ts.pbt.model.BooleanDomain
import org.usvm.ts.pbt.model.ConstantDomain
import org.usvm.ts.pbt.model.ExecutionKind
import org.usvm.ts.pbt.model.IntegerDomain
import org.usvm.ts.pbt.model.JsConcreteValue
import org.usvm.ts.pbt.model.NumberDomain
Expand Down Expand Up @@ -273,6 +274,7 @@ internal class OriginalTypeScriptClassReplayer(
// Saved environments may replay naturally evaluated initializers outside the lifecycle oracle's checked subset.
// The supplied graph still passes the normal copy/hash checks and cannot contain unresolved module boundaries.
sourceClosure: TypeScriptLocalSourceClosure? = null,
private val awaitPreparedObservation: Boolean = false,
) : AutoCloseable {
private val root = sourceRoot.toRealPath()
private val workspace = Files.createTempDirectory("usvm-calls-class-replay-")
Expand Down Expand Up @@ -314,6 +316,7 @@ internal class OriginalTypeScriptClassReplayer(
dropSentinel = function.inputs.isEmpty(),
counterGlobalName = counterGlobalName,
fields = observationFields.keys,
awaitPreparedObservation = awaitPreparedObservation,
)
)
FastCheckBackend(sourceRoots = listOf(overlay), tsconfig = tsconfig)
Expand Down Expand Up @@ -365,7 +368,11 @@ internal class OriginalTypeScriptClassReplayer(
property = PropertyDefinition(
id = PropertyId("calls.class.exact-replay"),
inputs = propertyInputs,
predicate = TypeScriptEntryPoint(module = wrapperName, exportName = "replayClassScenario"),
predicate = TypeScriptEntryPoint(
module = wrapperName,
exportName = "replayClassScenario",
executionKind = if (awaitPreparedObservation) ExecutionKind.ASYNC else ExecutionKind.SYNC,
),
),
configuration = PropertyRunConfiguration(
seed = nativeSeed,
Expand Down Expand Up @@ -402,6 +409,7 @@ private fun classReplayWrapper(
dropSentinel: Boolean,
counterGlobalName: String?,
fields: Set<String>,
awaitPreparedObservation: Boolean,
): String {
val json = CallsExperimentJson.json
val protocolModule = json.encodeToUtf8SafeString(FastCheckRuntime.protocolJsonModule().toUri().toString())
Expand All @@ -410,6 +418,11 @@ private fun classReplayWrapper(
val outputPath = json.encodeToUtf8SafeString(observationPath.toString())
val expectedFields = json.encodeToUtf8SafeString(fields.sorted())
val actualArgs = if (dropSentinel) "args.slice(1)" else "args"
val async = if (awaitPreparedObservation) "async " else ""
val await = if (awaitPreparedObservation) "await " else ""
val returnType = if (awaitPreparedObservation) "Promise<boolean>" else "boolean"
val promiseCheckImport = if (awaitPreparedObservation) "import { types as nodeTypes } from 'node:util';" else ""
val promiseCheckArgument = if (awaitPreparedObservation) ", nodeTypes.isPromise" else ""
val counterSetup = counterGlobalName?.let { name ->
"(globalThis as any)[${json.encodeToUtf8SafeString(
name
Expand All @@ -422,20 +435,21 @@ private fun classReplayWrapper(
import { writeFileSync } from 'node:fs';
import { stringifyProtocolJson } from $protocolModule;
import * as scenarioModule from $sourceModule;
$promiseCheckImport

${classReplayValueEncoderSource().prependIndent(indent = " ")}

${classReplayThrownValueDiagnosticSource().prependIndent(indent = " ")}

export function replayClassScenario(...args: unknown[]): boolean {
export ${async}function replayClassScenario(...args: unknown[]): $returnType {
const actualArgs = $actualArgs;
const inputs = actualArgs.map(value => encode(value));
$counterSetup
let observation: any;
let returned: any;
let completion = 'RETURNED';
try {
returned = (scenarioModule as any)[$exportKey](...actualArgs);
returned = $await(scenarioModule as any)[$exportKey](...actualArgs$promiseCheckArgument);
} catch (error) {
completion = 'THREW';
const isShapeFailure = error instanceof Error && error.message.startsWith('USVM class observation shape:');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ fun main(args: Array<String>) {
"class-start-smoke" -> runClassStartSmoke(args.drop(1))
"class-symbolic-probe" -> runClassSymbolicProbe(args.drop(1))
"class-replay-input" -> runSavedInputReplay(args.drop(1))
"class-experiment-missing-input-method" -> runSavedInputReplay(args.drop(1), experiment = true)
"class-prepare" -> runClassPrepare(args.drop(1))
"class-preflight" -> runClassPreflight(args.drop(1))
"class-cell" -> runClassCell(args.drop(1))
Expand Down Expand Up @@ -110,6 +111,7 @@ private fun usage(): String = """
calls class-start-smoke <startup-manifest.json> <class-id> <output-directory>
calls class-symbolic-probe <startup-manifest.json> <class-id> <output-directory>
calls class-replay-input <startup-manifest.json> <class-id> <probe-directory> <state-id> <timeout-ms> <output.json>
calls class-experiment-missing-input-method <startup-manifest.json> <class-id> <probe-directory> <state-id> <timeout-ms> <observation.json> <output.json>
calls class-prepare <class-manifest.json> <prepared-directory>
calls class-preflight <prepared-directory> <class-id> <preflight-ms>
calls class-cell <prepared-directory> <class-id> <profile> <seed> <budget-ms> <output-directory>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package org.usvm.ts.calls

import kotlinx.serialization.Serializable
import org.usvm.ts.pbt.model.JsConcreteValue

private val methodPathToken = Regex("[A-Za-z_$][A-Za-z0-9_$]*")

@Serializable
internal data class CallsMissingInputMethodObservation(
val fields: List<String>,
val errorMessage: String,
) {
init {
val validNames = fields.isNotEmpty() && fields.all { it.matches(methodPathToken) }
require(validNames) { "The observation must name a literal property chain relative to this" }
require(errorMessage == "this.${fields.joinToString(".")} is not a function") {
"The observed TypeError message must name the same missing method"
}
}
}

@Serializable
internal data class CallsMissingInputMethodExecution(val fields: List<String>, val install: Boolean)

@Serializable
internal data class CallsMissingInputMethodDecision(
val status: String,
val installed: Boolean,
val calls: Int,
val ownerCalls: Int,
val ownerId: Int? = null,
val method: String? = null,
)

@Serializable
internal data class CallsMissingInputMethodRejection(
val errorType: String,
val message: String,
val handledWithinWindow: Boolean,
)

@Serializable
internal data class CallsMissingInputMethodTrace(
val atCompletion: CallsMissingInputMethodDecision,
val afterDrain: CallsMissingInputMethodDecision,
val typeError: Boolean,
val returnedPromise: Boolean,
val unhandledRejections: List<CallsMissingInputMethodRejection>,
)

@Serializable
internal data class CallsMissingInputMethodRun(
val replay: CallsSavedInputReplayResult,
val trace: CallsMissingInputMethodTrace?,
) {
fun text(name: String): String? {
val value = replay.observation?.observation?.values?.get(name)
return (value as? JsConcreteValue.String)?.value
}
}

@Serializable
internal enum class CallsMissingInputMethodVerdict {
ORIGINAL_UNAVAILABLE,
NO_MATCHING_ORIGINAL_ERROR,
OWNER_INELIGIBLE,
ALTERNATIVE_UNAVAILABLE,
ADDED_METHOD_NOT_INVOKED_WITH_OWNER,
ALTERNATIVE_THREW,
RETURNED_PROMISE,
RETURNED_WITH_UNHANDLED_REJECTION,
RETURNED,
}

/** Each run restores its own copy of the recorded heap in a fresh native process. */
@Serializable
internal data class CallsMissingInputMethodResult(
val original: CallsMissingInputMethodRun,
val alternative: CallsMissingInputMethodRun?,
val verdict: CallsMissingInputMethodVerdict,
)

internal fun replayMissingInputMethod(
observation: CallsMissingInputMethodObservation,
replay: (CallsMissingInputMethodExecution) -> CallsSavedInputReplayResult,
): CallsMissingInputMethodResult {
val original = replay(CallsMissingInputMethodExecution(observation.fields, install = false)).missingMethodRun()
val originalTrace = original.trace
if (originalTrace == null) {
return CallsMissingInputMethodResult(
original = original,
alternative = null,
verdict = CallsMissingInputMethodVerdict.ORIGINAL_UNAVAILABLE,
)
}

val matchesOriginal = original.text("completion") == "THREW" && originalTrace.typeError &&
original.text("diagnostic") == "TypeError: ${observation.errorMessage}"
if (!matchesOriginal) {
return CallsMissingInputMethodResult(
original = original,
alternative = null,
verdict = CallsMissingInputMethodVerdict.NO_MATCHING_ORIGINAL_ERROR,
)
}
if (originalTrace.atCompletion.status != "ELIGIBLE") {
return CallsMissingInputMethodResult(
original = original,
alternative = null,
verdict = CallsMissingInputMethodVerdict.OWNER_INELIGIBLE,
)
}

val alternative = replay(CallsMissingInputMethodExecution(observation.fields, install = true)).missingMethodRun()
val trace = alternative.trace
val completion = alternative.text("completion")
val verdict = when {
trace == null || !trace.atCompletion.installed -> CallsMissingInputMethodVerdict.ALTERNATIVE_UNAVAILABLE
trace.atCompletion.ownerCalls == 0 -> CallsMissingInputMethodVerdict.ADDED_METHOD_NOT_INVOKED_WITH_OWNER
completion == "THREW" -> CallsMissingInputMethodVerdict.ALTERNATIVE_THREW
completion != "RETURNED" -> CallsMissingInputMethodVerdict.ALTERNATIVE_UNAVAILABLE
trace.returnedPromise -> CallsMissingInputMethodVerdict.RETURNED_PROMISE
trace.unhandledRejections.isNotEmpty() -> CallsMissingInputMethodVerdict.RETURNED_WITH_UNHANDLED_REJECTION
else -> CallsMissingInputMethodVerdict.RETURNED
}
return CallsMissingInputMethodResult(original, alternative, verdict)
}

private fun CallsSavedInputReplayResult.missingMethodRun(): CallsMissingInputMethodRun {
val observation = observation ?: return CallsMissingInputMethodRun(this, trace = null)
val values = observation.observation.values
val encoded = values["missingMethod"] as? JsConcreteValue.String
?: return CallsMissingInputMethodRun(this, trace = null)

val trace = CallsExperimentJson.json.decodeFromString<CallsMissingInputMethodTrace>(encoded.value)
val report = observation.copy(observation = observation.observation.copy(values = values - "missingMethod"))
return CallsMissingInputMethodRun(copy(observation = report), trace)
}

internal fun missingInputMethodSource(): String =
checkNotNull(CallsMissingInputMethodObservation::class.java.getResourceAsStream("missing-input-method.js"))
.bufferedReader().use { it.readText() }
Loading
Loading