feat(pbs): add explicit guest lifecycle hooks

This commit is contained in:
2026-10-28 09:12:48 +00:00
parent eb7d6a2398
commit 9504f4694a
41 changed files with 1209 additions and 24 deletions
+38
View File
@@ -60,6 +60,44 @@ is deliberately load-only because its entry requires arguments. Native binding
uses SYSTEM for the positive case and NONE for missing-capability rejection;
all other cases use NONE. Resource tests explicitly lower default limits.
## PBS controlled guest lifecycle qualification
Generate the source corpus and installed example, then run both runtime profiles:
```sh
./gradlew :prometeu-architecture-tests:test --tests '*PbsGuestLifecycleTest' :prometeu-app:installedKnowledgeTest
python3 tools/pbx-conformance/run.py --runtime ../runtime --lifecycle-only
python3 tools/pbx-conformance/run.py --runtime ../runtime --lifecycle-only --release
```
`PbsGuestLifecycleTest` emits ordinary/optimized production PBX for both hooks,
each independently and neither, ordinary direct calls, fatal traps, total fuel
exhaustion and successful calls spanning slices. Arbitrary function names and
unmarked functions named BeforePause/BeforeResume distinguish role metadata from
name conventions. An actual workspace import/reexport case selects one original
declaration without requiring colocation with Frame. A conflicting declaration
must fail project analysis. Synthetic binary fixtures explicitly cover direct
and transitive FRAME_SYNC rejection; they do not add PBS sync syntax.
`lifecycle.rs` loads these images with the production VM and runs the production
Firmware/SystemOS foreground path using the standard TestPlatform hardware.
Home/resume asserts exact ordered guest effects, unchanged continuation PC and
game-session ticks/frames during hooks, preserved heap/global state and a single
Init execution. Direct suspension and Shell foreground handoff must not add a
reaction tick. A partial frame retains its existing operand and call frame while
controlled hooks run. Ordinary direct calls do not acquire a controlled context.
The independent 1,500,000-cycle fuel budget survives slices and debugger stops;
single stepping uses the same accounting. Fatal trap/fuel/sync cases cannot run
subsequent gameplay or publish a logical frame. After a crash, counters are read
from the retained game session rather than the newly active crash UI. Probe
functions run only as terminal observations after continuation/frame assertions.
The runner adds production firmware/driver dependencies to its temporary Cargo
project. Sources, manifests, lockfiles and build outputs in the runtime checkout
remain untouched. This is local lifecycle conformance; installed runtime/game
qualification and MemcardBoot/persistence remain separate scopes.
Negative fixtures mutate Java-produced bytes independently of the writer to
exercise malformed input that the writer correctly refuses to construct.
Initialization JSON comes from `prometeu_system::CrashReport`, and is checked
+219
View File
@@ -0,0 +1,219 @@
//! Studio-produced PBS images through the production VM and foreground firmware.
use prometeu_bytecode::{Value, registry::LifecycleRole};
use prometeu_drivers::TestPlatform;
use prometeu_firmware::firmware::{Firmware, FirmwareState};
use prometeu_hal::{InputSignals, app_mode::AppMode, cartridge::{Cartridge, AssetsPayloadSource}};
use prometeu_system::task::{TaskId, TaskState};
use prometeu_vm::{HostContext, LogicalFrameEndingReason as Reason, ValidatedProgramImage, VirtualMachine};
use std::path::Path;
fn bytes(root: &Path, name: &str) -> Vec<u8> {
std::fs::read(root.join(format!("{name}.pbx"))).unwrap_or_else(|e| panic!("{name}: {e}"))
}
fn load(root: &Path, name: &str) -> VirtualMachine {
let image = ValidatedProgramImage::load(&bytes(root, name), &mut super::LoadBudget::new(Default::default()), super::caps::NONE).unwrap();
for role in [LifecycleRole::BeforePause, LifecycleRole::BeforeResume] {
if let Some(id) = image.registry().lifecycle_hook(role) { assert_ne!(id.0, 0); }
}
let mut vm = VirtualMachine::from_image(image, Default::default());
vm.prepare_boot_call().unwrap();
let report = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert!(matches!(report.reason, Reason::EndOfRom | Reason::Halted), "{name}: {report:?}");
vm
}
fn query(root: &Path, name: &str, vm: &mut VirtualMachine) -> i32 {
let id = std::fs::read_to_string(root.join(format!("{name}.probe"))).unwrap();
vm.prepare_call(id.trim()).unwrap();
let report = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert!(matches!(report.reason, Reason::EndOfRom | Reason::Halted), "{name}: {report:?}");
match vm.operand_stack_top(1)[0] { Value::Int32(value) => value, ref other => panic!("{other:?}") }
}
fn finish_hook(vm: &mut VirtualMachine, expected: Reason) -> usize {
let mut previous = vm.lifecycle_remaining_cycles().unwrap();
let mut slices = 0;
loop {
slices += 1; assert!(slices < 16);
let report = vm.run_budget(u64::MAX, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
// Includes the specified whole-instruction overshoot; this corpus uses scalar instructions.
assert!(report.cycles_used <= VirtualMachine::LIFECYCLE_SLICE + 100);
if report.reason != Reason::BudgetExhausted {
assert_eq!(report.reason, expected); break;
}
let remaining = vm.lifecycle_remaining_cycles().unwrap();
assert!(remaining < previous);
assert_eq!(previous.saturating_sub(report.cycles_used), remaining);
previous = remaining;
}
slices
}
fn snapshot(fw: &mut Firmware, task: TaskId) -> (usize, u64, u64) {
// The active foreground facade switches to the crash UI after failure.
// Observe the retained game session so a foreground change cannot reset the oracle.
let sessions = fw.os.sessions();
let session = sessions.vm_session_for_task(task).unwrap();
(session.vm.pc(), session.runtime.tick_index,
session.runtime.atomic_telemetry.completed_logical_frames.load(std::sync::atomic::Ordering::Relaxed) as u64)
}
fn firmware(root: &Path, name: &str) -> (Firmware, TestPlatform, TaskId) {
let mut fw = Firmware::new(None); let mut platform = TestPlatform::new();
fw.load_cartridge(Cartridge {
app_id: 86, title: "Studio PBS lifecycle".into(), app_version: "1.0.0".into(),
app_mode: AppMode::Game, capabilities: super::caps::NONE, memcard_slots: None,
program: bytes(root, name), assets: AssetsPayloadSource::empty(), asset_table: vec![], preload: vec![],
});
fw.tick(&InputSignals::default(), &mut platform);
let task = fw.os.lifecycle().resident_game_task().unwrap();
fw.tick(&InputSignals::default(), &mut platform);
assert!(fw.os.vm().last_crash_report().is_none());
(fw, platform, task)
}
fn foreground_case(root: &Path, name: &str, expected: i32, resume: bool) {
let (mut fw, mut platform, task) = firmware(root, name);
let signals = InputSignals::default();
fw.request_home_from_host();
fw.tick(&signals, &mut platform); // Existing Home handoff, including its gameplay reaction.
let suspended = snapshot(&mut fw, task);
fw.tick(&signals, &mut platform); // Hook only, or already-suspended case without a hook.
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended), "{name}");
assert_eq!(snapshot(&mut fw, task), suspended, "pause changed gameplay state: {name}");
assert!(fw.resume_resident_game_from_home());
if resume {
fw.tick(&signals, &mut platform); // BeforeResume only.
assert_eq!(snapshot(&mut fw, task), suspended, "resume changed gameplay state: {name}");
}
fw.tick(&signals, &mut platform); // First eligible gameplay frame validates guest stage/init/heap.
assert!(fw.os.vm().last_crash_report().is_none(), "{name}");
assert_eq!(snapshot(&mut fw, task).1, suspended.1 + 1);
let actual = {
let mut sessions = fw.os.sessions();
let session = sessions.vm_session_for_task_mut(task).unwrap();
// Terminal observation only, after all continuation/frame assertions; no later host tick.
query(root, name, &mut session.vm)
};
assert_eq!(actual, expected, "ordered guest effects/init/heap: {name}");
println!("FIRMWARE HOME/RESUME PASS {name}: pc={}, gameplayTicks={}, frames={}, guest={actual}", suspended.0, suspended.1, suspended.2);
}
fn other_foreground_paths(root: &Path, name: &str) {
for shell in [false, true] {
let (mut fw, mut platform, task) = firmware(root, name);
let before = snapshot(&mut fw, task);
if shell { fw.os.sessions().try_create_native_shell_task(99, "Tools").unwrap(); }
else { fw.os.lifecycle().suspend_task(task).unwrap(); }
fw.tick(&InputSignals::default(), &mut platform);
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended));
assert_eq!(snapshot(&mut fw, task), before);
println!("DIRECT/SHELL SUSPEND PASS {name}: shell={shell}, no reaction tick");
}
let mut vm = load(root, name);
vm.prepare_boot_call().unwrap();
let partial = vm.run_budget(1, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert_eq!(partial.reason, Reason::BudgetExhausted);
assert!(!vm.call_stack_is_empty());
let pc = vm.pc(); let stack = vm.operand_stack_top(1000).to_vec();
assert!(!stack.is_empty(), "suspended wrapper must retain an operand");
for role in [LifecycleRole::BeforePause, LifecycleRole::BeforeResume] {
assert!(vm.begin_lifecycle(role).unwrap());
finish_hook(&mut vm, Reason::LifecycleComplete);
assert_eq!(vm.pc(), pc); assert_eq!(vm.operand_stack_top(1000).to_vec(), stack);
assert!(!vm.call_stack_is_empty());
}
let resumed = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert!(matches!(resumed.reason, Reason::EndOfRom | Reason::Halted));
assert_eq!(query(root, name, &mut vm), 230112);
println!("SUSPENDED STACK/CONTINUATION PASS {name}: retained operand, frame and heap");
}
pub fn verify(root: &Path) {
for suffix in ["", "-optimized"] {
for (case, expected, resume) in [("both", 230112, true), ("pause", 20109, false), ("resume", 30110, true), ("none", 107, false)] {
let name = format!("pbs-lifecycle-{case}{suffix}");
let mut vm = load(root, &name);
for (role, present) in [(LifecycleRole::BeforePause, case == "both" || case == "pause"), (LifecycleRole::BeforeResume, resume)] {
let pc = vm.pc(); let stack = vm.operand_stack_top(1000).to_vec();
assert_eq!(vm.begin_lifecycle(role).unwrap(), present);
if present {
assert!(vm.begin_lifecycle(role).is_err(), "controlled calls cannot reenter");
finish_hook(&mut vm, Reason::LifecycleComplete);
}
assert_eq!(vm.pc(), pc); assert_eq!(vm.operand_stack_top(1000).to_vec(), stack);
}
vm.prepare_boot_call().unwrap();
let next = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert!(matches!(next.reason, Reason::Halted | Reason::EndOfRom));
assert_eq!(query(root, &name, &mut vm), expected);
foreground_case(root, &name, expected, resume);
}
other_foreground_paths(root, &format!("pbs-lifecycle-both{suffix}"));
let name = format!("pbs-lifecycle-direct{suffix}");
let mut vm = load(root, &name);
assert!(!vm.lifecycle_active()); assert_eq!(query(root, &name, &mut vm), 230112);
println!("ORDINARY CALL PASS {name}: no controlled invocation");
let name = format!("pbs-lifecycle-slices{suffix}");
let mut vm = load(root, &name);
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
let hook_pc = vm.pc(); vm.insert_breakpoint(hook_pc);
let remaining = vm.lifecycle_remaining_cycles();
let stopped = vm.run_budget(250_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert_eq!(stopped.reason, Reason::Breakpoint); assert_eq!(stopped.cycles_used, 0);
assert_eq!(vm.lifecycle_remaining_cycles(), remaining);
vm.remove_breakpoint(hook_pc);
vm.step(&mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert!(vm.lifecycle_remaining_cycles().unwrap() < remaining.unwrap());
assert!(finish_hook(&mut vm, Reason::LifecycleComplete) > 1);
println!("SLICES + DEBUGGER PASS {name}: one retained total fuel budget");
for case in ["trap", "fuel"] {
let name = format!("pbs-lifecycle-{case}{suffix}");
let mut vm = load(root, &name);
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
let mut slices = 0;
let terminal = loop {
slices += 1; assert!(slices < 16);
let report = vm.run_budget(u64::MAX, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
if report.reason != Reason::BudgetExhausted { break report.reason; }
};
if case == "trap" { assert!(matches!(terminal, Reason::Trap(_))); }
else { assert!(matches!(&terminal, Reason::Panic(text) if text.contains("lifecycle total cycle budget exhausted"))); assert!(slices > 1); }
let blocked = vm.run_budget(1000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert_eq!(blocked.reason, terminal); assert_eq!(blocked.steps_executed, 0);
assert!(vm.prepare_boot_call().is_err());
let (mut fw, mut platform, task) = firmware(root, &name);
fw.request_home_from_host(); fw.tick(&InputSignals::default(), &mut platform);
let before = snapshot(&mut fw, task);
for _ in 0..16 {
fw.tick(&InputSignals::default(), &mut platform);
if matches!(fw.state, FirmwareState::AppCrashes(_)) { break; }
}
assert!(matches!(fw.state, FirmwareState::AppCrashes(_)), "{name}");
assert_eq!(snapshot(&mut fw, task).1, before.1);
assert_eq!(snapshot(&mut fw, task).2, before.2);
println!("FATAL + GAMEPLAY BLOCK PASS {name}: {terminal:?}, slices={slices}");
}
}
// These binaries are explicitly synthetic; no PBS sync surface is claimed.
for case in ["direct", "transitive"] {
let name = format!("synthetic-lifecycle-sync-{case}");
let mut vm = load(root, &name);
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
let report = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert!(matches!(report.reason, Reason::Trap(_)), "{report:?}");
let again = vm.run_budget(1000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
assert_eq!(again.steps_executed, 0); assert_eq!(again.reason, report.reason);
let (mut fw, mut platform, task) = firmware(root, &name);
fw.request_home_from_host(); fw.tick(&InputSignals::default(), &mut platform);
let before = snapshot(&mut fw, task);
fw.tick(&InputSignals::default(), &mut platform);
assert!(matches!(fw.state, FirmwareState::AppCrashes(_)));
assert_eq!(snapshot(&mut fw, task).1, before.1); assert_eq!(snapshot(&mut fw, task).2, before.2);
println!("SYNTHETIC SYNC REJECTION PASS {case}: no gameplay/frame publication");
}
let name = "pbs-lifecycle-imports";
let mut vm = load(root, name);
assert!(vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap());
finish_hook(&mut vm, Reason::LifecycleComplete);
assert!(!vm.has_lifecycle_hook(LifecycleRole::BeforeResume));
println!("PRODUCTION PIPELINE IMPORTS PASS: alias/reexport selected one original hook");
}
+3
View File
@@ -1,5 +1,6 @@
use prometeu_bytecode::Value;
mod stack_queue;
mod lifecycle;
use prometeu_bytecode::load_limits::{LoadBudget, LoadLimits};
use prometeu_hal::syscalls::caps;
use prometeu_vm::{
@@ -42,6 +43,7 @@ fn main() {
for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes,Q::StringBytes,Q::StringAllocations,Q::IndividualStringBytes,Q::CallDepth] {
println!("DEFAULT VM LIMIT {resource:?}={}",limits.get(resource));
}
if std::env::args().any(|arg| arg == "--lifecycle-only") { lifecycle::verify(&root); return; }
if std::env::args().any(|arg| arg == "--stack-queue-only") { stack_queue::verify(&root); return; }
if std::env::args().any(|arg| arg == "--map-only") { verify_pbs_map_fixtures(&root); return; }
if std::env::args().any(|arg| arg == "--set-only") { verify_pbs_set_fixtures(&root); return; }
@@ -66,6 +68,7 @@ fn main() {
verify_pbs_set_fixtures(&root);
verify_pbs_map_fixtures(&root);
stack_queue::verify(&root);
lifecycle::verify(&root);
verify_pbs_resource_refusals(&root);
verify_pbs_closure_frames(&root);
for name in [
+7 -2
View File
@@ -11,6 +11,7 @@ parser = argparse.ArgumentParser()
parser.add_argument("--runtime", type=pathlib.Path, default=pathlib.Path("../runtime"))
parser.add_argument("--fixtures", type=pathlib.Path, default=pathlib.Path("prometeu-compiler/prometeu-build-pipeline/build/registry-conformance"))
parser.add_argument("--online", action="store_true", help="Allow Cargo to fetch uncached dependencies")
parser.add_argument("--lifecycle-only", action="store_true", help="Run PBS guest lifecycle VM and production firmware corpus")
parser.add_argument("--release", action="store_true", help="Execute an optimized runtime harness")
parser.add_argument("--set-only", action="store_true", help="Run mandatory PBS Set corpus")
parser.add_argument("--map-only", action="store_true", help="Run mandatory PBS Map/Keyval corpus")
@@ -36,10 +37,13 @@ if provider_hash_vectors.read_bytes() != consumer_hash_vectors.read_bytes():
print(subprocess.check_output(["rustc", "-Vv"], text=True).strip(), flush=True)
for source in [pathlib.Path(__file__), pathlib.Path(__file__).with_name("main.rs"),
pathlib.Path(__file__).with_name("stack_queue.rs"),
pathlib.Path(__file__).with_name("lifecycle.rs"),
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java"),
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java"),
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java"),
pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/random/main.pbs")]:
print("sha256", source, hashlib.sha256(source.read_bytes()).hexdigest(), flush=True)
print("studio", subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), flush=True)
print("runtime", subprocess.check_output(["git", "-C", str(runtime), "rev-parse", "HEAD"], text=True).strip(), flush=True)
print("runtime working tree", subprocess.check_output(["git","-C",str(runtime),"status","--short"],text=True).strip() or "clean",flush=True)
for source in [pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java"),
@@ -54,7 +58,7 @@ for relative in ["Cargo.lock", "docs/vm-arch/INTRINSICS.csv", "docs/vm-arch/BUIL
with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory:
root = pathlib.Path(directory)
manifest = '[package]\nname="studio-pbx-conformance"\nversion="0.1.0"\nedition="2024"\n[dependencies]\n'
for crate in ["prometeu-bytecode", "prometeu-hal", "prometeu-vm", "prometeu-system"]:
for crate in ["prometeu-bytecode", "prometeu-hal", "prometeu-vm", "prometeu-system", "prometeu-firmware", "prometeu-drivers"]:
features = ',features=["resource-diagnostics"]' if crate == "prometeu-vm" else ''
manifest += f'{crate}={{path={json.dumps(str(runtime / "crates/console" / crate))}{features}}}\n'
manifest += 'serde_json="1.0.149"\njsonschema={version="0.33",default-features=false}\n'
@@ -63,4 +67,5 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory:
(root / "src").mkdir()
(root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text())
(root / "src/stack_queue.rs").write_text(pathlib.Path(__file__).with_name("stack_queue.rs").read_text())
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--stack-queue-only"] if args.stack_queue_only else []), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True)
(root / "src/lifecycle.rs").write_text(pathlib.Path(__file__).with_name("lifecycle.rs").read_text())
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--lifecycle-only"] if args.lifecycle_only else []), *(["--stack-queue-only"] if args.stack_queue_only else []), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True)