diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/LSN-0097-explicit-guest-hooks-and-preserved-continuations.md b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/LSN-0097-explicit-guest-hooks-and-preserved-continuations.md new file mode 100644 index 00000000..19f863ea --- /dev/null +++ b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/LSN-0097-explicit-guest-hooks-and-preserved-continuations.md @@ -0,0 +1,160 @@ +--- +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/compiler/general/specs/typed-registry-and-pbx-v0.md). +- [Source-to-PBX corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java). +- [Production VM/foreground harness](../../../tools/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). diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/README.md b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/README.md new file mode 100644 index 00000000..0a257c9e --- /dev/null +++ b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/README.md @@ -0,0 +1,32 @@ +# Lifecycle qualification evidence + +Owner: compiler/pbs, propagating to compiler/general and Studio. Completed under +DEC-0081 / PLN-0159. `summary.json` records revision, platform/configuration, +commands, results, JUnit suites and the distinction between producer/runtime +profiles. All recorded checks completed with exit code zero. + +The source corpus contains 17 production PBS images (eight scenarios in ordinary +and optimized form, plus a real workspace import/alias/reexport image). Two +separate synthetic PBX images cover direct and transitive FRAME_SYNC rejection. +The mandatory runtime driver fails if an expected fixture or probe index is absent. + +- `frontend.log.gz`: focused source diagnostics and editorial classification. +- `regression-and-installed.log.gz`: complete Gradle regression and installed-JAR + example compilation/metadata validation. +- `runtime-dev.log.gz`, `runtime-release.log.gz`: production VM/firmware execution, + ordered guest effects, retained state/PC/frames, foreground transitions and + failure/budget/debugger checks for both producer variants. +- `TEST-*.xml.gz`: final focused source-corpus result, including project imports. +- `sources.sha256`: final implementation, test, harness and normative doc hashes. +- `fixtures.sha256`: generated PBS sources, PBX images and terminal probe indices. +- `SHA256SUMS`: hashes of retained evidence files. + +The full Gradle check preceded a final test-only addition of unmarked functions +named BeforePause/BeforeResume to the lifecycle corpus. Its focused regeneration +and both final runtime profiles passed afterward; production code was unchanged. + +The runtime checkout stayed clean and uncommitted. Local macOS arm64 is the +qualified platform. Installed runtime/reference-game qualification (DSC-0086) +and MemcardBoot/persistence (DSC-0085) remain separate. The installed example was +compiled from installed JARs and its role metadata checked; this does not claim an +installed runtime process test. diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/SHA256SUMS b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/SHA256SUMS new file mode 100644 index 00000000..992db3db --- /dev/null +++ b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/SHA256SUMS @@ -0,0 +1,10 @@ +2c4e57abf13882fb1cf661ed877e37f5e44225b0395fe83a3836e44678b518b4 README.md +e520456a82c905db92598e4a314b1614d409358674e73d0dcd61416b146d3c6d TEST-p.studio.compiler.backend.irvm.PbsGuestLifecycleTest.xml.gz +638814b1afabc2e156de2eb6f018400aab7fea2c9b69c7f956ab16251dd5ed60 fixtures.sha256 +ceb059e502313f0327e0560a4532c57f4a341776d054fee1558c54e6de82c4b1 frontend.log.gz +44619de3dcc5ca667a2dbe951146eba0cf21a919f8d0a1610dc5fec8ade1f33d regression-and-installed.log.gz +cd7051255fed7a2760fbec8be05b9e8a98b224f704828a26e28ee71097810bbf runtime-dev.log.gz +3bd1c9aceb4a05bfcd5ddaa4a1d8e2ed96270e3666b7f4ce46a91f7e7bf902ee runtime-release.log.gz +bd704a8fe37c15f2b404c3924e49b06f5a8b3a1e389be9252cd3dae953b67f7a sources.sha256 +867e02d58fcd451a68a54c59ae63e0d57d2c08fc79861d5d0d8b20ee832b5d81 summary.json +d7e7bdfdb38395e54163d7b9d24d7a6f1ce5fb5d017feac63c6e0fc463c7afaf workflow.txt diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/TEST-p.studio.compiler.backend.irvm.PbsGuestLifecycleTest.xml.gz b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/TEST-p.studio.compiler.backend.irvm.PbsGuestLifecycleTest.xml.gz new file mode 100644 index 00000000..69c2e658 Binary files /dev/null and b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/TEST-p.studio.compiler.backend.irvm.PbsGuestLifecycleTest.xml.gz differ diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/fixtures.sha256 b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/fixtures.sha256 new file mode 100644 index 00000000..0dafdb55 --- /dev/null +++ b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/fixtures.sha256 @@ -0,0 +1,43 @@ +5c2246b38f41115a78a218e18df97100c88766d493618337784d51e91bdd35a1 pbs-lifecycle-both-optimized.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-both-optimized.probe +50b428366203d8f48821af5c83235aa1022d284f7575152f75ff266b6299fefd pbs-lifecycle-both.pbs +6d4de740a607f6f330fb7e54144a0163ba49f9a2a206a8276f01ae89d96866be pbs-lifecycle-both.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-both.probe +07e4f1ce2de6003b54b4b892ca8999eedb6cd57758fece362f97cb8da205599c pbs-lifecycle-direct-optimized.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-direct-optimized.probe +ed4ac88be81337c387e315bd1124a66c7beda2723b72a5a9a8d81e0740a0d562 pbs-lifecycle-direct.pbs +6ca68fdfa58e57eab8a29a88f39f0ff14913b15df5ef2ff77ed793140b65c92f pbs-lifecycle-direct.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-direct.probe +c24146b38d7d588b6c0d8d5e08add0f884b5b2bc580633bad150c6d0c47814ca pbs-lifecycle-fuel-optimized.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-fuel-optimized.probe +8b747f16681b209f6ba05ecd41eba266824938fe446a31ddf55d29115c79a563 pbs-lifecycle-fuel.pbs +ce037c0e3206add2f07a47ba55276016915cd431f2051b2f9a9082e6bfb3ef78 pbs-lifecycle-fuel.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-fuel.probe +dddc982653e21944186c4825839bd6c016e96fad5163dd952ce5785575e818af pbs-lifecycle-imports.pbx +889a67c478fb1e7d369bf3c7cef4074033ab9fee7e18d28a7d85b9b2d33ae2b5 pbs-lifecycle-none-optimized.pbx +4fc82b26aecb47d2868c4efbe3581732a3e7cbcc6c2efb32062c08170a05eeb8 pbs-lifecycle-none-optimized.probe +5cb251da8ea307dd541698651393f2beb38c7cee19aafd074fdca509f0630ef0 pbs-lifecycle-none.pbs +8dddca4ceedd591f4189d7855f9bd679642969821000f5bfb82e14fcafd92adc pbs-lifecycle-none.pbx +4fc82b26aecb47d2868c4efbe3581732a3e7cbcc6c2efb32062c08170a05eeb8 pbs-lifecycle-none.probe +6bf05d7060e7a1d56db90a8af65159fc960396f462bd0f8527b0387e5dd87508 pbs-lifecycle-pause-optimized.pbx +6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918 pbs-lifecycle-pause-optimized.probe +15f6aa8662ed1554e585dd2420bfd276e526384fbdc255d75247688070684282 pbs-lifecycle-pause.pbs +34bfe4bd10f3b1520857ad8155f0ee5cb7948f11e69692e6595f2cf442293f1c pbs-lifecycle-pause.pbx +6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918 pbs-lifecycle-pause.probe +6549eb46d2080018054e2c4f2103493a02174b1734951b5d1296c1087e27cd83 pbs-lifecycle-resume-optimized.pbx +6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918 pbs-lifecycle-resume-optimized.probe +d4102af8845a3d744050570aaf51db9b316d226dac39e6da52661f24e61d6313 pbs-lifecycle-resume.pbs +408b88e8be1b42ca2491b6316a0ef66c493792114b0d2089f31cd1ce95f65a27 pbs-lifecycle-resume.pbx +6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918 pbs-lifecycle-resume.probe +9c4f993115ceb999ddbba679e3368eba1e219dcf05becf8b2a57a1ee9d15ee0e pbs-lifecycle-slices-optimized.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-slices-optimized.probe +a9aa1216c5d86e82e40fd5606147b17fad80d0b4c46462d8756747142fcbf52f pbs-lifecycle-slices.pbs +8fa567dafcd4af866991546ee73fdba47e4d0fbaa07ae83d21e814385af84f38 pbs-lifecycle-slices.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-slices.probe +f7090ddffc7a9292e740e883bc67b6fccce7afa5961fa1419a650a0689163e22 pbs-lifecycle-trap-optimized.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-trap-optimized.probe +103b2afa4ad1d35fda95d17ff91512cca916bd60cc4b9d4c274382c5741ebfe2 pbs-lifecycle-trap.pbs +1189b68937613f275c8bedd71d9c002a717a0b10af36561d22cbddd8be2dc548 pbs-lifecycle-trap.pbx +3fdba35f04dc8c462986c992bcf875546257113072a909c162f7e470e581e278 pbs-lifecycle-trap.probe +1e9d96319edace744d5beb7668759ce31561334118fa74f5cc14895d34003514 synthetic-lifecycle-sync-direct.pbx +f3cb6eedacec1ea0680422d63df61199bd8e5e6b8682d2aff892cbd5a5d2c2ec synthetic-lifecycle-sync-transitive.pbx diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/frontend.log.gz b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/frontend.log.gz new file mode 100644 index 00000000..b50f83b6 Binary files /dev/null and b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/frontend.log.gz differ diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/regression-and-installed.log.gz b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/regression-and-installed.log.gz new file mode 100644 index 00000000..51d5f689 Binary files /dev/null and b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/regression-and-installed.log.gz differ diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/runtime-dev.log.gz b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/runtime-dev.log.gz new file mode 100644 index 00000000..c10bb3ac Binary files /dev/null and b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/runtime-dev.log.gz differ diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/runtime-release.log.gz b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/runtime-release.log.gz new file mode 100644 index 00000000..0eb93904 Binary files /dev/null and b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/runtime-release.log.gz differ diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/sources.sha256 b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/sources.sha256 new file mode 100644 index 00000000..21aa88d8 --- /dev/null +++ b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/sources.sha256 @@ -0,0 +1,29 @@ +a42de4571212c8dff1eef91d23c0dba601775f6e0d7955ee4b9b17f6befff274 docs/compiler/general/specs/typed-registry-and-pbx-v0.md +63b86268963c8e55a1c696b4d94336e6b7eebcdff4b42c1f779689f5d105dd6d docs/specs/compiler-languages/pbs/11. AST Specification.md +2b00db5545a94c8da9924b8199941531e28745d6fdb98661f2483bf2902d286d docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md +e92272412d581986bf5fb7cea3d946847422f9ba3bd7c01d6684fd2d84810dc3 docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md +e0e81be40ddac4494e8cf0507dd63f95e2f0e88908b75ec9b62a545d40f393c4 docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md +40da42be54056b54edc33c83696315fa48df9b34d97e049b8369ce8c20a3be15 docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md +73aba41215252a1397c1d0257d4133aca2dba2b28ce9c946bc79b466e5587c5d docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md +35c5df2652f4d1573854f6d57fa11b21dc8cb3eb952298f7dc2b500852a0293f docs/specs/compiler/16. Runtime Execution and Initialization Specification.md +6c9f5337ce5aa22a455c5e4dbb76206f69a5ff0b9e4110c3792ec6e8f98e7aa6 docs/specs/compiler/19. Verification and Safety Checks Specification.md +d8d45d9a8c48ef13b180255bf261847cfed34704a6c63d4ed4a75c80665322e7 docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md +4ecdc9be93b98c016b339ead2e4e90c1785467e844fb68cbf84017052b99074d prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java +18f948fb3c87167b8521e28d32a77cad1fab1ed4ab12395f86f12274f3eedb88 prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java +2b8d17e5ba0145e880af4bc76d4ffe56f20094a0528701069edaf790f61d97e1 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSSemanticTokenProvider.java +0e0e08da348a921cc0e4ec17e61fcbdd713811bef7bd31dee1738b8666cd83cd prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java +063951bf7ebc9618c1e7868cb44275d4ea01894be94fa4cf4fd9989ebf6173f3 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java +02dd5c624df3530054ff35a191fbdac67831c89ef737c59044a1c3cc8b2497d7 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java +17e43cc02a33af36debb05f0af237d05813f61b9cbef15d23d96cc7722819c38 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java +e31d7159badadbcd3ef5367e72ca6366f91f90a89e9be95d3fcde0115087f246 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsLifecycleSemanticsValidator.java +26f56b90f647fe8870ae69efe436599ace45358ae7b00536381ee17014217163 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSemanticsErrors.java +1390df356accad8c02cf48de94b5d8e34cb7c8cb3843420120cfe2b0f72adac4 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsProjectLifecycleSemanticsValidator.java +fc078b7f68be79179bddfeeee744e05bf299c32f0ae1352be628a4b4a82a8669 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/LIFECYCLE.md +eea76258ef59e43be782bba2813e9398952fe97a224e2011f5b8ffbf16bfccae prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/lifecycle.pbs +75c5e944a7ca74896cbe526ad5ec40ab64ed8779e2abc22e5c325232c16bbdd5 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel +bafc27685be973fe8d68d16620bab7fabe43e061a84b9f8421bdb5c373257b17 prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PbsGuestLifecycleSemanticsTest.java +b5e119757386885f332ebd7cbcc335de07ac479f0baa4482b2f9e19aa66bed18 prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/PbxRegistryConformanceTest.java +d366e5e5fb34f80cee5eca654c44b26f5a1f2189ecf0550a3aaf0b4637967fd8 tools/pbx-conformance/README.md +68e0a22927e79c6081da7bdf13c2d51f0c3481f1da25df7968085a95e0fc71fb tools/pbx-conformance/lifecycle.rs +ab99510c78976e62047c88fd0c0f11e16b8bdb66c3a9b6632b263581a7c92528 tools/pbx-conformance/main.rs +29e621bb09f768dcd1cd11a69b338f099e378bfc05ab27fd5cacf69141da7803 tools/pbx-conformance/run.py diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/summary.json b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/summary.json new file mode 100644 index 00000000..a996b072 --- /dev/null +++ b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/summary.json @@ -0,0 +1,104 @@ +{ + "recorded_at_utc": "2026-10-28T09:06:34.710754+00:00", + "discussion": "DSC-0084", + "decision": "DEC-0081", + "plan": "PLN-0159", + "owners": [ + "compiler/pbs", + "compiler/general", + "studio" + ], + "studio_revision": "eb7d6a23988b2e13ab1e91b7663abbd7ab983f4c", + "studio_working_tree": "task changes identified in sources.sha256", + "runtime_revision": "dcf6561ea73446e0a3e1cf1c73eda20923b38df0", + "runtime_working_tree": "clean", + "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "architecture": "arm64", + "capabilities": "NONE", + "limits": "production defaults", + "features": [ + "resource-diagnostics" + ], + "checks": { + "frontend": { + "command": "./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests '*PbsGuestLifecycleSemanticsTest' --console=plain", + "exit_code": 0 + }, + "source_corpus": { + "command": "./gradlew :prometeu-architecture-tests:test --tests '*PbsGuestLifecycleTest' --console=plain", + "exit_code": 0 + }, + "regression_and_installed": { + "command": "./gradlew test :prometeu-app:installedKnowledgeTest --console=plain", + "exit_code": 0 + }, + "runtime_dev": { + "command": "python3 tools/pbx-conformance/run.py --runtime ../runtime --lifecycle-only", + "exit_code": 0 + }, + "runtime_release": { + "command": "python3 tools/pbx-conformance/run.py --runtime ../runtime --lifecycle-only --release", + "exit_code": 0 + }, + "workflow": { + "command": "discussion validate", + "exit_code": 0 + }, + "whitespace": { + "command": "git diff --check", + "exit_code": 0 + } + }, + "junit_suites": { + "prometeu-architecture-tests/build/test-results/test/TEST-p.studio.compiler.backend.irvm.PbsGuestLifecycleTest.xml": { + "tests": 3, + "failures": 0, + "errors": 0, + "skipped": 0 + }, + "prometeu-compiler/prometeu-build-pipeline/build/test-results/test/TEST-p.studio.compiler.backend.registry.PbxRegistryConformanceTest.xml": { + "tests": 18, + "failures": 0, + "errors": 0, + "skipped": 0 + }, + "prometeu-compiler/prometeu-build-pipeline/build/test-results/test/TEST-p.studio.compiler.workspaces.stages.AssembleLifecyclePipelineStageTest.xml": { + "tests": 3, + "failures": 0, + "errors": 0, + "skipped": 0 + }, + "prometeu-compiler/prometeu-build-pipeline/build/test-results/test/TEST-p.studio.compiler.lifecycle.LifecycleAssemblerServiceTest.xml": { + "tests": 10, + "failures": 0, + "errors": 0, + "skipped": 0 + }, + "prometeu-compiler/frontends/prometeu-frontend-pbs/build/test-results/test/TEST-p.studio.compiler.services.PbsGuestLifecycleSemanticsTest.xml": { + "tests": 3, + "failures": 0, + "errors": 0, + "skipped": 0 + } + }, + "runtime_profiles": [ + "dev", + "release" + ], + "producer_variants": [ + "ordinary", + "optimized" + ], + "source_pbx_images": 17, + "synthetic_sync_pbx_images": 2, + "known_limits": [ + "Local macOS arm64 qualification only", + "Installed JAR example compiled and role metadata checked; final installed runtime/reference-game qualification belongs to DSC-0086", + "MemcardBoot/persistence remain DSC-0085" + ], + "workflow_cli_gap": "The CLI exposes no next-lesson counter query; metadata counter was read without manual index mutation. Lesson registration and allocation remain discussion housekeep operations.", + "source_files": 29, + "workflow_status": "done", + "lesson": "LSN-0097", + "runtime_working_tree_after": "clean" +} diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/workflow.txt b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/workflow.txt new file mode 100644 index 00000000..7cac22d5 --- /dev/null +++ b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/evidence/workflow.txt @@ -0,0 +1,14 @@ +Discussion: DSC-0084 +Status: done +Ticket: pbs-guest-lifecycle-hooks +Title: PBS Guest Lifecycle Hooks +Tags: runtime-integration + +Active artifacts: +- LSN-0097 (lessons, done, present): discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/LSN-0097-explicit-guest-hooks-and-preserved-continuations.md + +Suggested next actions: +- none + +Final discussion validate: validation passed +Final git diff --check: passed diff --git a/docs/compiler/general/specs/typed-registry-and-pbx-v0.md b/docs/compiler/general/specs/typed-registry-and-pbx-v0.md index 002bce0d..6aa3eebe 100644 --- a/docs/compiler/general/specs/typed-registry-and-pbx-v0.md +++ b/docs/compiler/general/specs/typed-registry-and-pbx-v0.md @@ -265,3 +265,16 @@ BudgetExhausted and debugger pauses can occur between instructions and resume at the current PC; they neither roll back nor complete a method. No atomic observation of source operations by host/debugger is promised. SDK methods introduce no user callbacks or explicit suspension during the updates that complete their invariants. + + +## Producer-selected guest hook roots + +BeforePause/BeforeResume role targets and their transitive dependencies MUST +remain in the executable set even without ordinary callers. Preserve typed +metadata through merge, lifecycle assembly, optimization and linking. Names, +exports and frontend ASTs MUST NOT become a common role-selection mechanism. +Common emission validates unique nonzero roles, empty pause/resume signatures +and capture lists, and final hook FunctionIds other than zero. The ordinary +entry and synthetic Init/Frame assembly keep role None. Calling a hook as an +ordinary function does not request an OS transition. PBS marker syntax belongs +to its frontend; MemcardBoot selection/bootstrap is a separate producer scope. diff --git a/docs/specs/compiler-languages/pbs/11. AST Specification.md b/docs/specs/compiler-languages/pbs/11. AST Specification.md index e882d697..07294dca 100644 --- a/docs/specs/compiler-languages/pbs/11. AST Specification.md +++ b/docs/specs/compiler-languages/pbs/11. AST Specification.md @@ -76,7 +76,7 @@ Mandatory declaration metadata on required declaration nodes includes: 2. declared signature/surface when applicable (parameters/return), 3. declaration-level syntactic flags/attributes required by later phases, 4. stable `file/start/end` attribution, -5. lifecycle-marker metadata when a declaration carries `[Init]` or `[Frame]`, +5. lifecycle-marker metadata when a declaration carries `[Init]`, `[Frame]`, `[BeforePause]` or `[BeforeResume]`, 6. documentation attribute metadata when a declaration carries `[Doc(markdown = """...""")]`. Missing required attribution or metadata on mandatory nodes is non-conformant. @@ -110,6 +110,7 @@ Lifecycle-observable declarations must preserve marker metadata explicitly: - top-level `fn` marked with `[Init]`, - top-level `fn` marked with `[Frame]`, +- top-level `fn` marked with `[BeforePause]` or `[BeforeResume]`, - and host method signatures marked with `[InitAllowed]`. Documentation-observable declarations must preserve `Doc` metadata explicitly on every accepted named API declaration surface that carries `[Doc(markdown = """...""")]`. @@ -196,3 +197,14 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). Structs and free functions preserve ordered parameter declarations and spans. Explicit applied function references preserve type arguments and their source span. Implements preserves its binder, full applied owner and target. Substitution rewrites every field, signature, annotation and executable body/capture position with a declaration-local environment. Concrete application provenance retains original declaration, canonical logical arguments and requesting use; it is not an executable runtime template. See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). + + +## Guest hook marker identity + +LifecycleMarker explicitly distinguishes NONE, INIT, FRAME, BEFORE_PAUSE and +BEFORE_RESUME. Preserve marker attributes and source spans alongside the marker; +never reconstruct the role from a function name or an import alias. Invalid +attribute targets/combinations MUST be diagnosed rather than silently treated +as ordinary functions. Generic substitution/import processing MUST preserve +canonical source identity and marker metadata. No MemcardBoot marker is defined +by this surface. diff --git a/docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md b/docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md index dd36c0b9..1404236d 100644 --- a/docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md +++ b/docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md @@ -320,3 +320,26 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). Generic diagnostics distinguish duplicate/unbound parameters, exact arity, raw or improperly inferred application, unjustified symbolic capabilities, invalid substituted positions, constructor errors, collapsed overloads, invalid bound owners, overlap and bounded expansion. Preserve declaration and requesting-use locations with a short instantiation chain. Editor projections retain symbolic parameter, concrete argument and generic origin identities. Generated instance names and host stacks do not replace source explanations. See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). + + +## Guest lifecycle diagnostics and conformance + +Invalid target, marker arguments and combinations are source-anchored syntax or +reserved-attribute diagnostics. Nongeneric empty signatures use +`E_SEM_INVALID_LIFECYCLE_SIGNATURE`; generic-instantiation admission may also +report the existing generic lifecycle error. `E_SEM_DUPLICATE_LIFECYCLE_ROLE` +identifies the role, conflicting declarations and their source locations across +the project graph; import order MUST NOT select a winner. Source diagnostics do +not guess physical FunctionIds. Typed handoff/PBX validation rejects duplicate +roles, captures, invalid signatures and physical entry-zero targets separately +from runtime load failures and executed traps. + +Conformance MUST include both/one/no-hook cases, arbitrary names, imported and +repeated-import targets, invalid source surfaces, valid globals/closures, +optimized targets with no callers and ordinary direct calls. Execute generated +production PBX through production runtime/host Home/resume, observing ordered +effects, retained PC/state/init guard and gameplay frame/tick counters. Trap, +fuel exhaustion across slices and direct/transitive FRAME_SYNC are required; +sync fixtures use synthetic common IR because PBS exposes no sync construct. +Record revisions, platform/configuration, commands, scenarios, oracles and +results. Existing runtime tests alone are not producer integration evidence. diff --git a/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md b/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md index 2ea65f72..f3befb43 100644 --- a/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md +++ b/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md @@ -229,7 +229,7 @@ For executable PBS frontends, PBS lowering MUST emit a typed `IRLifecycleDeclara At frontend `IRBackend` emission time: -1. PBS MUST retain marker admission for `[Init]`, `[Frame]`, and `InitAllowed`, +1. PBS MUST retain marker admission for `[Init]`, `[Frame]`, `[BeforePause]`, `[BeforeResume]`, and `InitAllowed`, 2. PBS MUST emit typed references for: - file-init fragments that include global materialization and non-project `[Init]`, - the optional project-init callable, which is the `[Init]` colocated with `[Frame]`, @@ -262,3 +262,20 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). Instantiate structs, free functions and owner-bound implementations within PBS before publishing executable descriptors. Registry receives concrete fields, signatures, bodies, capture groups and targets. Specialized free-function references use existing empty-environment Closure values; Fn remains structural. Preserve receiver identity, implementation zero, singletons, rooting, GC, ownership, evaluation/fault order and quotas. No generic Dynamic/boxing ABI, opcode, descriptor category or runtime instantiation engine is introduced. See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). + + +## Lowering optional runtime hook roles + +Map BEFORE_PAUSE/BEFORE_RESUME to `IRRegistry.Role.BEFORE_PAUSE` (1) / +`BEFORE_RESUME` (2) in typed FunctionMetadata. Preserve the declaration/callable +identity, empty signature and capture list; no hidden receiver or parameter is +introduced. INIT/FRAME and ordinary functions retain role None (0). Function +names/exports/manifests are not role binding mechanisms. No MemcardBoot role is +inferred or emitted by these markers. + +Each role target and its dependencies are externally entered retention roots, +even without source callers. Merge, lifecycle assembly, linking and optimization +MUST preserve bodies and metadata. Common code consumes neutral typed roles, +never PBS ASTs/names. The ordinary assembled entry remains physical FunctionId +zero; hook targets are nonzero after deterministic linking. Common Registry/PBX +validation and production runtime admission remain mandatory defenses. diff --git a/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md b/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md index ae56bf52..8883d012 100644 --- a/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md +++ b/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md @@ -253,7 +253,7 @@ Rules: - An attribute attaches syntactic metadata to the declaration surface that immediately follows it. - Attributes do not introduce values, types, callables, or modules by themselves. - In v1 core, ordinary user-authored modules MUST reject attributes unless another specification explicitly permits them. -- Ordinary userland source MAY use `[Init]` and `[Frame]` only on top-level `fn` declarations. +- Ordinary userland source MAY use `[Init]`, `[Frame]`, `[BeforePause]` and `[BeforeResume]` only on top-level `fn` declarations. - Ordinary userland source MAY use `[Doc(markdown = """...""")]` on named API declarations where the static semantics specification permits documentation. - Reserved stdlib/toolchain interface modules MAY use attributes where explicitly allowed by syntax and semantics. - Reserved stdlib/toolchain interface modules MAY additionally use `[InitAllowed]` only on `declare host` method signatures where another specification explicitly permits it. @@ -1218,3 +1218,22 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). Struct and module-level free-function declarations and their barrel items accept ordered type parameters. Explicit function applications are reference expressions; calls use existing parentheses/apply. Generic construction supports explicit arguments and contextual diamond/omission. Owner-bound `implements` accepts its own parameter binder and a full applied owner. Independent method parameters, function diamond/inference and polymorphic Fn remain invalid. The owner specification defines exact arity, comparison disambiguation and recovery. See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). + + +## Controlled guest lifecycle marker syntax + +`[BeforePause]` and `[BeforeResume]` select optional runtime lifecycle hooks: + +```pbs +[BeforePause] +fn preparePause() -> void {} +[BeforeResume] +fn prepareResume() -> void {} +``` + +These markers accept no arguments and MUST NOT combine with another lifecycle +marker (`Init`, `Frame`, `BeforePause`, `BeforeResume`). Existing `[Doc]` metadata +may accompany them. Targets MUST be nongeneric top-level userland functions; +methods, lambdas, host/interface declarations and other declaration kinds are +invalid targets. Function names are arbitrary and do not select runtime roles. +PBS exposes no sync statement, lifecycle syscall or termination marker. diff --git a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md index 776a56a5..5ec580a3 100644 --- a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md +++ b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md @@ -80,7 +80,7 @@ Rules: - Attributes are not first-class values and are not reflectable in v1 core. - Attributes do not automatically survive into runtime or bytecode artifacts. - An attribute affects runtime artifacts only when another specification defines an explicit lowering for its semantic effect. -- In v1 core, the normative reserved attributes are `Host`, `Capability`, `AssetLowering`, `BuiltinType`, `BuiltinConst`, `IntrinsicCall`, `Init`, `Frame`, `InitAllowed`, and `Doc`. +- In v1 core, the normative reserved attributes are `Host`, `Capability`, `AssetLowering`, `BuiltinType`, `BuiltinConst`, `IntrinsicCall`, `Init`, `Frame`, `BeforePause`, `BeforeResume`, `InitAllowed`, and `Doc`. - `Host` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body. - `Capability` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body. - `AssetLowering` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body. @@ -837,3 +837,23 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). Templates are checked symbolically in definition scope. Required concrete owners validate all methods and constructors, including unused methods. Substitute complete bodies and applied Self; preserve position restrictions, invariant nominal/phantom identity and logical groups. Explicit function applications filter generic overloads by type arity; ordinary calls never infer them. Bound owner implementations require complete exact signatures and symbolic overlap rejection before use. Finite recursive applications are anchored; expanding type/body families are bounded errors. See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). + + +## Controlled guest lifecycle admission + +`[BeforePause]` and `[BeforeResume]` targets MUST be nongeneric top-level +userland functions with explicit unit signature `fn name() -> void`, zero +parameters, zero logical results and zero captures. Marker arguments and +combinations with any other lifecycle marker are invalid; `[Doc]` remains +allowed. Globals are not captures. Normal calls and closure creation/use inside +the body remain subject to ordinary PBS rules. + +Each role is independently optional and has at most one distinct target across +the compiled graph/image, including imported modules. Targets may be in any +compiled userland file, without colocation with `[Frame]`. Repeated imports of +the same source declaration MUST NOT manufacture duplicate targets; distinct +declarations for one role MUST produce a deterministic conflict diagnostic. +Direct calls remain normal calls and do not request an OS transition or create +a controlled invocation. Runtime FunctionId zero is reserved for the ordinary +entry; physical hook IDs are validated after linking. Init/Frame requirements +and their frontend/common assembly remain unchanged. diff --git a/docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md b/docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md index a8a23c1f..ca6ce020 100644 --- a/docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md +++ b/docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md @@ -382,3 +382,30 @@ The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-a ## Typed arrays and optional execution extension The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics. + + +## Controlled pause and resume hooks + +Source-selected BeforePause/BeforeResume functions lower to existing runtime +roles 1/2. Runtime owns invocation ordering, continuation, fuel and failures. +Home's existing handoff precedes BeforePause; suspension completes after normal +hook return. Reactivation precedes BeforeResume; no normal gameplay instruction +is eligible until that hook returns. Direct suspension and Shell handoff follow +the runtime contract without an additional gameplay reaction tick. Missing +hooks preserve existing transitions. + +Controlled calls retain the same VM stacks, suspended values, environments, +globals and heap roots, restoring the continuation on outer return and handing +control immediately to the OS. Mutations persist. They MUST NOT reprepare entry, +repeat Init, reset the boot guard, or add gameplay ticks/logical frames. Ordinary +calls to marked functions do not themselves acquire controlled-call semantics. + +Each controlled invocation has 1,500,000 virtual cycles total, sliced at at most +250,000 admitted cycles per host update, with the runtime's whole-instruction +overshoot rule. Slices/debugger stops do not renew fuel. There is no wall-clock +deadline. FRAME_SYNC, including in a callee, traps before frame/GC/publication +effects. Fatal traps/host failures and unfinished fuel exhaustion fail the +session, block gameplay and retain the existing crash envelope, without retry, +rollback or compensation. HALT is OS termination, not successful hook return. +Existing capability/service rules apply, without auto-save, flush, disk wait, +transition veto or reason argument. MemcardBoot and persistence are separate. diff --git a/docs/specs/compiler/16. Runtime Execution and Initialization Specification.md b/docs/specs/compiler/16. Runtime Execution and Initialization Specification.md index 5d7ee9ab..24196b71 100644 --- a/docs/specs/compiler/16. Runtime Execution and Initialization Specification.md +++ b/docs/specs/compiler/16. Runtime Execution and Initialization Specification.md @@ -153,3 +153,18 @@ This document is ready to move beyond temporary status only when: 2. service and module runtime lifecycle assumptions are explicit enough to remove the remaining TODO items, 3. execution lifecycle boundaries are aligned with dynamic semantics and runtime authority, 4. and the document no longer relies on unresolved TODO items for ordinary v1 runtime startup behavior. + + +## Optional controlled runtime hooks + +Producer-selected BeforePause/BeforeResume metadata MUST survive lifecycle +assembly without joining the init sequence or replacing the frame root/entry. +BeforePause runs after the existing gameplay handoff and before suspension; +BeforeResume runs after reactivation and before any normal gameplay instruction. +Missing hooks preserve transitions. Controlled calls preserve PC/stacks/roots, +globals and init guard; outer return restores continuation and yields to the OS +without another gameplay tick/frame or reinitialization. Direct calls remain +ordinary calls. Runtime owns the independent bounded fuel, transitive sync +prohibition, debugger behavior and failure envelope. There is no termination +hook, new syscall or automatic persistence. See the runtime's controlled +lifecycle contract and common typed Registry/PBX specification. diff --git a/docs/specs/compiler/19. Verification and Safety Checks Specification.md b/docs/specs/compiler/19. Verification and Safety Checks Specification.md index 740893d7..b0cc7c98 100644 --- a/docs/specs/compiler/19. Verification and Safety Checks Specification.md +++ b/docs/specs/compiler/19. Verification and Safety Checks Specification.md @@ -216,3 +216,15 @@ This specification MUST NOT be read as authorizing: - or reopening lifecycle-assembly ownership. Platform validators MUST NOT depend on types from the PBS frontend module (`prometeu-frontend-pbs`). The package `p.studio.compiler.pbs` is not the complete boundary; facades shipped by that module remain PBS-owned. Platform validators MUST NOT discover roles from `__pbs.` prefixes. + + +## Guest hook verification boundary + +Frontend diagnostics validate source marker targets/signatures and image-wide +uniqueness. Common typed validation MUST independently reject duplicate roles, +pause/resume parameters/results/captures and final FunctionId-zero targets. +These producer defenses do not replace runtime loading/admission. Assembly and +optimization MUST preserve hook metadata and externally entered bodies/callees. +Regression tests MUST inspect production PBX from source and execute it through +the production runtime. Source errors, common emission errors, loader failures +and executed traps retain distinct diagnostics; preserve the runtime envelope. diff --git a/docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md b/docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md index 996f6ced..9589da95 100644 --- a/docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md +++ b/docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md @@ -289,3 +289,15 @@ This document is healthy when: 4. common backend obligations are not described as owned by PBS, 5. frontend-specific lowering specs only own emission into `IRBackend`, 6. and scope boundaries with optimization/emission specs are explicit. + + +## Preserving optional runtime hook metadata + +Typed FunctionMetadata roles are frontend-neutral executable input. Lowering, +function ordering and optimization MUST retain externally entered role targets, +their dependencies and exact signature/capture/role metadata even without +ordinary CALL edges. Physical entry zero remains ordinary; deterministic linking +assigns other IDs to hooks. PBX emission consumes the existing role byte and +validates final targets, without role inference from function names or frontend +ASTs. Synthetic Init/Frame assembly is unchanged. FRAME_SYNC fixtures used to +test controlled-call rejection do not introduce frontend sync syntax. diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java index e6b0b418..1a4304b6 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java @@ -37,6 +37,8 @@ public final class InstalledKnowledgeProbe { check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/maps.pbs")), "Missing installed Map/Keyval example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-stack-and-queue.md")), "Missing installed Stack/Queue specification"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/stack-queue.pbs")), "Missing installed Stack/Queue example"); + check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/lifecycle.pbs")), "Missing installed lifecycle example"); + check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:LIFECYCLE.md")), "Missing installed lifecycle documentation"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/hashing.pbs")), "Missing installed hashing example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:sdk:game:1:sdk/hash/main.pbs")), "Missing installed hash SDK"); for (var reference : docs) { @@ -70,6 +72,11 @@ public final class InstalledKnowledgeProbe { BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString())), LogAggregator.stdout()); check(result.diagnostics().stream().noneMatch(issue -> issue.isError()), "Example must compile without errors"); check(result.bytecodeBytes().length > 0, "Example must produce bytecode"); + for (var role : java.util.List.of(p.studio.compiler.models.registry.IRRegistry.Role.BEFORE_PAUSE, + p.studio.compiler.models.registry.IRRegistry.Role.BEFORE_RESUME)) { + check(result.bytecodeModule().functions().stream().filter(f -> f.metadata().role() == role).count() == 1, + "Installed example must preserve exactly one " + role); + } Path listRoot=Files.createDirectory(Path.of("list-example")).toRealPath(); Files.createDirectories(listRoot.resolve("src")); Files.copy(root.resolve("prometeu.json"),listRoot.resolve("prometeu.json")); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java new file mode 100644 index 00000000..09ff7489 --- /dev/null +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java @@ -0,0 +1,157 @@ +package p.studio.compiler.backend.irvm; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.compiler.backend.bytecode.*; +import p.studio.compiler.lifecycle.LifecycleAssemblerService; +import p.studio.compiler.messages.*; +import p.studio.compiler.models.*; +import p.studio.compiler.models.registry.IRRegistry; +import p.studio.compiler.pbs.PbsFrontendCompiler; +import p.studio.compiler.pbs.lexer.PbsLexer; +import p.studio.compiler.pbs.parser.PbsParser; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.compiler.source.identifiers.*; +import p.studio.compiler.source.tables.*; +import p.studio.utilities.structures.ReadOnlyList; +import java.nio.file.*; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + +class PbsGuestLifecycleTest { + private static Path directory() { return Path.of(System.getProperty("pbs.registryConformanceDirectory")); } + private static final String BASE = """ + declare global trace: int = 0; + declare global inits: int = 0; + declare global stage: int = 0; + declare global kept: array = new array(1); + fn BeforePause() -> void {} + fn BeforeResume() -> void {} + [Init] fn init() -> void { inits += 1; stage = 10; kept[0] = 7; } + fn effect(delta: int) -> void { + let action = fn [delta]() -> int { return delta; }; + kept[0] = (kept[0] else 0) + action(); + } + fn readTrace() -> int { return trace * 10000 + inits * 100 + (kept[0] else 0); } + [Frame] fn frame() -> void { + if inits != 1 or stage == 20 { let fail = 1 / 0; } + stage = 10; + FRAME_BODY + } + """; + private static String pause() { return """ + [BeforePause] fn arbitraryPauseName() -> void { + if stage != 10 { let fail = 1 / 0; } + stage = 20; trace = trace * 10 + 2; effect(2); + } + """; } + private static String resume(boolean hasPause) { return """ + [BeforeResume] fn arbitraryResumeName() -> void { + if stage != EXPECTED { let fail = 1 / 0; } + stage = 30; trace = trace * 10 + 3; effect(3); + } + """.replace("EXPECTED", hasPause ? "20" : "10"); } + + private static void compile(String name, String source, boolean pause, boolean resume) throws Exception { + var diagnostics = DiagnosticSink.empty(); var id = new FileId(0); var moduleId = new ModuleId(0); + var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics); + var file = new PbsFrontendCompiler().compileParsedFile(id, ast, diagnostics, SourceKind.PROJECT, moduleId, + ReadOnlyList.from(new ModuleReference("test", ReadOnlyList.from("main"))), + HostAdmissionContext.permissiveDefault(), FESurfaceContext.empty(), new NameTable()); + assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList().toString()); + var aggregator = IRBackend.aggregator(); aggregator.merge(file); + var backend = aggregator.lifecycleModuleOrder(ReadOnlyList.from(moduleId)).emit(); + var issues = BuildingIssueSink.empty(); + var assembled = new LifecycleAssemblerService().assemble(backend, issues); + assertFalse(issues.hasErrors(), issues.asCollection().toString()); + Files.createDirectories(directory()); + Files.writeString(directory().resolve("pbs-lifecycle-"+name+".pbs"), source); + for (boolean optimize : new boolean[]{false, true}) { + var program = new LowerToIRVMService().lower(assembled); + if (optimize) program = new OptimizeIRVMService().optimize(program); + var output = new BytecodeEmitter().emit(program.coherentEmissionPlan()); + assertEquals(IRRegistry.Role.NONE, output.functions().get(0).metadata().role()); + for (var role : List.of(IRRegistry.Role.BEFORE_PAUSE, IRRegistry.Role.BEFORE_RESUME)) { + int found = 0; + for (int i = 0; i < output.functions().size(); i++) { + var metadata = output.functions().get(i).metadata(); + if (metadata.role() != role) continue; + found++; assertNotEquals(0, i); + assertTrue(metadata.signature().parameters().isEmpty()); + assertTrue(metadata.signature().results().isEmpty()); + assertTrue(metadata.captures().isEmpty()); + } + assertEquals((role == IRRegistry.Role.BEFORE_PAUSE ? pause : resume) ? 1 : 0, found); + } + new BytecodePreloadVerifierService().verify(output); + var prefix = "pbs-lifecycle-"+name+(optimize ? "-optimized" : ""); + Files.write(directory().resolve(prefix+".pbx"), output.serialize()); + for (int i = 0; i < program.module().functions().size(); i++) { + if (program.module().functions().get(i).name().contains("readTrace")) { + Files.writeString(directory().resolve(prefix+".probe"), Integer.toString(i)); + } + } + if (pause || resume) assertTrue(program.module().functions().stream().anyMatch(f -> f.name().contains("effect"))); + } + } + + @Test void sourceHooksSurviveAssemblyOptimizationAndExecuteWithNoCallers() throws Exception { + for (var name : List.of("both", "pause", "resume", "none")) { + boolean p = name.equals("both") || name.equals("pause"), r = name.equals("both") || name.equals("resume"); + // A pause-only image legitimately resumes without a hook resetting its guest stage. + var base = BASE.replace("FRAME_BODY", ""); + if (!r) base = base.replace(" or stage == 20", ""); + compile(name, base + (p ? pause() : "") + (r ? resume(p) : ""), p, r); + } + compile("direct", BASE.replace("FRAME_BODY", "arbitraryPauseName(); arbitraryResumeName();") + pause() + resume(true), true, true); + compile("trap", BASE.replace("FRAME_BODY", "") + pause().replace("effect(2);", "effect(2); let fail = 1 / 0;") + resume(true), true, true); + compile("fuel", BASE.replace("FRAME_BODY", "") + pause().replace("effect(2);", "effect(2); while true { stage = 20; }") + resume(true), true, true); + compile("slices", BASE.replace("FRAME_BODY", "") + pause().replace("effect(2);", "effect(2); for i: int from 0 until 20000 { stage = 20; }") + resume(true), true, true); + } + + @Test void importedHooksAreUniqueByDeclarationAndDoNotRequireFrameColocation(@TempDir Path root) throws Exception { + Files.createDirectories(root.resolve("src/hooks")); Files.createDirectories(root.resolve("src/facade")); + Files.writeString(root.resolve("prometeu.json"), """ + {"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]} + """); + Files.writeString(root.resolve("src/mod.barrel"), "pub fn frame() -> void;"); + Files.writeString(root.resolve("src/hooks/mod.barrel"), "pub fn selected() -> void;"); + Files.writeString(root.resolve("src/hooks/main.pbs"), "[BeforePause] fn selected() -> void {}"); + Files.writeString(root.resolve("src/facade/mod.barrel"), "pub fn selected() -> void;"); + Files.writeString(root.resolve("src/facade/main.pbs"), "import { selected } from @app:hooks;"); + Files.writeString(root.resolve("src/main.pbs"), """ + import { selected as first } from @app:hooks; + import { selected as second } from @app:facade; + [Frame] fn frame() -> void {} + """); + var result = project(root); + assertFalse(result.diagnostics().stream().anyMatch(d -> d.isError()), result.diagnostics().toString()); + Files.write(directory().resolve("pbs-lifecycle-imports.pbx"), result.bytecodeBytes()); + Files.writeString(root.resolve("src/duplicate.pbs"), "[BeforePause] fn conflicting() -> void {}"); + var conflict = p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze( + BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString())), p.studio.utilities.logs.LogAggregator.empty()); + assertTrue(conflict.diagnostics().stream().anyMatch(d -> d.isError() && d.getMessage().contains("BeforePause")), conflict.diagnostics().toString()); + } + + private static CompileResult project(Path root) { + return p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile( + BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString())), p.studio.utilities.logs.LogAggregator.empty()); + } + + @Test void syntheticPbxSyncFixturesCoverDirectAndTransitiveRejection() throws Exception { + // Independently labeled binary fixtures: PBS intentionally has no sync syntax. + for (boolean transitive : new boolean[]{false, true}) { + byte[] code = transitive ? new byte[]{0x51,0, 0x50,0,2,0,0,0, 0x51,0, (byte)0x80,0, 0x51,0} + : new byte[]{0x51,0, (byte)0x80,0, 0x51,0}; + var functions = new java.util.ArrayList(); + functions.add(new BytecodeModule.FunctionMeta(0,2,0,0,0,0,IRRegistry.FunctionMetadata.empty())); + functions.add(new BytecodeModule.FunctionMeta(2,transitive ? 8 : 4,0,0,0,0, + new IRRegistry.FunctionMetadata(IRRegistry.Signature.empty(),null,IRRegistry.Role.BEFORE_PAUSE))); + if (transitive) functions.add(new BytecodeModule.FunctionMeta(10,4,0,0,0,0,IRRegistry.FunctionMetadata.empty())); + var module = new BytecodeModule(0,null,ReadOnlyList.wrap(functions),code,null,null,null,IRRegistry.empty()); + new BytecodePreloadVerifierService().verify(module); + Files.createDirectories(directory()); + Files.write(directory().resolve("synthetic-lifecycle-sync-"+(transitive ? "transitive" : "direct")+".pbx"),module.serialize()); + } + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSSemanticTokenProvider.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSSemanticTokenProvider.java index fdf67b3b..94f91d3e 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSSemanticTokenProvider.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSSemanticTokenProvider.java @@ -353,7 +353,7 @@ public final class PBSSemanticTokenProvider implements FrontendSemanticTokenProv final ReadOnlyList tokens, final int index, final PbsToken token) { - if (!"Init".equals(token.lexeme()) && !"Frame".equals(token.lexeme())) { + if (PbsAst.LifecycleMarker.forAttribute(token.lexeme()) == PbsAst.LifecycleMarker.NONE) { return false; } if (index == 0 || index + 1 >= tokens.size()) { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java index 530982d4..0186228f 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java @@ -133,9 +133,24 @@ public final class PbsAst { } public enum LifecycleMarker { - NONE, - INIT, - FRAME + NONE(""), + INIT("Init"), + FRAME("Frame"), + BEFORE_PAUSE("BeforePause"), + BEFORE_RESUME("BeforeResume"); + + private final String attributeName; + + LifecycleMarker(String attributeName) { this.attributeName = attributeName; } + + public String attributeName() { return attributeName; } + + public static LifecycleMarker forAttribute(String name) { + for (var marker : values()) { + if (marker != NONE && marker.attributeName.equals(name)) return marker; + } + return NONE; + } } public record FunctionDecl( diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java index 1a0fab1a..f3fe1878 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java @@ -231,7 +231,11 @@ final class PbsRuntimeTypes { var returns=f.returnKind()==PbsAst.ReturnKind.PLAIN ? results(f.returnType()) : List.of(); var captures = capturesByFunction.getOrDefault(f.name(), List.of()).stream().flatMap(c -> results(c.typeRef()).stream()).toList(); return new IRRegistry.FunctionMetadata(new IRRegistry.Signature(ReadOnlyList.wrap(params),ReadOnlyList.wrap(returns)), - ReadOnlyList.wrap(captures), IRRegistry.Role.NONE); + ReadOnlyList.wrap(captures), switch (f.lifecycleMarker()) { + case BEFORE_PAUSE -> IRRegistry.Role.BEFORE_PAUSE; + case BEFORE_RESUME -> IRRegistry.Role.BEFORE_RESUME; + default -> IRRegistry.Role.NONE; + }); } IRRegistry registry() { return new IRRegistry(ReadOnlyList.wrap(new ArrayList<>(used.values())),ReadOnlyList.wrap(runtimeImplementations)); } Integer enumValue(String owner,String label) { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java index fc939c6d..8cce5f3d 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java @@ -170,7 +170,7 @@ final class PbsDeclarationParser { PbsAst.FunctionDecl parseFunction( final PbsToken fnToken, final ReadOnlyList pendingAttributes) { - return parseFunctionLike(fnToken, pendingAttributes); + return parseFunctionLike(fnToken, pendingAttributes, true); } PbsAst.ImplementsDecl parseImplementsDeclaration(final PbsToken implementsToken) { @@ -570,7 +570,18 @@ final class PbsDeclarationParser { private PbsAst.FunctionDecl parseFunctionLike( final PbsToken fnToken, final ReadOnlyList pendingAttributes) { - final var lifecycleMarker = validateAndResolveLifecycleMarker(pendingAttributes); + return parseFunctionLike(fnToken, pendingAttributes, false); + } + + private PbsAst.FunctionDecl parseFunctionLike( + final PbsToken fnToken, + final ReadOnlyList pendingAttributes, + final boolean topLevel) { + var lifecycleMarker = validateAndResolveLifecycleMarker(pendingAttributes); + if (!topLevel && lifecycleMarker != PbsAst.LifecycleMarker.NONE) { + reportAttributesNotAllowed(pendingAttributes, "Lifecycle markers are valid only on top-level userland functions"); + lifecycleMarker = PbsAst.LifecycleMarker.NONE; + } final var name = consumeCallableName(); final var typeParameters = typeParser.parseTypeParameters(); consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after function name"); @@ -731,12 +742,9 @@ final class PbsDeclarationParser { reportAttributesNotAllowed(attributes, "Only [Doc] is allowed before interface executable methods"); return PbsAst.LifecycleMarker.NONE; } - if ("Init".equals(attribute.name())) { - nextMarker = PbsAst.LifecycleMarker.INIT; - } else if ("Frame".equals(attribute.name())) { - nextMarker = PbsAst.LifecycleMarker.FRAME; - } else { - reportAttributesNotAllowed(attributes, "Only marker attributes [Init] and [Frame] are allowed before top-level functions"); + nextMarker = PbsAst.LifecycleMarker.forAttribute(attribute.name()); + if (nextMarker == PbsAst.LifecycleMarker.NONE) { + reportAttributesNotAllowed(attributes, "Only [Doc] and lifecycle markers [Init], [Frame], [BeforePause], [BeforeResume] are allowed before top-level functions"); return PbsAst.LifecycleMarker.NONE; } @@ -746,7 +754,7 @@ final class PbsDeclarationParser { } if (marker != PbsAst.LifecycleMarker.NONE && marker != nextMarker) { - reportAttributesNotAllowed(attributes, "Top-level functions cannot combine [Init] and [Frame]"); + reportAttributesNotAllowed(attributes, "Top-level functions cannot combine lifecycle markers"); return PbsAst.LifecycleMarker.NONE; } marker = nextMarker; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java index 0d174435..2f9ec29f 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java @@ -969,7 +969,7 @@ public final class PbsDeclarationSemanticsValidator { } private boolean isReservedAttribute(final String name) { - return RESERVED_ATTRIBUTES.contains(name); + return RESERVED_ATTRIBUTES.contains(name) || PbsAst.LifecycleMarker.forAttribute(name) != PbsAst.LifecycleMarker.NONE; } private void validateReservedAttributeTarget( diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsLifecycleSemanticsValidator.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsLifecycleSemanticsValidator.java index d37f3a3e..c5185fa0 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsLifecycleSemanticsValidator.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsLifecycleSemanticsValidator.java @@ -45,7 +45,8 @@ public final class PbsLifecycleSemanticsValidator { private void validateLifecycleSignature( final PbsAst.FunctionDecl functionDecl, final p.studio.compiler.source.diagnostics.DiagnosticSink diagnostics) { - final var valid = functionDecl.parameters().isEmpty() + final var valid = functionDecl.typeParameters().isEmpty() + && functionDecl.parameters().isEmpty() && functionDecl.returnKind() == PbsAst.ReturnKind.EXPLICIT_UNIT && functionDecl.returnType() != null && functionDecl.returnType().kind() == PbsAst.TypeRefKind.UNIT @@ -56,8 +57,8 @@ public final class PbsLifecycleSemanticsValidator { p.studio.compiler.source.diagnostics.Diagnostics.error( diagnostics, PbsSemanticsErrors.E_SEM_INVALID_LIFECYCLE_SIGNATURE.name(), - "Lifecycle functions marked with [%s] must have signature 'fn name() -> void'".formatted( - functionDecl.lifecycleMarker() == PbsAst.LifecycleMarker.INIT ? "Init" : "Frame"), + "Lifecycle functions marked with [%s] must be non-generic with signature 'fn name() -> void'".formatted( + functionDecl.lifecycleMarker().attributeName()), functionDecl.span()); } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSemanticsErrors.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSemanticsErrors.java index a24539b6..bbe35e4f 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSemanticsErrors.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSemanticsErrors.java @@ -18,6 +18,7 @@ public enum PbsSemanticsErrors { E_SEM_INVALID_LIFECYCLE_SIGNATURE, E_SEM_DUPLICATE_FILE_INIT, E_SEM_DUPLICATE_PROJECT_FRAME, + E_SEM_DUPLICATE_LIFECYCLE_ROLE, E_SEM_MISSING_PROJECT_FRAME, E_SEM_INIT_HOST_CALL_NOT_ALLOWED, E_SEM_MISSING_CONST_TYPE_ANNOTATION, diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsProjectLifecycleSemanticsValidator.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsProjectLifecycleSemanticsValidator.java index f75ded0f..12a1d879 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsProjectLifecycleSemanticsValidator.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsProjectLifecycleSemanticsValidator.java @@ -13,6 +13,8 @@ final class PbsProjectLifecycleSemanticsValidator { final java.util.List parsedSourceFiles, final DiagnosticSink diagnostics) { final var frames = new ArrayList(); + final var hooks = new java.util.EnumMap(PbsAst.LifecycleMarker.class); + final var declarations = new java.util.HashSet(); var sawExecutableSource = false; for (final var parsedSource : parsedSourceFiles) { @@ -24,6 +26,23 @@ final class PbsProjectLifecycleSemanticsValidator { if (!(topDecl instanceof PbsAst.FunctionDecl functionDecl)) { continue; } + final var span = functionDecl.span(); + if (!declarations.add(span.getFileId().getId() + ":" + span.getStart() + ":" + span.getEnd())) { + continue; + } + final var marker = functionDecl.lifecycleMarker(); + if (marker == PbsAst.LifecycleMarker.BEFORE_PAUSE || marker == PbsAst.LifecycleMarker.BEFORE_RESUME) { + final var previous = hooks.putIfAbsent(marker, functionDecl); + if (previous != null) { + p.studio.compiler.source.diagnostics.Diagnostics.error( + diagnostics, + PbsSemanticsErrors.E_SEM_DUPLICATE_LIFECYCLE_ROLE.name(), + "Only one [%s] target is allowed per image: '%s' conflicts with '%s' (file %d, span %d..%d)".formatted( + marker.attributeName(), functionDecl.name(), previous.name(), + previous.span().getFileId().getId(), previous.span().getStart(), previous.span().getEnd()), + span); + } + } if (functionDecl.lifecycleMarker() == PbsAst.LifecycleMarker.FRAME) { frames.add(functionDecl); } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/LIFECYCLE.md b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/LIFECYCLE.md new file mode 100644 index 00000000..67042926 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/LIFECYCLE.md @@ -0,0 +1,20 @@ +# Controlled pause and resume + +`src/lifecycle.pbs` declares both optional hooks. Each marker selects one +nongeneric top-level function with no parameters, results or captures. It can +be in a different file from `[Frame]`. Names are arbitrary; globals are shared +game state, not captures. Normal closures remain usable inside a hook. + +Home's existing handoff completes before BeforePause, which returns before +suspension. BeforeResume runs after reactivation and before the next gameplay +instruction. Runtime preserves the continuation, globals and init guard; +resume does not rerun Init. Each hook has bounded virtual fuel and cannot sync, +including through its callees. A fatal failure blocks the session. + +Calling `preparePause()` directly runs an ordinary function; it does not pause +the game or acquire the OS controlled-call context. To share work, an ordinary +helper can be called from gameplay and hooks. A marker does not grant service +capabilities or perform automatic saving, flushing or disk waiting. + +MemcardBoot and persistence have a separate contract. These two markers do not +select MemcardBoot or define a termination hook. diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/lifecycle.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/lifecycle.pbs new file mode 100644 index 00000000..b43b5664 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/lifecycle.pbs @@ -0,0 +1,18 @@ +// These functions are selected by attributes, independently of their names. +// Globals belong to the game state; they are not function captures. +declare global pauseCount: int = 0; +declare global resumeCount: int = 0; + +[BeforePause] +fn preparePause() -> void { + pauseCount += 1; +} + +[BeforeResume] +fn prepareResume() -> void { + resumeCount += 1; +} + +fn lifecycleExample() -> int { + return pauseCount + resumeCount; +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel index c582905b..e8973e1a 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel @@ -8,3 +8,4 @@ pub fn setExample() -> int; pub fn hashingExample() -> int; pub fn mapsExample() -> int; pub fn stackQueueExample() -> int; +pub fn lifecycleExample() -> int; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PbsGuestLifecycleSemanticsTest.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PbsGuestLifecycleSemanticsTest.java new file mode 100644 index 00000000..8e35d07e --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PbsGuestLifecycleSemanticsTest.java @@ -0,0 +1,90 @@ +package p.studio.compiler.services; + +import org.junit.jupiter.api.Test; +import p.studio.compiler.PBSSemanticTokenProvider; +import p.studio.compiler.models.SourceKind; +import p.studio.compiler.pbs.PbsFrontendCompiler; +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.compiler.pbs.lexer.PbsLexer; +import p.studio.compiler.pbs.parser.PbsParser; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.compiler.source.identifiers.FileId; +import p.studio.compiler.source.identifiers.ModuleId; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + +class PbsGuestLifecycleSemanticsTest { + @Test void permitsGlobalsClosuresAndDocOnBothHooks() { + var source = """ + declare global state: int = 0; + [Doc(markdown = \"\"\"Pause preparation.\"\"\")] + [BeforePause] fn arbitraryName() -> void { + let delta = 2; + let effect = fn [delta]() -> int { return delta; }; + state += effect(); + } + [BeforeResume] fn anotherName() -> void { state += 3; } + """; + var diagnostics = DiagnosticSink.empty(); + new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics); + assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getMessage()).toList().toString()); + var tokens = new PBSSemanticTokenProvider().tokenize(source); + for (var name : List.of("BeforePause", "BeforeResume")) { + assertTrue(tokens.stream().anyMatch(t -> t.startOffset() == source.indexOf(name) && t.semanticKey().equals("pbs-lifecycle"))); + } + } + + @Test void rejectsInvalidSourceSurfacesWithSourceLocations() { + for (var marker : List.of("BeforePause", "BeforeResume")) { + for (var source : List.of( + "["+marker+"] fn bad(x: int) -> void {}", + "["+marker+"] fn bad() -> int { return 1; }", + "["+marker+"] fn bad() -> void {}", + "["+marker+"(value = 1)] fn bad() -> void {}", + "["+marker+"][Init] fn bad() -> void {}", + "["+marker+"][Frame] fn bad() -> void {}", + "[BeforePause][BeforeResume] fn bad() -> void {}", + "declare struct Box() { ["+marker+"] fn bad() -> void {} }", + "declare service Box { ["+marker+"] fn bad() -> void {} }", + "declare contract Box { ["+marker+"] fn bad() -> void; }", + "["+marker+"] declare global bad: int = 0;")) { + var diagnostics = DiagnosticSink.empty(); + new PbsFrontendCompiler().compileFile(new FileId(7), source, diagnostics); + assertTrue(diagnostics.hasErrors(), source); + assertTrue(diagnostics.stream().anyMatch(d -> d.getSpan().getFileId().getId() == 7 + && d.getSpan().getEnd() > d.getSpan().getStart()), source); + } + var diagnostics = DiagnosticSink.empty(); + var id = new FileId(8); + PbsParser.parse(PbsLexer.lex("["+marker+"] fn bad() -> void {}", id, diagnostics), id, diagnostics, + PbsParser.ParseMode.INTERFACE_MODULE); + assertTrue(diagnostics.hasErrors()); + } + } + + private PbsParsedSourceFile file(int id, String source) { + var file = new FileId(id); + var diagnostics = DiagnosticSink.empty(); + var ast = PbsParser.parse(PbsLexer.lex(source, file, diagnostics), file, diagnostics); + assertFalse(diagnostics.hasErrors()); + return new PbsParsedSourceFile(file, ast, new ModuleId(id), SourceKind.PROJECT); + } + + @Test void uniquenessIsPerImageAndRepeatedDeclarationsAreNotCountedTwice() { + var frame = file(0, "[Frame] fn frame() -> void {}"); + for (var marker : List.of("BeforePause", "BeforeResume")) { + var first = file(1, "["+marker+"] fn first() -> void {}"); + var second = file(2, "["+marker+"] fn second() -> void {}"); + var diagnostics = DiagnosticSink.empty(); + new PbsProjectLifecycleSemanticsValidator().validate(List.of(frame, first, first), diagnostics); + assertFalse(diagnostics.hasErrors()); + new PbsProjectLifecycleSemanticsValidator().validate(List.of(frame, first, second), diagnostics); + var duplicates = diagnostics.stream().filter(d -> d.getCode().equals("E_SEM_DUPLICATE_LIFECYCLE_ROLE")).toList(); + assertEquals(1, duplicates.size()); + assertEquals(2, duplicates.getFirst().getSpan().getFileId().getId()); + assertTrue(duplicates.getFirst().getMessage().contains("first")); + assertTrue(duplicates.getFirst().getMessage().contains("second")); + assertTrue(duplicates.getFirst().getMessage().contains(marker)); + } + } +} diff --git a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/PbxRegistryConformanceTest.java b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/PbxRegistryConformanceTest.java index 42b8f8a7..f28a5a1f 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/PbxRegistryConformanceTest.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/PbxRegistryConformanceTest.java @@ -161,6 +161,23 @@ class PbxRegistryConformanceTest { var duplicated=ReadOnlyList.from(functions.get(0),functions.get(1),new BytecodeModule.FunctionMeta(4,2,0,0,0,0,pause)); assertThrows(BytecodeMarshalingException.class,()->new BytecodeModule(0,null,duplicated,m.code(),null,null,null,m.registry()).serialize()); } + @Test void pauseAndResumeRejectTypedParametersResultsAndCaptures() { + var integer = TypeRef.builtin(0x10); + for (var role : List.of(Role.BEFORE_PAUSE, Role.BEFORE_RESUME)) { + var signatures = List.of( + new Signature(ReadOnlyList.from(new NamedType(integer,"unexpected")),null), + new Signature(null,ReadOnlyList.from(integer)), Signature.empty()); + for (int n=0;n Vec { + 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"); +} diff --git a/tools/pbx-conformance/main.rs b/tools/pbx-conformance/main.rs index 42abd38e..89796ae5 100644 --- a/tools/pbx-conformance/main.rs +++ b/tools/pbx-conformance/main.rs @@ -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 [ diff --git a/tools/pbx-conformance/run.py b/tools/pbx-conformance/run.py index 8bc97b94..3d60c6e0 100644 --- a/tools/pbx-conformance/run.py +++ b/tools/pbx-conformance/run.py @@ -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)