feat(vm): add VM-owned PCG64 random and coverage headroom
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good

Implement GC-managed random generators, next/nextf intrinsics, bounded ranges and deterministic conformance coverage. Publish the runtime contract and producer guidance.

Give coverage domains at least five percentage points of measured headroom while preserving sufficient floors. Record local qualification: make ci-domains passes with 939 tests and all domain gates green.
This commit is contained in:
2026-10-09 12:51:05 +01:00
parent 9318cf7cd3
commit 3e39a90083
50 changed files with 2545 additions and 189 deletions
@@ -65,3 +65,6 @@ pub struct TrapInfo {
/// Machine-readable quota context; messages are not its serialization.
pub resource: Option<crate::ResourceFailure>,
}
/// All 64 unbiased bounded-random candidates were rejected.
pub const TRAP_RANDOM_REJECTION_LIMIT: u32 = 0x0000_0015;
+2 -2
View File
@@ -14,8 +14,8 @@ pub use abi::{
SourceSpan, TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT,
TRAP_ILLEGAL_INSTRUCTION, TRAP_INVALID_FUNC, TRAP_INVALID_HANDLE, TRAP_INVALID_INTRINSIC,
TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_NON_FINITE, TRAP_NULL_REFERENCE,
TRAP_NUMERIC_DOMAIN, TRAP_NUMERIC_RANGE, TRAP_OOB, TRAP_RESOURCE_LIMIT, TRAP_STACK_UNDERFLOW,
TRAP_TYPE, TRAP_UNAVAILABLE,
TRAP_NUMERIC_DOMAIN, TRAP_NUMERIC_RANGE, TRAP_OOB, TRAP_RANDOM_REJECTION_LIMIT,
TRAP_RESOURCE_LIMIT, TRAP_STACK_UNDERFLOW, TRAP_TYPE, TRAP_UNAVAILABLE,
};
pub use assembler::{assemble, AsmError};
pub use decoder::{decode_next, DecodeError, DecodedInstr};
@@ -158,6 +158,7 @@ impl BuiltinId {
pub const BOOL: Self = Self(0x13);
pub const STRING: Self = Self(0x14);
pub const DYNAMIC: Self = Self(0x15);
pub const RANDOM: Self = Self(0x16);
pub fn layout(self) -> Result<StorageLayout, E> {
use DefaultKind as D;
use Ownership as O;
@@ -169,6 +170,7 @@ impl BuiltinId {
Self::INT64 => (8, 8, 1, O::Plain, D::Int64),
Self::FLOAT => (8, 8, 1, O::Plain, D::Float),
Self::BOOL => (1, 1, 1, O::Plain, D::Bool),
Self::RANDOM => (8, 8, 1, O::GuestReference, D::Null),
Self::STRING => {
(size_of::<StringSlot>(), align_of::<StringSlot>(), 1, O::NativeString, D::Null)
}
@@ -17,11 +17,23 @@ fn main() {
let m = lookup_intrinsic_by_id(id).unwrap();
let mut ctx = HostContext::new(None);
for _ in 0..100 {
black_box((m.implementation)(black_box(&args), &mut ctx).unwrap());
black_box(
(m.implementation.host_callback().expect("host intrinsic"))(
black_box(&args),
&mut ctx,
)
.unwrap(),
);
}
let start = Instant::now();
for _ in 0..iterations {
black_box((m.implementation)(black_box(&args), &mut ctx).unwrap());
black_box(
(m.implementation.host_callback().expect("host intrinsic"))(
black_box(&args),
&mut ctx,
)
.unwrap(),
);
}
let elapsed = start.elapsed().as_nanos();
println!(
@@ -47,7 +47,10 @@ fn main() {
if !matches!(op, "ADD" | "SUB" | "MUL" | "DIV") {
let id = u32::from_str_radix(op, 16).unwrap();
let m = lookup_intrinsic_by_id(id).unwrap();
match (m.implementation)(&args, &mut HostContext::new(None)) {
match (m.implementation.host_callback().expect("host intrinsic"))(
&args,
&mut HostContext::new(None),
) {
Ok(v) => println!("{} {}", text(&v[0]), m.cost_cycles),
Err(prometeu_vm::IntrinsicExecutionError::Numeric(e)) => {
println!("trap:{:x} {}", e.code, m.cost_cycles)
+187 -34
View File
@@ -83,6 +83,7 @@ pub enum BuiltinTypeShape {
Scalar,
Aggregate,
Dynamic,
Reference,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -137,13 +138,23 @@ impl BuiltinTypeMeta {
// This context-free catalogue must never claim to validate it.
return Err(BuiltinValueError::RegistryRequired);
}
if self.shape == BuiltinTypeShape::Reference {
if values.len() != 1 {
return Err(BuiltinValueError::ArityMismatch { expected: 1, got: values.len() });
}
return if matches!(values, [Value::Null]) {
Ok(())
} else {
Err(BuiltinValueError::RegistryRequired)
};
}
let layout = self.flatten_layout();
validate_values_against_layout(values, &layout)
}
fn flatten_into(&self, out: &mut Vec<AbiType>) {
match self.shape {
BuiltinTypeShape::Scalar | BuiltinTypeShape::Dynamic => {
BuiltinTypeShape::Scalar | BuiltinTypeShape::Dynamic | BuiltinTypeShape::Reference => {
out.extend_from_slice(self.flat_slot_layout)
}
BuiltinTypeShape::Aggregate => {
@@ -216,9 +227,38 @@ pub enum BuiltinValueError {
TypeMismatch { index: usize, expected: AbiType },
}
pub type IntrinsicImplementation =
pub type IntrinsicHostImplementation =
fn(&[Value], &mut HostContext<'_>) -> Result<Vec<Value>, IntrinsicExecutionError>;
/// VM-owned operations cannot be invoked through a HostContext callback.
#[derive(Debug, Clone, Copy)]
pub enum IntrinsicImplementation {
Host(IntrinsicHostImplementation),
VmOwned,
}
impl IntrinsicImplementation {
pub fn host_callback(self) -> Option<IntrinsicHostImplementation> {
match self {
Self::Host(f) => Some(f),
Self::VmOwned => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntrinsicCostModel {
Fixed,
RandomRejectionV1,
}
impl IntrinsicCostModel {
pub const fn name(self) -> &'static str {
match self {
Self::Fixed => "fixed",
Self::RandomRejectionV1 => "random_rejection_v1",
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct IntrinsicMeta {
pub id: u32,
@@ -228,8 +268,12 @@ pub struct IntrinsicMeta {
pub arg_layout: &'static [AbiType],
pub ret_layout: &'static [AbiType],
pub parameter_names: &'static [&'static str],
/// Total virtual call cost; math attempts are charged before checks.
/// Full fixed cost, or base cost for a variable model.
pub cost_cycles: u64,
pub cost_model: IntrinsicCostModel,
pub attempt_cost_cycles: u64,
pub max_attempts: u32,
pub mutates_guest_state: bool,
pub deterministic: bool,
pub may_allocate: bool,
pub implementation: IntrinsicImplementation,
@@ -343,7 +387,7 @@ const PIXEL_FIELDS: [BuiltinFieldMeta; 3] = [
},
];
const BUILTIN_TYPES: [BuiltinTypeMeta; 9] = [
const BUILTIN_TYPES: [BuiltinTypeMeta; 10] = [
BuiltinTypeMeta {
id: 0x0001,
name: COLOR.name,
@@ -371,6 +415,15 @@ const BUILTIN_TYPES: [BuiltinTypeMeta; 9] = [
flat_slot_layout: &PIXEL_LAYOUT,
flat_slot_width: 3,
},
BuiltinTypeMeta {
id: 0x16,
name: "Random",
version: 1,
shape: BuiltinTypeShape::Reference,
fields: &[],
flat_slot_layout: &[AbiType::Builtin(BuiltinTypeKey::new("Random", 1))],
flat_slot_width: 1,
},
scalar_meta(0x10, "Int32", &[AbiType::Scalar(BuiltinScalarType::Int32)]),
scalar_meta(0x11, "Int64", &[AbiType::Scalar(BuiltinScalarType::Int64)]),
scalar_meta(0x12, "Float", &[AbiType::Scalar(BuiltinScalarType::Float)]),
@@ -513,9 +566,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &SINGLE_FLOAT_RET,
parameter_names: &["ax", "ay", "bx", "by"],
cost_cycles: 10,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: vec2_dot,
implementation: crate::IntrinsicImplementation::Host(vec2_dot),
},
IntrinsicMeta {
id: 0x1001,
@@ -526,9 +583,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &SINGLE_FLOAT_RET,
parameter_names: &["x", "y"],
cost_cycles: 40,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: vec2_length,
implementation: crate::IntrinsicImplementation::Host(vec2_length),
},
IntrinsicMeta {
id: 0x1100,
@@ -539,9 +600,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &["raw"],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_from_raw,
implementation: crate::IntrinsicImplementation::Host(color_from_raw),
},
IntrinsicMeta {
id: 0x1101,
@@ -552,9 +617,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &["r", "g", "b"],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_rgb,
implementation: crate::IntrinsicImplementation::Host(color_rgb),
},
IntrinsicMeta {
id: 0x1102,
@@ -565,9 +634,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &["r", "g", "b", "a"],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_rgba,
implementation: crate::IntrinsicImplementation::Host(color_rgba),
},
IntrinsicMeta {
id: 0x1103,
@@ -578,9 +651,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &["value"],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_html_rgba,
implementation: crate::IntrinsicImplementation::Host(color_html_rgba),
},
IntrinsicMeta {
id: 0x1104,
@@ -591,9 +668,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &["value"],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_gray_scale,
implementation: crate::IntrinsicImplementation::Host(color_gray_scale),
},
IntrinsicMeta {
id: 0x1105,
@@ -604,9 +685,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &INT_RET,
parameter_names: &["color"],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_hex,
implementation: crate::IntrinsicImplementation::Host(color_hex),
},
IntrinsicMeta {
id: 0x1106,
@@ -617,9 +702,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &INT_RET,
parameter_names: &["color"],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_alpha,
implementation: crate::IntrinsicImplementation::Host(color_alpha),
},
IntrinsicMeta {
id: 0x1120,
@@ -630,9 +719,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_black,
implementation: crate::IntrinsicImplementation::Host(color_black),
},
IntrinsicMeta {
id: 0x1121,
@@ -643,9 +736,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_white,
implementation: crate::IntrinsicImplementation::Host(color_white),
},
IntrinsicMeta {
id: 0x1122,
@@ -656,9 +753,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_red,
implementation: crate::IntrinsicImplementation::Host(color_red),
},
IntrinsicMeta {
id: 0x1123,
@@ -669,9 +770,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_green,
implementation: crate::IntrinsicImplementation::Host(color_green),
},
IntrinsicMeta {
id: 0x1124,
@@ -682,9 +787,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_blue,
implementation: crate::IntrinsicImplementation::Host(color_blue),
},
IntrinsicMeta {
id: 0x1125,
@@ -695,9 +804,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_yellow,
implementation: crate::IntrinsicImplementation::Host(color_yellow),
},
IntrinsicMeta {
id: 0x1126,
@@ -708,9 +821,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_orange,
implementation: crate::IntrinsicImplementation::Host(color_orange),
},
IntrinsicMeta {
id: 0x1127,
@@ -721,9 +838,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_indigo,
implementation: crate::IntrinsicImplementation::Host(color_indigo),
},
IntrinsicMeta {
id: 0x1128,
@@ -734,9 +855,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_gray,
implementation: crate::IntrinsicImplementation::Host(color_gray),
},
IntrinsicMeta {
id: 0x1129,
@@ -747,9 +872,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_cyan,
implementation: crate::IntrinsicImplementation::Host(color_cyan),
},
IntrinsicMeta {
id: 0x112A,
@@ -760,9 +889,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_magenta,
implementation: crate::IntrinsicImplementation::Host(color_magenta),
},
IntrinsicMeta {
id: 0x112B,
@@ -773,9 +906,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: color_transparent,
implementation: crate::IntrinsicImplementation::Host(color_transparent),
},
];
@@ -806,6 +943,7 @@ pub fn lookup_intrinsic(owner: &str, name: &str, version: u16) -> Option<&'stati
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
.find(|meta| meta.owner == owner && meta.name == name && meta.version == version)
}
@@ -814,6 +952,7 @@ pub fn lookup_intrinsic_by_id(id: u32) -> Option<&'static IntrinsicMeta> {
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
.find(|meta| meta.id == id)
}
@@ -877,6 +1016,9 @@ fn value_matches_abi_type(value: &Value, expected: AbiType) -> bool {
AbiType::Scalar(BuiltinScalarType::String) => {
matches!(value, Value::String(_) | Value::Null)
}
AbiType::Builtin(key) if key.name == "Random" && key.version == 1 => {
matches!(value, Value::HeapRef(_) | Value::Null)
}
AbiType::Builtin(key) if key == COLOR => {
matches!(value, Value::Int64(raw) if u32::try_from(*raw).is_ok())
}
@@ -1111,6 +1253,7 @@ pub(crate) fn metered_lookup_intrinsic(
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
{
budget.work(1)?;
if meta.id == id {
@@ -1226,7 +1369,7 @@ mod tests {
fn intrinsic_implementations_are_registered_without_syscalls() {
let dot = lookup_intrinsic("vec2", "dot", 1).expect("vec2.dot must exist");
let mut ctx = HostContext::new(None);
let result = (dot.implementation)(
let result = (dot.implementation.host_callback().expect("host intrinsic"))(
&[Value::Float(1.0), Value::Float(2.0), Value::Float(3.0), Value::Float(4.0)],
&mut ctx,
)
@@ -1234,8 +1377,11 @@ mod tests {
assert_eq!(result, vec![Value::Float(11.0)]);
let length = lookup_intrinsic("vec2", "length", 1).expect("vec2.length must exist");
let result = (length.implementation)(&[Value::Float(3.0), Value::Float(4.0)], &mut ctx)
.expect("length implementation must execute");
let result = (length.implementation.host_callback().expect("host intrinsic"))(
&[Value::Float(3.0), Value::Float(4.0)],
&mut ctx,
)
.expect("length implementation must execute");
assert_eq!(result, vec![Value::Float(5.0)]);
}
@@ -1244,7 +1390,7 @@ mod tests {
let mut ctx = HostContext::new(None);
let rgba = lookup_intrinsic("color", "rgba", 1).expect("color.rgba must exist");
let result = (rgba.implementation)(
let result = (rgba.implementation.host_callback().expect("host intrinsic"))(
&[Value::Int64(0x11), Value::Int64(0x22), Value::Int64(0x33), Value::Int64(0x44)],
&mut ctx,
)
@@ -1252,13 +1398,19 @@ mod tests {
assert_eq!(result, vec![Value::Int64(0x11223344)]);
let html = lookup_intrinsic("color", "html_rgba", 1).expect("color.html_rgba must exist");
let result = (html.implementation)(&[Value::String("#AABBCCDD".into())], &mut ctx)
.expect("html_rgba implementation must execute");
let result = (html.implementation.host_callback().expect("host intrinsic"))(
&[Value::String("#AABBCCDD".into())],
&mut ctx,
)
.expect("html_rgba implementation must execute");
assert_eq!(result, vec![Value::Int64(0xAABBCCDD)]);
let alpha = lookup_intrinsic("color", "alpha", 1).expect("color.alpha must exist");
let result = (alpha.implementation)(&[Value::Int64(0xAABBCCDD)], &mut ctx)
.expect("alpha implementation must execute");
let result = (alpha.implementation.host_callback().expect("host intrinsic"))(
&[Value::Int64(0xAABBCCDD)],
&mut ctx,
)
.expect("alpha implementation must execute");
assert_eq!(result, vec![Value::Int64(0xDD)]);
}
@@ -1266,7 +1418,7 @@ mod tests {
fn input_intrinsic_requires_hardware_context() {
let mut ctx = HostContext::new(None);
let touch_x = lookup_intrinsic("input.touch", "x", 1).expect("input.touch.x must exist");
let err = (touch_x.implementation)(&[], &mut ctx)
let err = (touch_x.implementation.host_callback().expect("host intrinsic"))(&[], &mut ctx)
.expect_err("touch.x must fail without hardware context");
assert_eq!(err, IntrinsicExecutionError::HardwareUnavailable);
}
@@ -1287,6 +1439,7 @@ pub fn intrinsic_catalog() -> impl Iterator<Item = &'static IntrinsicMeta> {
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
}
pub fn builtin_constant_catalog() -> impl Iterator<Item = &'static BuiltinConstMeta> {
BUILTIN_CONSTS.iter()
+7 -3
View File
@@ -16,14 +16,14 @@ fn atom(t: AbiType) -> String {
}
pub fn intrinsic_catalog_csv() -> String {
let mut out = String::from(
"final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate,parameter_names,cost_cycles\n",
"final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate,parameter_names,cost_cycles,mutates_guest_state,cost_model,attempt_cost_cycles,max_attempts\n",
);
let mut entries: Vec<_> = intrinsic_catalog().collect();
entries.sort_by_key(|m| m.id);
for m in entries {
writeln!(
&mut out,
"0x{:04X},{},{}.{},{},{},{},{},{},{},{},{},{},{},{}",
"0x{:04X},{},{}.{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}",
m.id,
m.id,
m.owner,
@@ -38,7 +38,11 @@ pub fn intrinsic_catalog_csv() -> String {
m.deterministic,
m.may_allocate,
m.parameter_names.join("|"),
m.cost_cycles
m.cost_cycles,
m.mutates_guest_state,
m.cost_model.name(),
m.attempt_cost_cycles,
m.max_attempts
)
.unwrap();
}
+1
View File
@@ -1,4 +1,5 @@
mod dynamic_box;
mod random;
use crate::object::{ObjectHeader, ObjectKind};
use crate::resource_budget::{
BudgetVec, Reservation, ResourceFailure, ResourceReason, RuntimeBudget, RuntimeResource as Q,
@@ -0,0 +1,48 @@
//! Quota-accounted opaque leaf payload and infallible state publication.
use super::*;
use crate::random::{INCREMENT, Pcg64};
impl Heap {
pub(crate) fn allocate_random(&mut self, seed: i64) -> Result<HeapRef, ResourceFailure> {
let prepared = self.prepare_insertion()?;
let mut payload = BudgetVec::new(&self.budget, Q::GuestBytes);
payload.reserve(32)?;
let state = Pcg64::new(seed);
payload.extend_from_slice(&state.state.to_le_bytes()).expect("reserved random state");
payload.extend_from_slice(&state.inc.to_le_bytes()).expect("reserved random increment");
Ok(self.commit_insertion(
prepared,
StoredObject {
header: ObjectHeader::new(ObjectKind::Random, 32),
payload,
array_elems: None,
closure_env: None,
typed: None,
dynamic_box: None,
},
))
}
pub(crate) fn random_state(&self, r: HeapRef) -> Result<Pcg64, ValueError> {
if !self.is_valid(r) {
return Err(ValueError::InvalidHandle);
}
let obj = self.objects[r.index as usize].as_ref().unwrap();
if obj.header.kind != ObjectKind::Random || obj.payload.len() != 32 {
return Err(ValueError::Type);
}
let state = u128::from_le_bytes(obj.payload[..16].try_into().unwrap());
let inc = u128::from_le_bytes(obj.payload[16..].try_into().unwrap());
if inc != INCREMENT {
return Err(ValueError::Type);
}
Ok(Pcg64 { state, inc })
}
/// Caller validated this handle and retained its roots, with no intervening
/// safepoint. Mutation is fixed-width and cannot allocate or fail.
pub(crate) fn commit_random(&mut self, r: HeapRef, state: Pcg64) {
let obj = self.objects[r.index as usize].as_mut().expect("validated random object");
obj.payload[..16].copy_from_slice(&state.state.to_le_bytes());
}
}
@@ -12,7 +12,7 @@ const fn query(
owner: &'static str,
name: &'static str,
ret_layout: &'static [AbiType],
implementation: crate::IntrinsicImplementation,
implementation: crate::IntrinsicHostImplementation,
) -> IntrinsicMeta {
IntrinsicMeta {
id,
@@ -23,9 +23,13 @@ const fn query(
ret_layout,
parameter_names: &[],
cost_cycles: 1,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation,
implementation: crate::IntrinsicImplementation::Host(implementation),
}
}
+6 -4
View File
@@ -7,6 +7,8 @@ mod call_frame;
mod input_intrinsics;
mod math_intrinsics;
mod numeric;
mod random;
mod random_intrinsics;
pub use numeric::NumericError;
mod local_addressing;
// Keep the verifier internal in production builds, but expose it for integration tests
@@ -38,10 +40,10 @@ mod vm_init_error;
pub use builtins::{
AbiType, BuiltinConstKey, BuiltinConstMaterializer, BuiltinConstMeta, BuiltinConstSlotValue,
BuiltinFieldMeta, BuiltinLayoutType, BuiltinScalarType, BuiltinTypeKey, BuiltinTypeMeta,
BuiltinTypeShape, BuiltinValueError, IntrinsicExecutionError, IntrinsicImplementation,
IntrinsicKey, IntrinsicMeta, builtin_constant_catalog, intrinsic_catalog,
lookup_builtin_constant, lookup_builtin_type, lookup_intrinsic, lookup_intrinsic_by_id,
materialize_builtin_constant,
BuiltinTypeShape, BuiltinValueError, IntrinsicCostModel, IntrinsicExecutionError,
IntrinsicHostImplementation, IntrinsicImplementation, IntrinsicKey, IntrinsicMeta,
builtin_constant_catalog, intrinsic_catalog, lookup_builtin_constant, lookup_builtin_type,
lookup_intrinsic, lookup_intrinsic_by_id, materialize_builtin_constant,
};
pub use prometeu_hal::{HostContext, HostReturn, NativeInterface, SyscallId};
pub use virtual_machine::{BudgetReport, LogicalFrameEndingReason, VirtualMachine};
@@ -23,9 +23,13 @@ const fn entry<const ID: u32>(
ret_layout,
parameter_names,
cost_cycles,
cost_model: crate::IntrinsicCostModel::Fixed,
attempt_cost_cycles: 0,
max_attempts: 0,
mutates_guest_state: false,
deterministic: true,
may_allocate: false,
implementation: execute::<ID>,
implementation: crate::IntrinsicImplementation::Host(execute::<ID>),
}
}
pub(crate) const MATH_INTRINSICS: [IntrinsicMeta; 26] = [
+3
View File
@@ -86,6 +86,9 @@ pub enum ObjectKind {
/// Internal immutable multi-slot Dynamic payload, never a nominal guest type.
DynamicBox = 8,
/// Opaque PCG64 generator, with no transitive references.
Random = 9,
// Future kinds must be appended here to keep tag numbers stable.
}
+99
View File
@@ -0,0 +1,99 @@
//! PCG-XSL-RR 128/64 setseq. No host entropy or floating arithmetic.
use crate::numeric;
use prometeu_bytecode::TRAP_RANDOM_REJECTION_LIMIT;
const MULTIPLIER: u128 = 0x2360_ED05_1FC6_5DA4_4385_DF64_9FCC_F645;
pub(crate) const INCREMENT: u128 = 109;
pub(crate) const MAX_ATTEMPTS: u32 = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Pcg64 {
pub state: u128,
pub inc: u128,
}
impl Pcg64 {
pub fn new(seed: i64) -> Self {
let bits = u128::from(seed as u64);
Self {
state: bits.wrapping_add(INCREMENT).wrapping_mul(MULTIPLIER).wrapping_add(INCREMENT),
inc: INCREMENT,
}
}
pub fn next(&mut self) -> u64 {
self.state = self.state.wrapping_mul(MULTIPLIER).wrapping_add(self.inc);
let x = self.state as u64 ^ (self.state >> 64) as u64;
x.rotate_right((self.state >> 122) as u32)
}
}
pub(crate) fn float_word(word: u64) -> f64 {
// k <= 2^53-1 is exactly representable; dividing by 2^53 is exact.
numeric::div(numeric::from_i64((word >> 11) as i64), f64::from_bits(0x4340_0000_0000_0000))
.expect("finite exact random grid division")
}
/// Bounds were checked by the VM before reservations. The callback performs
/// one charged candidate draw. It can be injected only inside private tests.
pub(crate) fn bounded(min: i64, max: i64, mut draw: impl FnMut() -> u64) -> Result<i64, u32> {
debug_assert!(min < max);
let n = (i128::from(max) - i128::from(min)) as u64;
let threshold = n.wrapping_neg() % n;
for _ in 0..MAX_ATTEMPTS {
let word = draw();
if word >= threshold {
return Ok((i128::from(min) + i128::from(word % n)) as i64);
}
}
Err(TRAP_RANDOM_REJECTION_LIMIT)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zero_rotation_state_and_float_endpoints() {
let mut p = Pcg64 { state: 0, inc: INCREMENT };
assert_eq!(p.next(), 109);
assert_eq!(float_word(0).to_bits(), 0);
assert_eq!(float_word(u64::MAX).to_bits(), 0x3fef_ffff_ffff_ffff);
}
#[test]
fn threshold_boundaries_full_width_and_unit_consumption() {
for (min, max) in [(0, 1), (-3, 3), (i64::MIN, i64::MAX), (-1, i64::MAX)] {
let n = (i128::from(max) - i128::from(min)) as u64;
let threshold = n.wrapping_neg() % n;
let mut attempts = 0;
let value = bounded(min, max, || {
attempts += 1;
if attempts == 1 && threshold > 0 { threshold - 1 } else { threshold }
})
.unwrap();
assert_eq!(attempts, if threshold > 0 { 2 } else { 1 });
assert_eq!(value, (i128::from(min) + i128::from(threshold % n)) as i64);
}
}
#[test]
fn sixty_fourth_success_and_cap_are_distinct() {
let mut n = 0;
assert_eq!(
bounded(0, 3, || {
n += 1;
if n == 64 { 1 } else { 0 }
}),
Ok(1)
);
assert_eq!(n, 64);
n = 0;
assert_eq!(
bounded(0, 3, || {
n += 1;
0
}),
Err(TRAP_RANDOM_REJECTION_LIMIT)
);
assert_eq!(n, 64);
}
}
@@ -0,0 +1,45 @@
//! The shared catalog owns IDs, layouts, effects and charging descriptors.
use crate::{
AbiType, BuiltinScalarType, BuiltinTypeKey, IntrinsicCostModel, IntrinsicImplementation,
IntrinsicMeta,
};
const I64: AbiType = AbiType::Scalar(BuiltinScalarType::Int64);
const FLOAT: AbiType = AbiType::Scalar(BuiltinScalarType::Float);
const RANDOM: AbiType = AbiType::Builtin(BuiltinTypeKey::new("Random", 1));
const fn entry(
id: u32,
name: &'static str,
args: &'static [AbiType],
ret: &'static [AbiType],
names: &'static [&'static str],
cost: u64,
) -> IntrinsicMeta {
let rejection = id == 0x4003;
IntrinsicMeta {
id,
owner: "random",
name,
version: 1,
arg_layout: args,
ret_layout: ret,
parameter_names: names,
cost_cycles: cost,
cost_model: if rejection {
IntrinsicCostModel::RandomRejectionV1
} else {
IntrinsicCostModel::Fixed
},
attempt_cost_cycles: if rejection { 8 } else { 0 },
max_attempts: if rejection { crate::random::MAX_ATTEMPTS } else { 0 },
deterministic: true,
mutates_guest_state: true,
may_allocate: id == 0x4000,
implementation: IntrinsicImplementation::VmOwned,
}
}
pub(crate) const RANDOM_INTRINSICS: [IntrinsicMeta; 4] = [
entry(0x4000, "new", &[I64], &[RANDOM], &["seed"], 32),
entry(0x4001, "next", &[RANDOM], &[I64], &["rng"], 8),
entry(0x4002, "nextf", &[RANDOM], &[FLOAT], &["rng"], 12),
entry(0x4003, "range", &[RANDOM, I64, I64], &[I64], &["rng", "min", "max"], 4),
];
@@ -204,6 +204,7 @@ fn component(registry: &Registry, ty: TypeId, part: u32, budget: &mut LoadBudget
TypeKind::Builtin(B::FLOAT | B::VEC2) => FLOAT,
TypeKind::Builtin(B::BOOL) => BOOL,
TypeKind::Builtin(B::STRING) => STRING | NULL,
TypeKind::Builtin(B::RANDOM) => REFERENCE | NULL,
TypeKind::Builtin(B::DYNAMIC) => {
if part == 0 {
I64 | NULL
@@ -558,6 +559,7 @@ fn abi_mask(abi: AbiType) -> u8 {
AbiType::Scalar(BuiltinScalarType::Bool) => BOOL,
AbiType::Scalar(BuiltinScalarType::String) => STRING,
AbiType::Builtin(key) if key.name == "color" => I64,
AbiType::Builtin(key) if key.name == "Random" => REFERENCE | NULL,
AbiType::DynamicTag => I64 | NULL,
_ => ANY,
}
@@ -103,9 +103,10 @@ impl TypedStorage {
// until every native value is constructed. Count advances only after init.
unsafe {
match self.registry.declarations().types[ty.0 as usize].kind {
TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Fn(_) => {
self.data.init(offset, HeapRef::NULL)
}
TypeKind::Struct(_)
| TypeKind::Array(_)
| TypeKind::Fn(_)
| TypeKind::Builtin(B::RANDOM) => self.data.init(offset, HeapRef::NULL),
TypeKind::Trait(_) => self.data.init(
offset,
TraitSlot { receiver: HeapRef::NULL, implementation: 0, padding: 0 },
@@ -135,7 +136,10 @@ impl TypedStorage {
// immutable Registry. Only matching typed writes can change its contents.
let result = unsafe {
match self.registry.declarations().types[ty.0 as usize].kind {
TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Fn(_) => {
TypeKind::Struct(_)
| TypeKind::Array(_)
| TypeKind::Fn(_)
| TypeKind::Builtin(B::RANDOM) => {
let r = *self.data.get::<HeapRef>(offset);
ValueGroup::new(&[if r.is_null() { Value::Null } else { Value::HeapRef(r) }])
}
@@ -205,11 +209,18 @@ impl TypedStorage {
// &mut self gives exclusive access. Native assignment drops exactly once.
unsafe {
match (&self.registry.declarations().types[ty.0 as usize].kind, values) {
(TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Fn(_), [Value::Null]) => {
self.data.replace(offset, HeapRef::NULL)
}
(
TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Fn(_),
TypeKind::Struct(_)
| TypeKind::Array(_)
| TypeKind::Fn(_)
| TypeKind::Builtin(B::RANDOM),
[Value::Null],
) => self.data.replace(offset, HeapRef::NULL),
(
TypeKind::Struct(_)
| TypeKind::Array(_)
| TypeKind::Fn(_)
| TypeKind::Builtin(B::RANDOM),
[Value::HeapRef(r)],
) => self.data.replace(offset, *r),
(TypeKind::Trait(_), [Value::Null, Value::Null]) => self.data.replace(
@@ -68,6 +68,14 @@ pub(crate) fn validate(
}
_ => false,
},
TypeKind::Builtin(B::RANDOM) => match &values[0] {
Value::Null => true,
Value::HeapRef(r) => {
heap.random_state(*r)?;
true
}
_ => false,
},
TypeKind::Fn(_) => match &values[0] {
Value::Null => true,
Value::HeapRef(r) if !r.is_null() => heap.closure_type(*r)? == type_id,
@@ -8,6 +8,7 @@ mod control;
mod dynamic;
mod gc;
mod loader;
mod random;
mod reference;
mod runtime;
mod stack;
@@ -892,6 +893,10 @@ impl VirtualMachine {
)
})?;
if matches!(intrinsic.implementation, crate::IntrinsicImplementation::VmOwned) {
return self.execute_random(intrinsic, pc_at_intrinsic);
}
let args_count = intrinsic.arg_slots();
let mut args = BudgetVec::new(&self.budget, RuntimeResource::TemporaryBytes);
args.reserve(args_count)
@@ -923,7 +928,11 @@ impl VirtualMachine {
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
let results = intrinsic
.validate_argument_values(&args)
.and_then(|()| (intrinsic.implementation)(&args, ctx))
.and_then(|()| {
(intrinsic.implementation.host_callback().expect("host intrinsic"))(
&args, ctx,
)
})
.map_err(|err| match err {
crate::IntrinsicExecutionError::ArityMismatch { expected, got } => self
.trap(
@@ -0,0 +1,504 @@
//! Validate/reserve/stage/commit while retaining source operands and roots.
use super::*;
use crate::random::{self, Pcg64};
use crate::value_contract::ValueError;
impl VirtualMachine {
pub(super) fn execute_random(
&mut self,
meta: &crate::IntrinsicMeta,
pc: u32,
) -> Result<(), LogicalFrameEndingReason> {
self.execute_random_with(meta, pc, Pcg64::next)
}
fn execute_random_with(
&mut self,
meta: &crate::IntrinsicMeta,
pc: u32,
mut draw: impl FnMut(&mut Pcg64) -> u64,
) -> Result<(), LogicalFrameEndingReason> {
let op = OpCode::Intrinsic;
self.cycles += meta.cost_cycles;
let consumed = meta.arg_slots();
if self.temporary_slots() < consumed {
return Err(self.trap(
TRAP_STACK_UNDERFLOW,
op as u16,
"Incomplete random operands".into(),
pc,
));
}
let base = self.operand_stack.len() - consumed;
meta.validate_argument_values(&self.operand_stack[base..])
.map_err(|_| self.value_trap(ValueError::Type, op, pc))?;
let receiver = if meta.id != 0x4000 {
match self.operand_stack[base] {
Value::Null => return Err(self.value_trap(ValueError::NullReference, op, pc)),
Value::HeapRef(r) => Some(r),
_ => unreachable!("checked random carrier"),
}
} else {
None
};
let mut candidate = receiver
.map(|r| self.heap.random_state(r))
.transpose()
.map_err(|e| self.value_trap(e, op, pc))?;
let bounds = if meta.id == 0x4003 {
let (Value::Int64(min), Value::Int64(max)) =
(&self.operand_stack[base + 1], &self.operand_stack[base + 2])
else {
unreachable!("checked integer carriers")
};
if min >= max {
return Err(self.trap(
prometeu_bytecode::TRAP_NUMERIC_DOMAIN,
op as u16,
"random.range requires min < max".into(),
pc,
));
}
Some((*min, *max))
} else {
None
};
let growth = self
.operand_stack
.prepare_growth(meta.ret_slots().saturating_sub(consumed))
.map_err(|e| self.resource_trap(e, op, pc))?;
let _result_charge = self
.budget
.reserve(
RuntimeResource::TemporaryBytes,
self.budget
.bytes::<Value>(1, RuntimeResource::TemporaryBytes)
.map_err(|e| self.resource_trap(e, op, pc))?,
)
.map_err(|e| self.resource_trap(e, op, pc))?;
let result = match meta.id {
0x4000 => {
let Value::Int64(seed) = self.operand_stack[base] else {
unreachable!("checked seed carrier")
};
Value::HeapRef(
self.heap.allocate_random(seed).map_err(|e| self.resource_trap(e, op, pc))?,
)
}
0x4001 => Value::Int64(draw(candidate.as_mut().unwrap()) as i64),
0x4002 => Value::Float(random::float_word(draw(candidate.as_mut().unwrap()))),
0x4003 => {
let (min, max) = bounds.unwrap();
let value = random::bounded(min, max, || {
self.cycles += meta.attempt_cost_cycles;
draw(candidate.as_mut().unwrap())
})
.map_err(|code| {
self.trap(code, op as u16, "Random rejection limit reached".into(), pc)
})?;
Value::Int64(value)
}
_ => unreachable!("shared catalog VM-owned identity"),
};
// All fallible work finished. Source roots remained live throughout.
if let Some(r) = receiver {
self.heap.commit_random(r, candidate.unwrap());
}
self.operand_stack.commit_growth(growth);
self.operand_stack.truncate(base);
self.operand_stack.push(result).expect("reserved random result slot");
Ok(())
}
}
#[cfg(test)]
#[path = "../../tests/support/random.rs"]
mod support;
#[cfg(test)]
mod tests {
use super::*;
use crate::object::ObjectKind;
use crate::random::MAX_ATTEMPTS;
use prometeu_bytecode::registry::TypeId;
use prometeu_bytecode::{TRAP_NUMERIC_DOMAIN, TRAP_RANDOM_REJECTION_LIMIT, assemble};
use support::{Native, run, sig, step, vm};
fn trap_code(r: &LogicalFrameEndingReason) -> u32 {
let LogicalFrameEndingReason::Trap(t) = r else { panic!("{r:?}") };
t.code
}
fn fault_vm(id: u32, args: &[Value]) -> VirtualMachine {
let mut v =
VirtualMachine::fault_session(assemble(&format!("INTRINSIC {id}")).unwrap(), vec![]);
v.operand_stack.extend_from_slice(args).unwrap();
v
}
fn charges(v: &VirtualMachine) -> Vec<u64> {
[
RuntimeResource::GuestBytes,
RuntimeResource::HandleSlots,
RuntimeResource::AuxiliaryBytes,
RuntimeResource::TemporaryBytes,
]
.iter()
.map(|&q| v.budget.used(q))
.collect()
}
#[test]
fn carrier_receiver_bounds_precedence_and_all_faults_retain_sources() {
for id in [0x4001, 0x4002, 0x4003] {
for case in 0..9 {
let mut v = fault_vm(id, &[]);
let live = v.heap.allocate_random(42).unwrap();
let wrong = v.heap.allocate_object(ObjectKind::Bytes, &[]).unwrap();
let (receiver, lo, hi, code) = match case {
0 => (Value::Boolean(false), Value::Int64(1), Value::Int64(2), TRAP_TYPE),
1 => (
Value::Null,
Value::Int32(1),
Value::Int64(2),
if id == 0x4003 { TRAP_TYPE } else { TRAP_NULL_REFERENCE },
),
2 => (
Value::HeapRef(HeapRef { index: 99, generation: 1 }),
Value::Int64(2),
Value::Int64(1),
TRAP_INVALID_HANDLE,
),
3 => (
Value::HeapRef(HeapRef {
index: live.index,
generation: live.generation + 1,
}),
Value::Int64(1),
Value::Int64(2),
TRAP_INVALID_HANDLE,
),
4 => (
Value::HeapRef(HeapRef::NULL),
Value::Int64(1),
Value::Int64(2),
TRAP_INVALID_HANDLE,
),
5 => (Value::HeapRef(wrong), Value::Int64(2), Value::Int64(1), TRAP_TYPE),
6 => (Value::Null, Value::Int64(2), Value::Int64(1), TRAP_NULL_REFERENCE),
7 => (
Value::HeapRef(live),
Value::Int64(2),
Value::Int64(1),
TRAP_NUMERIC_DOMAIN,
),
_ => (Value::HeapRef(live), Value::Int64(1), Value::Boolean(false), TRAP_TYPE),
};
if id != 0x4003 && case >= 7 {
continue;
}
let mut args = vec![receiver];
if id == 0x4003 {
args.extend([lo, hi]);
}
v.operand_stack.extend_from_slice(&args).unwrap();
let state = v.heap.random_state(live).unwrap();
let ownership = charges(&v);
let r = v.run_budget(1, &mut Native, &mut HostContext::new(None)).unwrap();
assert_eq!(trap_code(&r.reason), code, "id={id}, case={case}");
assert_eq!(
(r.cycles_used, r.steps_executed),
(
if id == 0x4001 {
8
} else if id == 0x4002 {
12
} else {
4
},
0
)
);
assert_eq!(v.operand_stack.as_slice(), args);
assert_eq!(v.heap.random_state(live).unwrap(), state);
assert_eq!(charges(&v), ownership);
let LogicalFrameEndingReason::Trap(t) = r.reason else { unreachable!() };
assert_eq!((t.pc, t.opcode), (0, OpCode::Intrinsic as u16));
}
}
}
#[test]
fn short_stack_and_seed_carriers_charge_without_consumption() {
for id in 0x4000..=0x4003 {
let mut v = fault_vm(id, &[]);
let r = run(&mut v, 1);
assert_eq!(trap_code(&r.reason), TRAP_STACK_UNDERFLOW);
assert_eq!(r.steps_executed, 0);
assert_eq!(r.cycles_used, crate::lookup_intrinsic_by_id(id).unwrap().cost_cycles);
}
for seed in [Value::Null, Value::Int32(42), Value::Float(42.)] {
let mut v = fault_vm(0x4000, std::slice::from_ref(&seed));
let r = run(&mut v, 1);
assert_eq!(trap_code(&r.reason), TRAP_TYPE);
assert_eq!(v.operand_stack.as_slice(), &[seed]);
assert_eq!(v.heap.len(), 0);
}
}
#[test]
fn synthetic_rejections_use_real_transaction_cost_and_rollback() {
for accept in [None, Some(1), Some(3), Some(MAX_ATTEMPTS)] {
let mut v = fault_vm(0x4003, &[]);
let r = v.heap.allocate_random(42).unwrap();
let args = [Value::HeapRef(r), Value::Int64(0), Value::Int64(3)];
v.operand_stack.extend_from_slice(&args).unwrap();
let original = v.heap.random_state(r).unwrap();
let owned = charges(&v);
let mut attempts = 0;
let result =
v.execute_random_with(crate::lookup_intrinsic_by_id(0x4003).unwrap(), 0, |state| {
attempts += 1;
state.next();
if Some(attempts) == accept { 1 } else { 0 }
});
assert_eq!(v.cycles, 4 + 8 * u64::from(attempts));
assert_eq!(attempts, accept.unwrap_or(64));
assert_eq!(charges(&v), owned);
if accept.is_some() {
result.unwrap();
assert_eq!(v.operand_stack.as_slice(), &[Value::Int64(1)]);
let mut expected = original;
for _ in 0..attempts {
expected.next();
}
assert_eq!(v.heap.random_state(r).unwrap(), expected);
} else {
assert_eq!(trap_code(&result.unwrap_err()), TRAP_RANDOM_REJECTION_LIMIT);
assert_eq!(v.heap.random_state(r).unwrap(), original);
assert_eq!(v.operand_stack.as_slice(), &args);
// A subsequent normal draw sees the first canonical word, proving rollback.
v.operand_stack.truncate(1);
v.execute_random(crate::lookup_intrinsic_by_id(0x4001).unwrap(), 0).unwrap();
assert_eq!(v.operand_stack[0], Value::Int64(0x86b1_da1d_7206_2b68u64 as i64));
}
}
}
#[test]
fn resource_refusals_preserve_all_charges_seed_and_candidate_state() {
for limit in [0, 1, size_of::<crate::heap::StoredObject>() as u64 + 16] {
let mut v = fault_vm(0x4000, &[Value::Int64(42)]);
v.budget.test_lower_limit(RuntimeResource::GuestBytes, limit);
let owned = charges(&v);
let err =
v.execute_random(crate::lookup_intrinsic_by_id(0x4000).unwrap(), 0).unwrap_err();
assert_eq!(trap_code(&err), TRAP_RESOURCE_LIMIT);
assert_eq!(charges(&v), owned);
assert_eq!(v.heap.allocation_count(), 0);
assert_eq!(v.operand_stack.as_slice(), &[Value::Int64(42)]);
}
for q in [RuntimeResource::AuxiliaryBytes, RuntimeResource::HandleSlots] {
let mut v = fault_vm(0x4000, &[Value::Int64(42)]);
v.budget.test_lower_limit(q, v.budget.used(q));
let owned = charges(&v);
let err =
v.execute_random(crate::lookup_intrinsic_by_id(0x4000).unwrap(), 0).unwrap_err();
assert_eq!(trap_code(&err), TRAP_RESOURCE_LIMIT);
assert_eq!(charges(&v), owned);
assert_eq!(v.heap.len(), 0);
}
for id in [0x4001, 0x4002, 0x4003] {
let mut v = fault_vm(id, &[]);
let r = v.heap.allocate_random(42).unwrap();
let state = v.heap.random_state(r).unwrap();
let mut args = vec![Value::HeapRef(r)];
if id == 0x4003 {
args.extend([Value::Int64(0), Value::Int64(3)]);
}
v.operand_stack.extend_from_slice(&args).unwrap();
v.budget.test_lower_limit(RuntimeResource::TemporaryBytes, 0);
let owned = charges(&v);
let mut draws = 0;
let err = v
.execute_random_with(crate::lookup_intrinsic_by_id(id).unwrap(), 0, |p| {
draws += 1;
p.next()
})
.unwrap_err();
assert_eq!(trap_code(&err), TRAP_RESOURCE_LIMIT);
assert_eq!(draws, 0);
assert_eq!(charges(&v), owned);
assert_eq!(v.operand_stack.as_slice(), args);
assert_eq!(v.heap.random_state(r).unwrap(), state);
assert_eq!(v.cycles, crate::lookup_intrinsic_by_id(id).unwrap().cost_cycles);
}
}
#[test]
fn every_random_root_survives_gc_then_releases_and_stale_handles_fault() {
// Local, global, typed field, typed array, capture and direct Dynamic roots.
for root in 0..6 {
let mut v = vm(&[
("RET", sig(&[], &[]), vec![], 1),
("GET_CAPTURE 0\nINTRINSIC 16385\nRET", sig(&[], &[0]), vec![TypeId(1)], 0),
]);
let registry = v.validated_image.as_ref().unwrap().registry().clone();
let r = v.heap.allocate_random(42).unwrap();
match root {
0 => v.operand_stack[0] = Value::HeapRef(r),
1 => v.globals.push(Value::HeapRef(r)).unwrap(),
2 => {
let s = v.heap.allocate_typed_struct(registry.clone(), TypeId(4)).unwrap();
v.heap.store_typed(&registry, s, 0, &[Value::HeapRef(r)]).unwrap();
v.globals.push(Value::HeapRef(s)).unwrap();
}
3 => {
let s = v.heap.allocate_typed_array(registry.clone(), TypeId(5), 1).unwrap();
v.heap.store_typed(&registry, s, 0, &[Value::HeapRef(r)]).unwrap();
v.globals.push(Value::HeapRef(s)).unwrap();
}
4 => {
let s = v.heap.alloc_typed_closure(1, TypeId(6), &[Value::HeapRef(r)]).unwrap();
v.globals.push(Value::HeapRef(s)).unwrap();
}
_ => {
let d = crate::value_contract::pack_dynamic(
&registry,
&mut v.heap,
TypeId(1),
&[Value::HeapRef(r)],
)
.unwrap();
v.globals.extend_from_slice(d.as_slice()).unwrap();
}
}
let original = v.heap.random_state(r).unwrap();
v.gc_alloc_threshold = 1;
v.handle_safepoint().unwrap();
assert!(v.heap.is_valid(r));
assert_eq!(v.heap.random_state(r).unwrap(), original);
v.globals.clear();
v.operand_stack[0] = Value::Null;
v.last_gc_live_count = 0;
v.handle_safepoint().unwrap();
assert!(!v.heap.is_valid(r));
assert_eq!(v.heap.len(), 0);
assert_eq!(v.budget.used(RuntimeResource::GuestBytes), 0);
v.operand_stack.push(Value::HeapRef(r)).unwrap();
let err =
v.execute_random(crate::lookup_intrinsic_by_id(0x4001).unwrap(), 0).unwrap_err();
assert_eq!(trap_code(&err), TRAP_INVALID_HANDLE);
}
}
#[test]
fn dynamic_defaults_exact_types_wrong_objects_and_no_trait_adaptation() {
let mut v = vm(&[("RET", sig(&[], &[]), vec![], 0)]);
let registry = v.validated_image.as_ref().unwrap().registry().clone();
let r = v.heap.allocate_random(42).unwrap();
let packed = crate::value_contract::pack_dynamic(
&registry,
&mut v.heap,
TypeId(1),
&[Value::HeapRef(r)],
)
.unwrap();
assert_eq!(packed.as_slice(), &[Value::Int64(1), Value::HeapRef(r)]);
assert_eq!(v.heap.allocation_count(), 1);
assert_eq!(
crate::value_contract::unpack_dynamic(&registry, &v.heap, TypeId(1), packed.as_slice())
.unwrap()
.as_slice(),
&[Value::HeapRef(r)]
);
assert!(
crate::value_contract::ref_to_trait(
&registry,
&v.heap,
TypeId(1),
TypeId(8),
&[Value::HeapRef(r)]
)
.is_err()
);
for ty in [4, 5] {
let object = if ty == 4 {
v.heap.allocate_typed_struct(registry.clone(), TypeId(4)).unwrap()
} else {
v.heap.allocate_typed_array(registry.clone(), TypeId(5), 1).unwrap()
};
assert_eq!(v.heap.load_typed(&registry, object, 0).unwrap().as_slice(), &[Value::Null]);
let before = v.heap.load_typed(&registry, object, 0).unwrap();
assert_eq!(
v.heap.store_typed(&registry, object, 0, &[Value::HeapRef(object)]),
Err(ValueError::Type)
);
assert_eq!(
v.heap.load_typed(&registry, object, 0).unwrap().as_slice(),
before.as_slice()
);
}
}
#[test]
fn real_unknown_carriers_wrong_kind_and_domain_rollback_resume() {
let code = "GET_GLOBAL 0\nGET_GLOBAL 1\nGET_GLOBAL 2\nINTRINSIC 16387\nPOP\nGET_GLOBAL 0\nINTRINSIC 16385\nRET";
for bad in 0..4 {
let mut v = vm(&[(code, sig(&[], &[0]), vec![], 0)]);
let r = v.heap.allocate_random(42).unwrap();
let receiver = if bad == 0 {
Value::Null
} else if bad == 1 {
Value::HeapRef(v.heap.allocate_object(ObjectKind::Bytes, &[]).unwrap())
} else {
Value::HeapRef(r)
};
let lo = if bad == 2 { Value::Int32(0) } else { Value::Int64(2) };
let hi = Value::Int64(1);
v.globals.extend_from_slice(&[receiver, lo, hi]).unwrap();
for _ in 0..3 {
step(&mut v);
}
let args = v.operand_stack.as_slice().to_vec();
let report = run(&mut v, 1);
assert_eq!(report.cycles_used, 4);
assert_eq!(report.steps_executed, 0);
assert_eq!(v.operand_stack.as_slice(), args);
assert_eq!(
trap_code(&report.reason),
[TRAP_NULL_REFERENCE, TRAP_TYPE, TRAP_TYPE, TRAP_NUMERIC_DOMAIN][bad]
);
assert_eq!(v.heap.random_state(r).unwrap(), Pcg64::new(42));
// Resume after fault with the retained generator and verify first word.
v.globals[0] = Value::HeapRef(r);
v.operand_stack.clear();
v.operand_stack.push(Value::Int64(0)).unwrap();
assert_eq!(run(&mut v, 1000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(v.operand_stack[0], Value::Int64(0x86b1_da1d_7206_2b68u64 as i64));
}
}
#[test]
fn reset_unload_and_other_session_do_not_import_snapshot_handles() {
let bodies = [
("PUSH_I64 42\nINTRINSIC 16384\nRET", sig(&[], &[1]), vec![], 0),
("GET_LOCAL 0\nRET", sig(&[1], &[1]), vec![], 0),
];
let mut v = vm(&bodies);
run(&mut v, 1000);
let snapshot = v.operand_stack_top(1);
let Value::HeapRef(r) = snapshot[0] else { panic!() };
let owned = v.budget.clone();
let mut other =
VirtualMachine::from_image(support::image(&bodies).unwrap(), RuntimeLimits::default());
assert!(matches!(
other.prepare_call_with_args("1", &snapshot),
Err(VmInitError::EntrypointArgumentsInvalid { trap_code: TRAP_INVALID_HANDLE, .. })
));
v.initialize(support::bytes(&bodies)).unwrap();
assert!(!v.heap.is_valid(r));
assert_eq!(owned.used(RuntimeResource::GuestBytes), 0);
assert_eq!(owned.used(RuntimeResource::HandleSlots), 0);
assert!(matches!(
v.prepare_call_with_args("1", &snapshot),
Err(VmInitError::EntrypointArgumentsInvalid { trap_code: TRAP_INVALID_HANDLE, .. })
));
v.prepare_boot_call().unwrap();
run(&mut v, 1000);
let owned = v.budget.clone();
drop(v);
assert_eq!(owned.used(RuntimeResource::GuestBytes), 0);
assert_eq!(owned.used(RuntimeResource::HandleSlots), 0);
}
}
@@ -8,11 +8,12 @@ use prometeu_vm::{
};
#[test]
fn all_nine_descriptors_match_registry_storage_and_canonical_defaults() {
fn all_ten_descriptors_match_registry_storage_and_canonical_defaults() {
for (name, id, size, alignment, width, nullable) in [
("color", 1, 4, 4, 1, false),
("vec2", 2, 16, 8, 2, false),
("pixel", 3, 24, 8, 3, false),
("Random", 0x16, 8, 8, 1, true),
("Int32", 0x10, 4, 4, 1, false),
("Int64", 0x11, 8, 8, 1, false),
("Float", 0x12, 8, 8, 1, false),
@@ -0,0 +1,49 @@
seed draw word_hex signed float_bits
0 1 9B3184D7EE6BACDB -7263878661019030309 3FE366309AFDCD75
0 2 8B7B271AA4769FD4 -8396074084920287276 3FE16F64E3548ED3
0 3 9B4DB63DFE544AAB -7255943047247803733 3FE369B6C7BFCA89
0 4 E714BA3532308667 -1795605613775911321 3FECE29746A64610
0 5 64EAF919A9A040E2 7271898436958437602 3FD93ABE466A6810
0 6 325BCFFB862545B0 3628722603971397040 3FC92DE7FDC312A0
0 7 70180161DC24B6EC 8077207451505833708 3FDC06005877092C
0 8 39257F36B038F771 4117837307161671537 3FCC92BF9B581C78
1 1 3150032F5C48AC0A 3553343607941934090 3FC8A80197AE2454
1 2 099B2F21D97DB047 692198790160822343 3FA3365E43B2FB60
1 3 7539BA4A2ED012EB 8446987403885810411 3FDD4E6E928BB404
1 4 C842BA297694C455 -4016443230415174571 3FE90857452ED298
1 5 C8AE2BB397CD3537 -3986200569830361801 3FE915C57672F9A6
1 6 C2F1AF39457336BA -4399542700451088710 3FE85E35E728AE66
1 7 8710A37C51FEC0AD -8714285524614987603 3FE0E2146F8A3FD8
1 8 A4C73DCA70459C07 -6573217191447651321 3FE498E7B94E08B3
42 1 86B1DA1D72062B68 -8740965581747508376 3FE0D63B43AE40C5
42 2 1304AA46C9853D39 1370407407632858425 3FB304AA46C98538
42 3 A3670E9E0DD50358 -6672348250926415016 3FE46CE1D3C1BAA0
42 4 F9090E529A7DAE00 -501854135533064704 3FEF2121CA534FB5
42 5 C85B9FD837996F2C -4009435292248740052 3FE90B73FB06F32D
42 6 606121F8E3919196 6944869453235589526 3FD818487E38E464
42 7 7CE1C7FF478354BA 8998693429693338810 3FDF3871FFD1E0D4
42 8 CBC4AC70E541310E -3763693787692322546 3FE978958E1CA826
-1 1 EE89537ECBD16900 -1258382816822859520 3FEDD12A6FD97A2D
-1 2 DCBE53D8A6C852E6 -2540500949814193434 3FEB97CA7B14D90A
-1 3 561BA13FFCFD5094 6204730207832461460 3FD586E84FFF3F54
-1 4 76962EA43FCF9400 8545068625962177536 3FDDA58BA90FF3E4
-1 5 A2BF24C068F28D0D -6719611710200443635 3FE457E4980D1E51
-1 6 3D575F16AA0C40D8 4420106110234280152 3FCEABAF8B550620
-1 7 032B99D40D100946 228445342143613254 3F895CCEA0688040
-1 8 7053160AB14A824F 8093837190494847567 3FDC14C582AC52A0
-9223372036854775808 1 1C08F9C51E05B9F1 2020139057883232753 3FBC08F9C51E05B8
-9223372036854775808 2 4CC379FA6A441AFF 5531398883772734207 3FD330DE7E9A9106
-9223372036854775808 3 1E9926CF448F8AA7 2204836164224912039 3FBE9926CF448F88
-9223372036854775808 4 18ADD82F6DA7760F 1778315126095967759 3FB8ADD82F6DA770
-9223372036854775808 5 77DFD36640320B00 8637855046437047040 3FDDF7F4D9900C82
-9223372036854775808 6 CE09AC671D48BD0F -3600156868233085681 3FE9C1358CE3A917
-9223372036854775808 7 B15DBA0399E9E3D1 -5666168231532305455 3FE62BB740733D3C
-9223372036854775808 8 E88252991CF3E42C -1692699692368665556 3FED104A53239E7C
9223372036854775807 1 77D44C809FDF62DB 8634610500897825499 3FDDF5132027F7D8
9223372036854775807 2 05BCF3AED615466A 413473198052820586 3F96F3CEBB585500
9223372036854775807 3 693ED392E1CE694A 7583731450345580874 3FDA4FB4E4B8739A
9223372036854775807 4 83D248E707AC837B -8948009352528362629 3FE07A491CE0F590
9223372036854775807 5 5DD1D07026E00956 6760413695766956374 3FD774741C09B802
9223372036854775807 6 5713B8336C9A861C 6274561236862141980 3FD5C4EE0CDB26A0
9223372036854775807 7 4F2E7352ED7CCE69 5705624577933889129 3FD3CB9CD4BB5F32
9223372036854775807 8 DB109447225C784B -2661464346535888821 3FEB621288E44B8F
1 seed draw word_hex signed float_bits
2 0 1 9B3184D7EE6BACDB -7263878661019030309 3FE366309AFDCD75
3 0 2 8B7B271AA4769FD4 -8396074084920287276 3FE16F64E3548ED3
4 0 3 9B4DB63DFE544AAB -7255943047247803733 3FE369B6C7BFCA89
5 0 4 E714BA3532308667 -1795605613775911321 3FECE29746A64610
6 0 5 64EAF919A9A040E2 7271898436958437602 3FD93ABE466A6810
7 0 6 325BCFFB862545B0 3628722603971397040 3FC92DE7FDC312A0
8 0 7 70180161DC24B6EC 8077207451505833708 3FDC06005877092C
9 0 8 39257F36B038F771 4117837307161671537 3FCC92BF9B581C78
10 1 1 3150032F5C48AC0A 3553343607941934090 3FC8A80197AE2454
11 1 2 099B2F21D97DB047 692198790160822343 3FA3365E43B2FB60
12 1 3 7539BA4A2ED012EB 8446987403885810411 3FDD4E6E928BB404
13 1 4 C842BA297694C455 -4016443230415174571 3FE90857452ED298
14 1 5 C8AE2BB397CD3537 -3986200569830361801 3FE915C57672F9A6
15 1 6 C2F1AF39457336BA -4399542700451088710 3FE85E35E728AE66
16 1 7 8710A37C51FEC0AD -8714285524614987603 3FE0E2146F8A3FD8
17 1 8 A4C73DCA70459C07 -6573217191447651321 3FE498E7B94E08B3
18 42 1 86B1DA1D72062B68 -8740965581747508376 3FE0D63B43AE40C5
19 42 2 1304AA46C9853D39 1370407407632858425 3FB304AA46C98538
20 42 3 A3670E9E0DD50358 -6672348250926415016 3FE46CE1D3C1BAA0
21 42 4 F9090E529A7DAE00 -501854135533064704 3FEF2121CA534FB5
22 42 5 C85B9FD837996F2C -4009435292248740052 3FE90B73FB06F32D
23 42 6 606121F8E3919196 6944869453235589526 3FD818487E38E464
24 42 7 7CE1C7FF478354BA 8998693429693338810 3FDF3871FFD1E0D4
25 42 8 CBC4AC70E541310E -3763693787692322546 3FE978958E1CA826
26 -1 1 EE89537ECBD16900 -1258382816822859520 3FEDD12A6FD97A2D
27 -1 2 DCBE53D8A6C852E6 -2540500949814193434 3FEB97CA7B14D90A
28 -1 3 561BA13FFCFD5094 6204730207832461460 3FD586E84FFF3F54
29 -1 4 76962EA43FCF9400 8545068625962177536 3FDDA58BA90FF3E4
30 -1 5 A2BF24C068F28D0D -6719611710200443635 3FE457E4980D1E51
31 -1 6 3D575F16AA0C40D8 4420106110234280152 3FCEABAF8B550620
32 -1 7 032B99D40D100946 228445342143613254 3F895CCEA0688040
33 -1 8 7053160AB14A824F 8093837190494847567 3FDC14C582AC52A0
34 -9223372036854775808 1 1C08F9C51E05B9F1 2020139057883232753 3FBC08F9C51E05B8
35 -9223372036854775808 2 4CC379FA6A441AFF 5531398883772734207 3FD330DE7E9A9106
36 -9223372036854775808 3 1E9926CF448F8AA7 2204836164224912039 3FBE9926CF448F88
37 -9223372036854775808 4 18ADD82F6DA7760F 1778315126095967759 3FB8ADD82F6DA770
38 -9223372036854775808 5 77DFD36640320B00 8637855046437047040 3FDDF7F4D9900C82
39 -9223372036854775808 6 CE09AC671D48BD0F -3600156868233085681 3FE9C1358CE3A917
40 -9223372036854775808 7 B15DBA0399E9E3D1 -5666168231532305455 3FE62BB740733D3C
41 -9223372036854775808 8 E88252991CF3E42C -1692699692368665556 3FED104A53239E7C
42 9223372036854775807 1 77D44C809FDF62DB 8634610500897825499 3FDDF5132027F7D8
43 9223372036854775807 2 05BCF3AED615466A 413473198052820586 3F96F3CEBB585500
44 9223372036854775807 3 693ED392E1CE694A 7583731450345580874 3FDA4FB4E4B8739A
45 9223372036854775807 4 83D248E707AC837B -8948009352528362629 3FE07A491CE0F590
46 9223372036854775807 5 5DD1D07026E00956 6760413695766956374 3FD774741C09B802
47 9223372036854775807 6 5713B8336C9A861C 6274561236862141980 3FD5C4EE0CDB26A0
48 9223372036854775807 7 4F2E7352ED7CCE69 5705624577933889129 3FD3CB9CD4BB5F32
49 9223372036854775807 8 DB109447225C784B -2661464346535888821 3FEB621288E44B8F
@@ -0,0 +1,19 @@
# Random fixture provenance
The canonical PCG-XSL-RR 128/64 setseq source is pcg-cpp revision
`428802d1a5634f96bcd0705fab379ff0113bcf13`.
Its [check-pcg64.out](https://github.com/imneme/pcg-cpp/blob/428802d1a5634f96bcd0705fab379ff0113bcf13/test-high/expected/check-pcg64.out)
contains the first six seed=42, seq=54 words used here.
Downloaded upstream fixture SHA-256: `afc9e7775bdc59ab90d85caebe533d58ae7324be36cf9a4c975e6d7f86b9df24`.
[random-oracle.py](random-oracle.py) independently uses Python mathematical
integers modulo 2^128, division-based rotation, and Fraction-to-binary64
conversion. It imports no VM/production RNG code and cross-checks those six
canonical words. Additional seeds 0, 1, -1, MIN/MAX and draws 7–8 are generated
by that independent arithmetic model. The Float column maps the same word;
it does not represent alternating calls. Signed values are stored explicitly.
Reproduce with `python3 crates/console/prometeu-vm/tests/fixtures/random-oracle.py`
and check the TSV diff. This is a test oracle, never a runtime dependency.
Statistical quality and sequence conformance are different evidence; these
fixtures establish bits/consumption, not cryptographic or independence claims.
@@ -0,0 +1,23 @@
"""Independent mathematical fixture model (test-only Python arbitrary precision).
Pinned canonical PCG64 seed=42 words cross-check this model; no VM code imported.
"""
from pathlib import Path
from fractions import Fraction
import struct
M = 47026247687942121848144207491837523525
mod = 2**128
rows = ['seed\tdraw\tword_hex\tsigned\tfloat_bits']
first = []
for seed in [0, 1, 42, -1, -(2**63), 2**63-1]:
state = ((seed % 2**64 + 109) * M + 109) % mod
for index in range(1, 9):
state = (state * M + 109) % mod
x = (state % 2**64) ^ (state // 2**64)
rotation = state // 2**122
word = (x // 2**rotation + (x % 2**rotation) * 2**(64-rotation)) % 2**64
signed = word if word < 2**63 else word - 2**64
bits = struct.unpack('>Q', struct.pack('>d', float(Fraction(word // 2**11, 2**53))))[0]
rows.append(f'{seed}\t{index}\t{word:016X}\t{signed}\t{bits:016X}')
if seed == 42 and index <= 6: first.append(f'{word:016X}')
assert first == ['86B1DA1D72062B68','1304AA46C9853D39','A3670E9E0DD50358','F9090E529A7DAE00','C85B9FD837996F2C','606121F8E3919196']
Path(__file__).with_name('random-conformance.tsv').write_text('\n'.join(rows)+'\n')
@@ -26,7 +26,8 @@ impl NativeInterface for NoNative {
}
fn call(id: u32, args: &[Value]) -> Result<Value, E> {
let m = lookup_intrinsic_by_id(id).unwrap();
(m.implementation)(args, &mut HostContext::new(None)).map(|mut v| v.remove(0))
(m.implementation.host_callback().expect("host intrinsic"))(args, &mut HostContext::new(None))
.map(|mut v| v.remove(0))
}
fn floats(id: u32, xs: &[f64]) -> Result<u64, u32> {
match call(id, &xs.iter().copied().map(Value::Float).collect::<Vec<_>>()) {
@@ -0,0 +1,308 @@
mod support {
pub mod random;
}
use prometeu_bytecode::registry::{BuiltinId, Ownership, TypeId};
use prometeu_bytecode::{
TRAP_NULL_REFERENCE, TRAP_NUMERIC_DOMAIN, TRAP_RESOURCE_LIMIT, TRAP_TYPE, Value,
};
use prometeu_vm::resource_budget::{RuntimeLimits, RuntimeResource as Q};
use prometeu_vm::{
IntrinsicCostModel, IntrinsicImplementation, LogicalFrameEndingReason as End, VirtualMachine,
VmInitError, lookup_builtin_type, lookup_intrinsic_by_id,
};
use support::random::*;
fn trap(r: &prometeu_vm::BudgetReport) -> &prometeu_bytecode::TrapInfo {
let End::Trap(t) = &r.reason else { panic!("{r:?}") };
t
}
fn vectors(seed: i64) -> Vec<(u64, i64, u64)> {
include_str!("fixtures/random-conformance.tsv")
.lines()
.skip(1)
.filter_map(|l| {
let cols: Vec<_> = l.split('\t').collect();
(cols[0].parse::<i64>().unwrap() == seed).then(|| {
(
u64::from_str_radix(cols[2], 16).unwrap(),
cols[3].parse().unwrap(),
u64::from_str_radix(cols[4], 16).unwrap(),
)
})
})
.collect()
}
#[test]
fn independent_words_signed_and_float_bits_for_all_seed_patterns() {
for seed in [0, 1, 42, -1, i64::MIN, i64::MAX] {
for floating in [false, true] {
let mut code = format!("PUSH_I64 {seed}\nINTRINSIC 16384\nSET_LOCAL 0\n");
for _ in 0..8 {
code.push_str(if floating {
"GET_LOCAL 0\nINTRINSIC 16386\n"
} else {
"GET_LOCAL 0\nINTRINSIC 16385\n"
});
}
code.push_str("RET");
let mut v = vm(&[(&code, sig(&[], &vec![if floating { 2 } else { 0 }; 8]), vec![], 1)]);
let r = run(&mut v, 10000);
assert_eq!(r.reason, End::EndOfRom);
let expected: Vec<_> = vectors(seed)
.iter()
.rev()
.map(|(_, signed, bits)| {
if floating {
Value::Float(f64::from_bits(*bits))
} else {
Value::Int64(*signed)
}
})
.collect();
assert_eq!(v.operand_stack_top(8), expected, "seed={seed}, Float={floating}");
}
}
}
#[test]
fn interleaving_unit_range_aliases_and_equal_seed_independent_objects() {
let mut v = vm(&[(
"PUSH_I64 42\nINTRINSIC 16384\nDUP\nSET_LOCAL 0\nSET_GLOBAL 0\nPUSH_I64 42\nINTRINSIC 16384\nSET_LOCAL 1\nGET_LOCAL 0\nINTRINSIC 16385\nGET_GLOBAL 0\nINTRINSIC 16386\nGET_LOCAL 0\nPUSH_I64 -7\nPUSH_I64 -6\nINTRINSIC 16387\nGET_LOCAL 0\nINTRINSIC 16385\nGET_LOCAL 1\nINTRINSIC 16385\nRET",
sig(&[], &[0, 2, 0, 0, 0]),
vec![],
2,
)]);
assert_eq!(run(&mut v, 1000).reason, End::EndOfRom);
let x = vectors(42);
assert_eq!(
v.operand_stack_top(5),
vec![
Value::Int64(x[0].1),
Value::Int64(x[3].1),
Value::Int64(-7),
Value::Float(f64::from_bits(x[1].2)),
Value::Int64(x[0].1)
]
);
assert_eq!(v.heap().len(), 2);
}
#[test]
fn range_all_int64_spans_and_power_of_two_consumption() {
for (min, max) in
[(0, 1), (-10, -3), (-10, 10), (0, 16), (i64::MIN, 0), (-1, i64::MAX), (i64::MIN, i64::MAX)]
{
let code = format!(
"PUSH_I64 42\nINTRINSIC 16384\nSET_LOCAL 0\nGET_LOCAL 0\nPUSH_I64 {min}\nPUSH_I64 {max}\nINTRINSIC 16387\nGET_LOCAL 0\nINTRINSIC 16385\nRET"
);
let mut v = vm(&[(&code, sig(&[], &[0, 0]), vec![], 1)]);
assert_eq!(run(&mut v, 1000).reason, End::EndOfRom);
let span = (i128::from(max) - i128::from(min)) as u64;
let first = vectors(42)[0].0;
// This fixed first word is accepted for all these spans, including > i64 MAX.
let expected = (i128::from(min) + i128::from(first % span)) as i64;
assert_eq!(
v.operand_stack_top(2),
vec![Value::Int64(vectors(42)[1].1), Value::Int64(expected)]
);
}
}
#[test]
fn random_storage_dynamic_and_capture_preserve_shared_identity() {
let body = "PUSH_I64 42\nINTRINSIC 16384\nSET_LOCAL 0\nSTRUCT_NEW 4\nDUP\nGET_LOCAL 0\nSTRUCT_SET type=4,field=0\nSET_LOCAL 1\nPUSH_I64 1\nARRAY_NEW 5\nDUP\nPUSH_I64 0\nGET_LOCAL 0\nARRAY_SET 5\nSET_LOCAL 2\nGET_LOCAL 0\nDYN_PACK 1\nDYN_UNPACK 1\nINTRINSIC 16385\nGET_LOCAL 1\nSTRUCT_GET type=4,field=0\nINTRINSIC 16385\nGET_LOCAL 2\nPUSH_I64 0\nARRAY_GET 5\nINTRINSIC 16385\nGET_LOCAL 0\nMAKE_CLOSURE fn=1,type=6\nCALL_CLOSURE 6\nRET";
let mut v = vm(&[
(body, sig(&[], &[0; 4]), vec![], 3),
("GET_CAPTURE 0\nINTRINSIC 16385\nRET", sig(&[], &[0]), vec![TypeId(1)], 0),
]);
assert_eq!(run(&mut v, 2000).reason, End::EndOfRom);
assert_eq!(
v.operand_stack_top(4),
vectors(42)[..4].iter().rev().map(|x| Value::Int64(x.1)).collect::<Vec<_>>()
);
// generator + Struct + Array + Closure; no Dynamic box for one-slot Random.
assert_eq!(v.heap().allocation_count(), 4);
}
#[test]
fn random_parameter_result_and_typed_null_have_exact_dynamic_type() {
let mut v = vm(&[
("PUSH_I64 42\nINTRINSIC 16384\nCALL 1\nINTRINSIC 16385\nRET", sig(&[], &[0]), vec![], 0),
("GET_LOCAL 0\nRET", sig(&[1], &[1]), vec![], 0),
]);
assert_eq!(run(&mut v, 1000).reason, End::EndOfRom);
assert_eq!(v.operand_stack_top(1), vec![Value::Int64(vectors(42)[0].1)]);
let mut v = vm(&[("GET_LOCAL 0\nDYN_PACK 1\nDYN_UNPACK 1\nRET", sig(&[], &[1]), vec![], 1)]);
assert_eq!(run(&mut v, 1000).reason, End::EndOfRom);
assert_eq!(v.operand_stack_top(1), vec![Value::Null]);
let mut v = vm(&[("GET_LOCAL 0\nDYN_PACK 1\nDYN_UNPACK 7\nRET", sig(&[], &[7]), vec![], 1)]);
let r = run(&mut v, 1000);
assert_eq!(trap(&r).code, TRAP_TYPE);
}
#[test]
fn all_random_attempts_charge_before_validation_and_budget_overshoot() {
for (id, cost) in [(16384, 32), (16385, 8), (16386, 12), (16387, 12)] {
let body = if id == 16384 {
"PUSH_I64 42\nINTRINSIC 16384\nPOP\nRET".into()
} else {
format!(
"PUSH_I64 42\nINTRINSIC 16384\n{}INTRINSIC {id}\nPOP\nRET",
if id == 16387 { "PUSH_I64 5\nPUSH_I64 6\n" } else { "" }
)
};
let mut v = vm(&[(&body, sig(&[], &[]), vec![], 0)]);
for _ in 0..if id == 16384 {
1
} else if id == 16387 {
4
} else {
2
} {
step(&mut v);
}
let before = (v.pc(), v.operand_stack_top(10).to_vec(), v.heap().allocation_count());
let zero = run(&mut v, 0);
assert_eq!((zero.cycles_used, zero.steps_executed), (0, 0));
assert_eq!((v.pc(), v.operand_stack_top(10).to_vec(), v.heap().allocation_count()), before);
let one = run(&mut v, 1);
assert_eq!((one.cycles_used, one.steps_executed), (cost, 1));
assert_eq!(one.reason, End::BudgetExhausted);
}
}
#[test]
fn range_domain_fault_preserves_operands_and_shared_stream() {
for (min, max) in [(1, 1), (2, 1)] {
let code = format!(
"PUSH_I64 42\nINTRINSIC 16384\nDUP\nSET_GLOBAL 0\nPUSH_I64 {min}\nPUSH_I64 {max}\nINTRINSIC 16387\nRET"
);
let mut v = vm(&[(&code, sig(&[], &[0]), vec![], 0)]);
for _ in 0..6 {
step(&mut v);
}
let args = v.operand_stack_top(3).to_vec();
let r = run(&mut v, 1);
assert_eq!(trap(&r).code, TRAP_NUMERIC_DOMAIN);
assert_eq!((r.cycles_used, r.steps_executed), (4, 0));
assert_eq!(v.operand_stack_top(3), args);
}
}
#[test]
fn quota_refusal_new_preserves_seed_and_publishes_no_handle() {
let image =
image(&[("PUSH_I64 42\nINTRINSIC 16384\nPOP\nRET", sig(&[], &[]), vec![], 0)]).unwrap();
for resource in [Q::GuestBytes, Q::HandleSlots, Q::TemporaryBytes] {
let mut v = VirtualMachine::from_image(
image.clone(),
RuntimeLimits::default().lowered(resource, 0).unwrap(),
);
v.prepare_boot_call().unwrap();
step(&mut v);
let r = run(&mut v, 1);
assert_eq!(trap(&r).code, TRAP_RESOURCE_LIMIT);
assert_eq!(trap(&r).resource.as_ref().unwrap().resource, resource);
assert_eq!((r.cycles_used, r.steps_executed), (32, 0));
assert_eq!(v.operand_stack_top(1), vec![Value::Int64(42)]);
assert_eq!(v.heap().allocation_count(), 0);
}
}
#[test]
fn unknown_analysis_checks_null_receiver_at_runtime() {
let mut v = vm(&[(
"GET_LOCAL 0\nSET_GLOBAL 0\nGET_GLOBAL 0\nINTRINSIC 16385\nRET",
sig(&[], &[0]),
vec![],
1,
)]);
for _ in 0..3 {
step(&mut v);
}
let r = run(&mut v, 1);
assert_eq!(trap(&r).code, TRAP_NULL_REFERENCE);
assert_eq!((r.cycles_used, r.steps_executed), (8, 0));
assert_eq!(v.operand_stack_top(1), vec![Value::Null]);
}
#[test]
fn loader_rejects_unknown_unreachable_ids_and_new_random_construction() {
for code in ["RET\nINTRINSIC 16388", "STRUCT_NEW 1\nRET", "PUSH_I32 42\nINTRINSIC 16384\nRET"] {
let err = image(&[(code, sig(&[], &[]), vec![], 0)]).unwrap_err();
let VmInitError::RegistryLoadFailed(failure) = err else { panic!("{err:?}") };
if code.contains("16388") {
assert_eq!(failure.code, prometeu_bytecode::load_limits::LoadCode::InvalidCode);
assert_eq!(failure.reason, prometeu_bytecode::load_limits::LoadReason::NativeId);
}
}
}
#[test]
fn catalog_reference_layout_effects_and_cost_models_are_exact() {
let b = lookup_builtin_type("Random", 1).unwrap();
assert_eq!(b.id, 0x16);
assert!(b.fields.is_empty());
let l = BuiltinId::RANDOM.layout().unwrap();
assert_eq!((l.size, l.alignment, l.slots, l.ownership), (8, 8, 1, Ownership::GuestReference));
assert_eq!(l.default_values(), &[Value::Null]);
for (id, name, cost, slots) in [
(0x4000, "new", 32, 1),
(0x4001, "next", 8, 1),
(0x4002, "nextf", 12, 1),
(0x4003, "range", 4, 3),
] {
let m = lookup_intrinsic_by_id(id).unwrap();
assert_eq!(
(m.owner, m.name, m.version, m.cost_cycles, m.arg_slots(), m.ret_slots()),
("random", name, 1, cost, slots, 1)
);
assert!(m.deterministic && m.mutates_guest_state);
assert_eq!(m.may_allocate, id == 0x4000);
assert!(matches!(m.implementation, IntrinsicImplementation::VmOwned));
assert!(m.implementation.host_callback().is_none());
assert_eq!(
(m.cost_model, m.attempt_cost_cycles, m.max_attempts),
if id == 0x4003 {
(IntrinsicCostModel::RandomRejectionV1, 8, 64)
} else {
(IntrinsicCostModel::Fixed, 0, 0)
}
);
}
assert_eq!(lookup_intrinsic_by_id(0x4003).unwrap().parameter_names, &["rng", "min", "max"]);
for m in prometeu_vm::intrinsic_catalog().filter(|m| m.id < 0x4000) {
assert!(!m.mutates_guest_state);
assert_eq!(
(m.cost_model, m.attempt_cost_cycles, m.max_attempts),
(IntrinsicCostModel::Fixed, 0, 0)
);
}
}
#[test]
fn real_pcg_rejection_consumes_two_words_and_one_instruction() {
let mut v = vm(&[(
"PUSH_I64 42\nINTRINSIC 16384\nSET_LOCAL 0\nGET_LOCAL 0\nINTRINSIC 16385\nSET_LOCAL 1\nGET_LOCAL 0\nPUSH_I64 -9223372036854775808\nPUSH_I64 1\nINTRINSIC 16387\nGET_LOCAL 0\nINTRINSIC 16385\nRET",
sig(&[], &[0, 0]),
vec![],
2,
)]);
for _ in 0..9 {
step(&mut v);
}
let r = run(&mut v, 1);
assert_eq!((r.cycles_used, r.steps_executed, r.reason), (20, 1, End::BudgetExhausted));
assert_eq!(run(&mut v, 1000).reason, End::EndOfRom);
let x = vectors(42);
let expected = (i128::from(i64::MIN) + i128::from(x[2].0 % ((1u64 << 63) + 1))) as i64;
assert_eq!(v.operand_stack_top(2), vec![Value::Int64(x[3].1), Value::Int64(expected)]);
}
#[test]
fn published_emission_example_matches_bits_consumption_and_total_cycles() {
let doc = include_str!("../../../../docs/vm-arch/random-producer-handoff.md");
let code = doc.split("```text\n").nth(1).unwrap().split("```").next().unwrap();
let mut v = vm(&[(code, sig(&[], &[0, 2, 0]), vec![], 1)]);
let r = run(&mut v, 1000);
assert_eq!(r.reason, End::EndOfRom);
assert_eq!(r.cycles_used, 82);
assert_eq!(
v.operand_stack_top(3),
vec![
Value::Int64(-7),
Value::Float(f64::from_bits(0x3fb3_04aa_46c9_8538)),
Value::Int64(0x86b1_da1d_7206_2b68u64 as i64)
]
);
}
@@ -0,0 +1,94 @@
#![allow(dead_code)]
use prometeu_bytecode::{
assemble, load_limits::LoadBudget, registry::*, registry_codec::PbxModule,
};
use prometeu_vm::resource_budget::RuntimeLimits;
use prometeu_vm::{
HostContext, HostReturn, NativeInterface, ValidatedProgramImage, VirtualMachine, VmInitError,
};
use std::sync::Arc;
pub struct Native;
impl NativeInterface for Native {
fn syscall(
&mut self,
_: u32,
_: &[prometeu_bytecode::Value],
_: &mut HostReturn,
_: &mut HostContext,
) -> Result<(), prometeu_hal::vm_fault::VmFault> {
panic!("random must not invoke host syscalls")
}
}
pub fn sig(params: &[u32], results: &[u32]) -> Signature {
Signature {
parameters: params.iter().map(|&t| NamedType { type_id: TypeId(t), name: None }).collect(),
results: results.iter().map(|&t| TypeId(t)).collect(),
}
}
pub fn declarations() -> Vec<TypeDecl> {
let mut t: Vec<_> = [BuiltinId::INT64, BuiltinId::RANDOM, BuiltinId::FLOAT, BuiltinId::DYNAMIC]
.into_iter()
.map(|b| TypeDecl { name: None, kind: TypeKind::Builtin(b) })
.collect();
t.extend([
TypeDecl {
name: None,
kind: TypeKind::Struct(vec![NamedType { type_id: TypeId(1), name: None }]),
},
TypeDecl { name: None, kind: TypeKind::Array(TypeId(1)) },
TypeDecl { name: None, kind: TypeKind::Fn(sig(&[], &[0])) },
TypeDecl { name: None, kind: TypeKind::Struct(vec![]) },
TypeDecl { name: None, kind: TypeKind::Trait(vec![]) },
TypeDecl { name: None, kind: TypeKind::Fn(sig(&[1], &[1])) },
]);
t
}
pub type Body<'a> = (&'a str, Signature, Vec<TypeId>, u32);
pub fn bytes(bodies: &[Body<'_>]) -> Vec<u8> {
let mut code = Vec::new();
let mut functions = Vec::new();
for (text, signature, captures, locals) in bodies {
let body = assemble(text).unwrap();
functions.push(FunctionDecl {
signature: signature.clone(),
captures: captures.clone(),
local_slots: *locals,
max_stack_slots: 64,
code_offset: code.len() as u32,
code_len: body.len() as u32,
..Default::default()
});
code.extend(body);
}
let mut b = LoadBudget::new(Default::default());
let registry = Registry::resolve(
RegistryDeclarations { types: declarations(), functions, implementations: vec![] },
code.len(),
&mut b,
)
.unwrap();
PbxModule {
registry: &registry,
constants: &[],
code: &code,
debug: None,
exports: &[],
syscalls: &[],
}
.serialize(&mut b)
.unwrap()
}
pub fn image(bodies: &[Body<'_>]) -> Result<Arc<ValidatedProgramImage>, VmInitError> {
ValidatedProgramImage::load(&bytes(bodies), &mut LoadBudget::new(Default::default()), 0)
}
pub fn vm(bodies: &[Body<'_>]) -> VirtualMachine {
let mut v = VirtualMachine::from_image(image(bodies).unwrap(), RuntimeLimits::default());
v.prepare_boot_call().unwrap();
v
}
pub fn run(v: &mut VirtualMachine, budget: u64) -> prometeu_vm::BudgetReport {
v.run_budget(budget, &mut Native, &mut HostContext::new(None)).unwrap()
}
pub fn step(v: &mut VirtualMachine) {
v.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
@@ -141,7 +141,9 @@ fn query_all(platform: &mut TestPlatform) -> Vec<Value> {
(0x2100..=0x2135)
.map(|id| {
let meta = lookup_intrinsic_by_id(id).unwrap();
let result = (meta.implementation)(&[], &mut ctx).unwrap();
let result =
(meta.implementation.host_callback().expect("host intrinsic"))(&[], &mut ctx)
.unwrap();
meta.validate_result_values(&result).unwrap();
result.into_iter().next().unwrap()
})
@@ -211,11 +213,14 @@ fn every_known_query_faults_when_unavailable_and_rejects_arguments() {
let meta = lookup_intrinsic_by_id(id).unwrap();
let mut ctx = HostContext::new(None);
assert_eq!(
(meta.implementation)(&[], &mut ctx),
(meta.implementation.host_callback().expect("host intrinsic"))(&[], &mut ctx),
Err(IntrinsicExecutionError::HardwareUnavailable)
);
assert_eq!(
(meta.implementation)(&[Value::Int64(0)], &mut ctx),
(meta.implementation.host_callback().expect("host intrinsic"))(
&[Value::Int64(0)],
&mut ctx
),
Err(IntrinsicExecutionError::ArityMismatch { expected: 0, got: 1 })
);
let mut vm = query_vm(assemble(&format!("INTRINSIC {id}\nHALT")).unwrap());