feat(runtime): add optional pause and resume lifecycle hooks
Intrepid/Prometeu/Runtime/pipeline/pr-master Build started...

This commit is contained in:
2026-10-13 12:18:18 +01:00
parent 23dc6fc66d
commit 0af8b2b1fe
39 changed files with 1381 additions and 70 deletions
@@ -76,13 +76,15 @@ call and capture access validate whole groups and reserve capacity before consum
or publication. Refusal preserves operands/owners and publishes no partial object
or frame; provisional reservations refund and attempted cycles remain. No quota
rescue GC. Use existing distinct NullReference/InvalidHandle/Type/Resource traps.
Fn can invoke syscalls, mutate and fault: no purity flag, fault isolation, separate
budget, guest unwind or rollback of earlier body effects.
Ordinary Fn calls can invoke syscalls, mutate and fault: no purity flag, fault
isolation, separate budget, guest unwind or rollback of earlier body effects.
SystemOS lifecycle invocations use the separate budget described below.
## 5 Context, GC and Host
VM owns one PC, operand/call stacks and globals directly. FRAME_SYNC retains
frames/locals/environments and resumes next PC in any body. Budget exhaustion
frames/locals/environments and resumes next PC in normal gameplay bodies. It is
forbidden during lifecycle hooks and their callees. Budget exhaustion
retains the same logical frame. Last-root RET completes entry, rooting results
before threshold GC. Recurring host entry remains FunctionId 0 with init once.
@@ -92,8 +94,9 @@ and legally retained native/host roots. Trace whole capture groups and shared
cells; unreachable cycles collect. Results remain roots until consumed/replaced,
reset/unload. No GC at ordinary callee RET or allocation/quota rescue.
HeapRef copies/inspection snapshots establish no guest roots or cross-session
imports. No native registration/delivery/reentry API is created here. Guest
callbacks are ordinary Fn calls in the main execution context.
imports. Ordinary guest callbacks are Fn calls in the main execution context.
Optional SystemOS lifecycle entry uses Registry roles and the controlled boundary
described below; it does not introduce arbitrary native reentry.
See [memory](03-memory-stack-heap-and-allocation.md),
[Registry/PBX](02c-program-registry-and-pbx-v1.md) and
@@ -102,3 +105,14 @@ See [memory](03-memory-stack-heap-and-allocation.md),
## Random core integration
[Random references](02e-vm-owned-random-core.md) are valid capture, parameter and result groups. Existing roots retain the generator; copying captures aliases its state.
## System-owned lifecycle entry
Optional zero-argument, zero-result, capture-free lifecycle targets are bound by
[Registry roles](02c-program-registry-and-pbx-v1.md#optional-lifecycle-roles).
They are ordinary functions called through a controlled SystemOS boundary, not
closure values or replacement boot entries. The boundary retains the existing
stacks and roots, appends its frame, and returns to SystemOS immediately on outer
completion. See [lifecycle execution](09a-coroutines-and-cooperative-scheduling.md#controlled-lifecycle-calls)
for independent fuel, debugger behavior and failure semantics. Frontend Init and
Frame assembly is unchanged.
@@ -81,11 +81,34 @@ Encoding primitives: list=`count:u32` followed by records; optional name=`presen
| Trait payload | ordered method list; each method has optional name, explicit-parameter list, result list; concrete receiver is not repeated here |
| Fn payload | ordered parameter list, result list; names do not define identity |
| Captures section | function_count:u32, then each FunctionId in order: capture_count:u32 and TypeIds:u32; counts match functions, empty lists explicit |
| Function | optional name, parameter list, result list, code_offset:u32, code_len:u32, local_slots:u32, max_stack_slots:u32 |
| Function | lifecycle_role:u8, optional name, parameter list, result list, code_offset:u32, code_len:u32, local_slots:u32, max_stack_slots:u32 |
| Implementation | owner_type_id:u32, trait_type_id:u32, method_count:u32, FunctionIds:u32 in trait-method order; count must match |
Code offsets are relative to Code. Local and temporary counts widen from current u16 without truncation. `max_stack_slots` counts temporaries only; zero means zero, never infer. No guest-controlled builtin layouts or raw Rust structures/pointers are serialized. Remove old/external compatibility; regeneration is mandatory.
## Optional lifecycle roles
The executable Function record carries one role byte before its optional name:
`0=None`, `1=BeforePause`, `2=BeforeResume`. Zero means an ordinary function,
not a callable hook. Unknown values reject with InvalidRegistry/LifecycleRole.
Each nonzero role has at most one target; duplicates reject with
InvalidRegistry/DuplicateLifecycleRole. Targets MUST NOT be FunctionId 0 and
MUST have zero parameters, results and captures; violations reject with
InvalidEntrypoint/LifecycleSignature. Preserve function/section context and the
wire offset when decoding an invalid role. Resolve optional FunctionIds once
in the immutable Registry. Names, exports, manifests and trait Method records
are not the binding mechanism.
Either hook may be absent. Additional roles require a future contract; there is
no termination role. PBX remains version 1, with no old-layout fallback or
external-artifact compatibility. Producers MUST regenerate their images and
emit this byte for every function, including zero for ordinary functions.
Frontend compilers choose their own source syntax and lower it to these roles.
Their existing Init/Frame boot assembly remains frontend-owned; runtime keeps
FunctionId 0 as its ordinary entry and does not introduce Init/Frame roles.
Execution ordering and limits are defined in [lifecycle](09a-coroutines-and-cooperative-scheduling.md).
## Values, storage and initialization
Value remains the generic stack/local representation. Structs/arrays are references; primitive and builtin-value array elements are stored directly. Layout descriptors distinguish value-slot width from heap-instance layout and distinguish GC references from native ownership. Derive offsets/defaults/maps once; access by indices/offsets rather than repeatedly traversing semantic metadata. Measure bitmap versus offset/block lists; changing the map encoding must not change the contract.
@@ -97,7 +97,8 @@ Sync Phase
Important properties:
- events are processed at known points;
- no execution occurs outside the frame loop;
- normal gameplay executes inside the frame loop; optional SystemOS lifecycle
hooks execute outside it with an independent budget;
- frame structure remains observable for host tooling and host-owned certification.
## 7 Foreground Lifecycle Events
@@ -111,7 +112,9 @@ The Game pause path is:
Home/SystemOS request
-> pause event becomes visible to the Game
-> bounded pause reaction budget
-> SystemOS suspension, even if the Game did not cooperate
-> leave gameplay execution
-> optional BeforePause hook
-> SystemOS suspension on normal completion, or session failure
```
The Game resume path is:
@@ -120,7 +123,8 @@ The Game resume path is:
SystemOS resume request
-> VM reactivation
-> resume or foreground-restore event becomes visible to the Game
-> Game may synchronize while still internally paused
-> optional BeforeResume hook
-> normal gameplay becomes eligible after successful return
-> visual foreground returns after a valid current-epoch render submission
```
@@ -128,10 +132,11 @@ SystemOS resume request
scheduler/runtime state. A Game may observe pause/resume, but it must not
control whether SystemOS suspends or resumes the VM.
When SystemOS replaces one Game with another from Home, the old Game MAY receive
a cooperative terminate/save lifecycle event if the runtime supports such an
event. That event is non-blocking in v1. SystemOS remains authoritative and may
close the old Game task/session without guest acknowledgement.
Registry hooks are optional and independent. Their binding, single-context call
boundary, fuel and debugger semantics follow [the lifecycle contract](09a-coroutines-and-cooperative-scheduling.md#controlled-lifecycle-calls).
Existing pending native lifecycle delivery bookkeeping remains separate; it is
not a new guest event API. There is no termination hook. SystemOS may close an
old Game task/session without guest acknowledgement when replacing it.
Pause budgets are measured in deterministic machine units, not host wall-clock
time. A suspended Game receives no normal gameplay ticks, no normal Game input,
@@ -13,7 +13,8 @@ diagnostic decoding can identify retired numbers. No compatibility mode exists.
Other instruction numbers are unchanged.
FRAME_SYNC closes a logical frame and preserves context. It has zero stack effect,
is not a terminator, can occur in any body and resumes next PC. Host MUST NOT
is not a terminator and resumes next PC. It is forbidden while a lifecycle hook
is active, including in its callees. Host MUST NOT
prepare fresh entry solely because sync occurred. Budget exhaustion/breakpoints
preserve the same open frame without draw publication or extra callback budget.
@@ -34,3 +35,53 @@ and invoke typed Fn callbacks. UI/SDK APIs and future coroutine protocols requir
separate contracts. See [Fn](02b-vm-function-values-and-closures.md),
[events](09-events-and-concurrency.md) and
[memory](03-memory-stack-heap-and-allocation.md).
## Controlled lifecycle calls
SystemOS optionally invokes the Registry's BeforePause and BeforeResume roles.
BeforePause runs after leaving the existing gameplay loop/handoff and before OS
suspension completes. BeforeResume runs after reactivation and before any normal
gameplay instruction. Neither hook is required, takes arguments, returns a
value, or vetoes the transition. Absence preserves the existing transition.
Direct suspension and Shell foreground handoff obey the same ordering; they do
not add a gameplay reaction tick. Home retains its existing one-tick handoff.
A controlled call appends a frame and locals to the same VM stacks. It retains
the previous PC, halted state and stack boundaries; all suspended stack values,
frame environments, globals and heap references remain roots. Existing stack,
call-depth and allocation quotas include retained frames. Reserve before entry
mutation. Ordinary calls inside the hook work normally. On successful outer
return (including a branch to function end), restore the continuation and return
immediately to SystemOS, even if the execution slice has unused cycles. Never
clear the stacks with boot-entry preparation or execute gameplay in that slice.
Global/heap mutations persist. There is at most one lifecycle invocation per
session; duplicate requests do not reenter or renew it, and conflicting pending
transitions reject.
Each invocation receives 1,500,000 virtual cycles total, sliced at no more than
250,000 admitted cycles per host update. This budget is independent of normal
logical frames and never renews between slices or debugger stops. Positive
remaining budget admits a whole instruction and allows its existing overshoot.
A normal completed return succeeds even if that final instruction consumes the
remaining budget; an unfinished invocation at exhaustion fails. There is no
wall-clock deadline. Breakpoints preserve the invocation and remaining budget;
while stopped, no cycles or gameplay frames advance. Instruction stepping uses
the same budget and the session's real service context.
FRAME_SYNC traps before frame/GC/publication effects, including from ordinary
callees. Fatal traps, host errors/panics and total exhaustion fail the session,
block gameplay and report the failing phase through the existing crash path.
There is no retry, rollback of earlier mutations or compensating other hook.
Normal service-result errors remain guest data. HALT closes the task through
the OS termination path; it is not successful hook return.
Hooks use the existing services and capability checks. No automatic save,
flush, disk-completion wait, guest event queue or reason argument is added.
Host-owned in-flight work keeps its ownership until the service/host safely
releases it; lifecycle failure does not simulate cancellation or free borrowed
buffers. Native calls must return promptly: VM fuel only bounds bytecode and
cannot preempt a blocked native/host call. Existing FS read/write and the current
memcard commit backend are synchronous interfaces, so this implementation does
not promise a wall-time bound for them. The new asynchronous memcard backend
must expose bounded submission/polling independently; hooks can then submit an
explicit commit without waiting for disk completion.