Files
prometeu-studio/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/LSN-0097-explicit-guest-hooks-and-preserved-continuations.md
T
bquarkz 71fb80efc3
Test / Tests and coverage occurred while executing withChecks step.
Intrepid/Prometeu/Studio/pipeline/head There was a failure building this commit
feat(studio): ship JavaFX 2 Play and delegate integration tooling
Launch the JavaFX 2 project shell on Java 25 with an interactive viewport,
managed Play lifecycle and project mutation guards. Preserve headless/MCP and
save compatibility, and qualify exact runtime executable bundles.
Separate unit JaCoCo gates from opt-in integration suites and use the internal
Pong fixture for the headless visual pilot.
Move maintenance and native conformance tools into tooling; retain the VS Code
extension and update current navigation links.

Validation: tooling make verify passed, including 1064 Studio unit tests,
JaCoCo thresholds and 22 headless integration tests.
2026-11-19 17:32:03 +00:00

161 lines
8.5 KiB
Markdown

---
id: LSN-0097
ticket: pbs-guest-lifecycle-hooks
title: Explicit Guest Hooks and Preserved Continuations
created: 2026-10-28
tags: [runtime-integration]
---
# Explicit Guest Hooks and Preserved Continuations
Owner: `compiler/pbs`, with propagation to `compiler/general` and `studio`.
Historical workflow: AGD-0086 → accepted DEC-0081 → completed PLN-0159.
The normative language/runtime contracts live in the linked specifications;
this lesson explains their implementation and qualification.
## Original problem
The runtime already published optional BeforePause and BeforeResume Registry
roles. Studio's common IR/PBX represented them, but PBS had no source declaration
selecting their targets. Init and Frame were already frontend-owned inputs to a
guarded common entry wrapper. Turning them into runtime callbacks would have
changed initialization and frame semantics unnecessarily.
The missing producer capability was explicit selection, validation and metadata
propagation, followed by source-to-production-runtime evidence. Existing runtime
unit tests were useful oracles but did not prove the PBS producer path.
## Consolidated decision
Use marker attributes on nongeneric top-level userland functions:
```pbs
declare global transitions: int = 0;
[BeforePause]
fn preparePause() -> void {
transitions += 1;
}
[BeforeResume]
fn prepareResume() -> void {
transitions += 1;
}
```
Each target has zero parameters, logical results and captures. Reading/writing
globals is allowed and does not create a function capture. Closures can still be
created and used in the body. Markers accept no arguments, cannot combine with
another lifecycle marker and may accompany existing Doc metadata.
Each role is independently optional, with at most one distinct declaration in
the compiled image, including imports. No colocation with Frame is required.
Repeated imports and reexports preserve the original declaration's identity.
Function names do not select roles; an unmarked function named BeforePause is
ordinary. A direct call to preparePause is also ordinary and does not request an
OS transition or acquire a controlled-call context.
BeforePause/BeforeResume lower to existing role bytes 1/2. Init, Frame, ordinary
functions and physical entry zero retain role None. The selected targets and
their dependencies are externally entered retention roots, even without source
callers. MemcardBoot selection/bootstrap/persistence remain a separate scope;
there is no termination hook or new lifecycle syscall.
## Implementation result
The PBS AST/parser recognizes both markers and rejects invalid declaration
targets, arguments and lifecycle combinations. Source semantic validation checks
empty nongeneric signatures; project validation detects distinct conflicting
targets and reports their names/locations. Canonical source spans distinguish a
new declaration from the same declaration encountered repeatedly.
PbsRuntimeTypes emits the role in typed FunctionMetadata. Existing common
assembly, lowering, optimization, linking and PBX writing preserve that metadata
and retain the functions/callees. The common writer independently rejects
captures, invalid typed signatures, duplicate roles and physical entry-zero
targets. It consumes neutral roles rather than PBS ASTs or names.
Editorial token classification recognizes both attributes. The installed
knowledge package includes the updated English specs, both hooks in the complete
example and a lifecycle guide. The installed-JAR gate compiles the example and
checks exactly one target per role. No runtime source or commit was needed.
## Execution model and qualification
Home's existing gameplay handoff precedes BeforePause and suspension. Reactivation
precedes BeforeResume; normal gameplay becomes eligible after the hook's outer
return. Controlled calls use the same stacks, globals and heap roots and restore
the interrupted continuation. Init and its guard are not restarted.
The runtime owns 1,500,000 total virtual cycles per controlled invocation, in
slices of at most 250,000 admitted cycles with whole-instruction overshoot.
Slices/debugger stops do not renew fuel. FRAME_SYNC traps inside a controlled
hook or its callees before frame publication. Fatal trap/fuel failure blocks
gameplay through the existing crash path. There is no automatic save, rollback,
compensation or wall-clock timeout.
Qualification used runtime `dcf6561ea73446e0a3e1cf1c73eda20923b38df0`, a clean
checkout, on local macOS arm64. Both Rust dev/release profiles executed ordinary
and optimized producer images. Seventeen actual PBS-produced images cover both,
each and neither hook, ordinary calls, successful multi-slice execution, fatal
trap/fuel, and an actual import/alias/reexport project. Two explicitly synthetic
binary fixtures cover direct/transitive sync because PBS has no sync syntax.
The production Firmware/SystemOS foreground path ran on the standard
TestPlatform hardware. It checked ordered guest effects, preserved PC, game
session tick/frame counters, global/heap state and one Init execution. Direct
suspension and Shell handoff added no reaction tick. A partial-frame VM check
retained its operand and call frame while both hooks executed. Breakpoint and
instruction stepping used the retained total fuel budget. Failure replays made
zero subsequent VM steps and produced no additional gameplay frame.
The guest observation encodes `trace * 10000 + initCount * 100 + heapValue`:
| Hooks | Trace | Init count | Heap value | Expected observation |
| --- | --- | --- | --- | --- |
| Both | 23 | 1 | 12 | 230112 |
| Pause only | 2 | 1 | 9 | 20109 |
| Resume only | 3 | 1 | 10 | 30110 |
| Neither | 0 | 1 | 7 | 107 |
Probe calls are terminal observations after all continuation/frame assertions;
they do not instrument or replace the foreground lifecycle path.
Full Gradle regression and installedKnowledgeTest passed, along with source,
semantic/editorial, common Registry/PBX and lifecycle-assembly tests. Commands,
suite summaries, profile logs and source/fixture hashes are retained in
[evidence](evidence/summary.json). This is local lifecycle qualification;
reference-game/installed-runtime qualification remains DSC-0086 and persistence
remains DSC-0085. Other platforms are not claimed by this evidence.
## Pitfalls and reusable patterns
- **Source selection is not invocation.** Preserve normal function-call behavior;
only the OS-controlled boundary changes the execution context.
- **No caller does not mean dead.** A runtime role is an external entry edge.
Verify final optimized bytes and execution, not just parser acceptance.
- **Zero captures does not prohibit globals or internal closures.** Validate the
target environment rather than banning ordinary language facilities.
- **Count declarations, not import appearances.** Cross-file uniqueness must
reject distinct targets while accepting an alias/reexport of the original.
- **Check physical IDs after linking.** Frontends select stable callable identity;
the common linker/writer validates final entry-zero exclusion.
- **Observe the retained session after failure.** A crash activates another UI
context. Reading an active-foreground telemetry facade can return the UI's zero
counters and produce a false lifecycle failure. Read the game's session counters.
- **Keep synthetic instruction tests explicit.** A binary sync oracle qualifies
runtime rejection without advertising unsupported PBS syntax.
- **Separate producer and provider variants.** Optimized PBS and release Rust are
two independent dimensions; qualify both instead of using one as a substitute.
## References
- [Static source contract](<../../../docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md>).
- [Dynamic execution contract](<../../../docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md>).
- [PBS lowering](<../../../docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md>).
- [Common typed Registry/PBX](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md).
- [Source-to-PBX corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java).
- [Production VM/foreground harness](../../../../tooling/scripts/pbx-conformance/lifecycle.rs).
- [Installed lifecycle guide](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/LIFECYCLE.md).
- Runtime [role binding](../../../../runtime/docs/specs/runtime/02c-program-registry-and-pbx-v0.md) and [controlled execution](../../../../runtime/docs/specs/runtime/09a-coroutines-and-cooperative-scheduling.md).