Files
prometeu-runtime/crates/console/prometeu-vm/src/program_image/tests.rs
T
bquarkz 9318cf7cd3
Intrepid/Prometeu/Runtime/pipeline/pr-master There was a failure building this commit
feat(vm): add deterministic gameplay math and domain coverage gates
2026-10-09 10:25:11 +01:00

289 lines
11 KiB
Rust

use super::*;
use prometeu_bytecode::load_limits::LoadLimits;
use prometeu_bytecode::registry::{
BuiltinId, FunctionDecl, RegistryDeclarations, TypeDecl, TypeKind,
};
use prometeu_bytecode::registry_codec::PbxModule;
use prometeu_bytecode::{SourceSpan, SyscallDecl};
use prometeu_hal::syscalls::{Syscall, caps, meta_for};
fn budget() -> LoadBudget {
LoadBudget::new(LoadLimits::default())
}
fn fixture(
code: &[u8],
max: u32,
constants: &[K],
debug: Option<&DebugInfo>,
syscalls: &[SyscallDecl],
) -> Vec<u8> {
let registry = Registry::resolve(
RegistryDeclarations {
types: vec![TypeDecl {
name: Some("boolean".into()),
kind: TypeKind::Builtin(BuiltinId::BOOL),
}],
functions: vec![FunctionDecl {
name: Some("boot".into()),
code_len: code.len() as u32,
max_stack_slots: max,
..Default::default()
}],
..Default::default()
},
code.len(),
&mut budget(),
)
.unwrap();
PbxModule { registry: &registry, code, constants, debug, exports: &[], syscalls }
.serialize(&mut budget())
.unwrap()
}
fn has_cart() -> SyscallDecl {
let m = meta_for(Syscall::SystemHasCart);
SyscallDecl {
module: m.module.into(),
name: m.name.into(),
version: m.version,
arg_slots: m.arg_slots as u16,
ret_slots: m.ret_slots,
}
}
fn hostcall_code() -> Vec<u8> {
let mut code = (Op::Hostcall as u16).to_le_bytes().to_vec();
code.extend_from_slice(&0u32.to_le_bytes());
code.extend_from_slice(&(Op::Pop as u16).to_le_bytes());
code.extend_from_slice(&(Op::Halt as u16).to_le_bytes());
code
}
#[test]
fn publication_shares_owners_and_preserves_payload_bits_and_names() {
let debug = DebugInfo {
pc_to_span: vec![(0, SourceSpan { file_id: 7, start: 2, end: 3 })],
function_names: vec![(0, "debug boot".into())],
};
let constants = [
K::Null,
K::String("é猫".into()),
K::String(String::new()),
K::Float64(f64::from_bits(0x0008000000000042)),
K::Float64(-0.0),
];
let bytes = fixture(&[1, 0], 0, &constants, Some(&debug), &[]);
let mut b = budget();
b.charge(Q::TemporaryBytes, 7).unwrap();
let image = ValidatedProgramImage::load(&bytes, &mut b, caps::NONE).unwrap();
assert_eq!(b.used(Q::TemporaryBytes), 7);
assert!(image.payload_bytes() > 0 && image.registry_bytes() > 0);
assert_eq!(image.registry().declarations().functions[0].name.as_deref(), Some("boot"));
assert_eq!(image.execution.functions[0].max_stack_slots, 0);
assert_eq!(image.constant_content(), (5, 2));
assert!(image.lease_constant(0).is_none());
let Value::Float(nan) = image.constants()[3] else { panic!() };
let Value::Float(zero) = image.constants()[4] else { panic!() };
assert_eq!(nan.to_bits(), 0x0008000000000042);
assert_eq!(zero.to_bits(), (-0.0f64).to_bits());
let projection = image.execution.clone();
assert!(Arc::ptr_eq(&projection.rom, &image.execution.rom));
assert!(Arc::ptr_eq(&projection.constant_pool, &image.execution.constant_pool));
assert!(Arc::ptr_eq(
projection.debug_info.as_ref().unwrap(),
image.execution.debug_info.as_ref().unwrap()
));
assert_eq!(image.debug().unwrap().function_names[0].1, "debug boot");
let lease = image.lease_constant(1).unwrap();
let Value::String(text) = &image.constants()[1] else { panic!() };
assert!(Arc::ptr_eq(text, lease.content()));
drop(bytes);
drop(projection);
drop(image);
assert_eq!(lease.content().as_ref(), "é猫");
assert_eq!(lease.retained_content(), (5, 1));
}
#[test]
fn binding_precedes_publication_and_does_not_mutate_input() {
let code = hostcall_code();
let bytes = fixture(&code, 1, &[], None, &[has_cart()]);
let original = bytes.clone();
let image = ValidatedProgramImage::load(&bytes, &mut budget(), caps::SYSTEM).unwrap();
assert_eq!(bytes, original);
assert_eq!(&image.code()[..2], &(Op::Syscall as u16).to_le_bytes());
assert_eq!(&image.code()[2..6], &(Syscall::SystemHasCart as u32).to_le_bytes());
assert_eq!(image.capabilities(), caps::SYSTEM);
}
#[test]
fn native_binding_errors_keep_identity_and_roll_back_image_ownership() {
let code = hostcall_code();
let mut unknown = has_cart();
unknown.name = "missing".into();
let mut abi = has_cart();
abi.ret_slots = 2;
for (decl, caps, expected) in
[(unknown, caps::SYSTEM, 0), (has_cart(), caps::NONE, 1), (abi, caps::SYSTEM, 2)]
{
let bytes = fixture(&code, 1, &[], None, &[decl]);
let mut b = budget();
b.charge(Q::TemporaryBytes, 7).unwrap();
b.charge(Q::RegistryBytes, 3).unwrap();
let error = ValidatedProgramImage::load(&bytes, &mut b, caps).unwrap_err();
let VmInitError::LoaderPatchFailed(LoaderPatchError::ResolveFailed(error)) = error else {
panic!("{error:?}")
};
assert!(matches!(
(expected, error),
(0, DeclaredLoadError::UnknownSyscall { .. })
| (1, DeclaredLoadError::MissingCapability { .. })
| (2, DeclaredLoadError::AbiMismatch { .. })
));
assert_eq!(b.used(Q::TemporaryBytes), 7);
assert_eq!(b.used(Q::RegistryBytes), 3);
assert_eq!(b.used(Q::Functions), 0);
assert_eq!(b.used(Q::ConstantEntries), 0);
assert!(b.used(Q::Work) > 0);
}
}
#[test]
fn raw_or_unbound_calls_cannot_reach_an_image() {
let mut raw = hostcall_code();
raw[..2].copy_from_slice(&(Op::Syscall as u16).to_le_bytes());
let mut out_of_bounds = hostcall_code();
out_of_bounds[2..6].copy_from_slice(&1u32.to_le_bytes());
for (code, decls, kind) in [
(&raw[..], vec![], 0),
(&out_of_bounds[..], vec![has_cart()], 1),
(&[1, 0][..], vec![has_cart()], 2),
] {
let bytes = fixture(code, 1, &[], None, &decls);
let error = ValidatedProgramImage::load(&bytes, &mut budget(), caps::SYSTEM).unwrap_err();
assert!(matches!(
(kind, error),
(
0,
VmInitError::LoaderPatchFailed(
LoaderPatchError::RawSyscallInPreloadArtifact { .. }
)
) | (
1,
VmInitError::LoaderPatchFailed(LoaderPatchError::HostcallIndexOutOfBounds { .. })
) | (2, VmInitError::LoaderPatchFailed(LoaderPatchError::UnusedSyscallDecl { .. }))
));
}
}
#[test]
fn verification_rejects_unreachable_bad_instructions_and_underflow() {
let pop = (Op::Pop as u16).to_le_bytes();
for code in [&pop[..], &[1, 0, 0xff, 0xff][..]] {
let bytes = fixture(code, 0, &[], None, &[]);
let mut b = budget();
let VmInitError::RegistryLoadFailed(error) =
ValidatedProgramImage::load(&bytes, &mut b, caps::NONE).unwrap_err()
else {
panic!()
};
assert_eq!(error.function, Some(0));
assert_eq!(b.used(Q::RegistryBytes), 0);
assert_eq!(b.used(Q::TemporaryBytes), 0);
}
}
#[test]
fn late_work_refusal_releases_all_new_owners() {
let bytes = fixture(&[1, 0], 0, &[K::String("abc".into())], None, &[]);
let mut full = budget();
ValidatedProgramImage::load(&bytes, &mut full, caps::NONE).unwrap();
let mut b = LoadBudget::new(LoadLimits { work: full.used(Q::Work) - 1, ..Default::default() });
b.charge(Q::TemporaryBytes, 7).unwrap();
b.charge(Q::RegistryBytes, 3).unwrap();
let VmInitError::RegistryLoadFailed(error) =
ValidatedProgramImage::load(&bytes, &mut b, caps::NONE).unwrap_err()
else {
panic!()
};
assert_eq!(error.resource, Some(Q::Work));
assert_eq!(b.used(Q::TemporaryBytes), 7);
assert_eq!(b.used(Q::RegistryBytes), 3);
assert_eq!(b.used(Q::ConstantStringBytes), 0);
assert_eq!(b.used(Q::PbxBytes), 0);
}
#[test]
fn constant_strings_share_image_domain_across_sessions_and_native_snapshots() {
use crate::resource_budget::{RuntimeLimits, RuntimeResource};
use crate::{HostContext, HostReturn, NativeInterface, VirtualMachine};
struct Native;
impl NativeInterface for Native {
fn syscall(
&mut self,
_id: u32,
_args: &[Value],
_ret: &mut HostReturn,
_ctx: &mut HostContext,
) -> Result<(), prometeu_hal::vm_fault::VmFault> {
Ok(())
}
}
let mut code = (Op::PushConst as u16).to_le_bytes().to_vec();
code.extend_from_slice(&0u32.to_le_bytes());
code.extend_from_slice(&(Op::Halt as u16).to_le_bytes());
let bytes = fixture(&code, 1, &[K::String("shared".into())], None, &[]);
let image = ValidatedProgramImage::load(&bytes, &mut budget(), caps::NONE).unwrap();
let lease = image.lease_constant(0).unwrap();
let limits = RuntimeLimits::default().lowered(RuntimeResource::StringBytes, 0).unwrap();
let mut first = VirtualMachine::from_image(image.clone(), limits.clone());
let mut second = VirtualMachine::from_image(image.clone(), limits);
first.prepare_boot_call().unwrap();
second.prepare_boot_call().unwrap();
for vm in [&mut first, &mut second] {
vm.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
let snapshot = first.operand_stack_top(1);
let other = second.operand_stack_top(1);
let (Value::String(left), Value::String(right)) = (&snapshot[0], &other[0]) else { panic!() };
assert!(Arc::ptr_eq(left, right));
assert_eq!(snapshot.retained_domains(), 1);
drop(image);
drop(first);
drop(second);
drop(other);
assert_eq!(lease.retained_content(), (6, 1));
drop(lease);
let Value::String(text) = &snapshot[0] else { panic!() };
assert_eq!(text.as_ref(), "shared");
}
#[test]
#[ignore = "explicit release measurement; not a timing assertion"]
fn sealed_image_load_probe() {
use std::time::Instant;
let constants: Vec<_> =
(0..512).map(|index| K::String(format!("{index:04}:{}", "x".repeat(59)))).collect();
let bytes = fixture(&[1, 0], 0, &constants, None, &[]);
let mut budget = budget();
let start = Instant::now();
let image = ValidatedProgramImage::load(&bytes, &mut budget, caps::NONE).unwrap();
let elapsed = start.elapsed().as_nanos();
assert_eq!(image.constant_content(), (32768, 512));
assert_eq!(budget.used(Q::TemporaryBytes), 0);
println!(
"image arch={} pbx={} registry={} payload={} work={} peak_scratch={} retained_scratch={} strings={} allocations={} load_ns={}",
std::env::consts::ARCH,
bytes.len(),
image.registry_bytes(),
image.payload_bytes(),
budget.used(Q::Work),
budget.peak_usage(Q::TemporaryBytes),
budget.used(Q::TemporaryBytes),
image.constant_content().0,
image.constant_content().1,
elapsed
);
}