7.1 KiB
id, ticket, title, created, tags
| id | ticket | title | created | tags | |
|---|---|---|---|---|---|
| LSN-0062 | gameplay-math-and-numeric-semantics | Portable Math Requires a Runtime-Owned Numeric Contract | 2026-10-09 |
|
Context
Gameplay code can be produced on one computer and executed by different hosts. That portability depends on preserving numeric behavior in the runtime that executes the cartridge. A frontend-only math implementation would make different producers responsible for agreeing on details that affect game state.
This lesson derives from accepted decision DEC-0048, implemented through PLN-0179. The published normative result is Gameplay Math and Numeric Semantics. The discussion lifecycle remains in the index. The qualification record contains executed evidence, configuration and remaining host comparisons.
Key Decisions
Own observable numeric behavior in the VM
What: Guest Float operations, conversions and math use the same binary64 software adapter. Runtime metadata owns exact signatures, argument names, identities, constants, flags and fixed virtual costs. The intended frontend projection uses math for integers and mathf for Float.
Why: Producers select an exact identity and emit a call; the runtime determines the result. The frontend does not become a second numeric engine.
Trade-offs: Software execution costs CPU time. The measured direct-call costs range from tens of nanoseconds for dot to microseconds for atan2 on the available machine. Those measurements do not alter guest-visible cycle costs. Frontend projection and integration remain a separate delivery.
Separate reproducibility from mathematical accuracy
What: Result bits, faults and virtual cycles must agree exactly between qualified runtime builds. The mathematical reference comparison separately checks correct rounding or the prescribed strict error bound.
Why: Two results can both satisfy a mathematical error bound and still drive different simulation branches. Approximation quality does not establish reproducibility.
Trade-offs: Backend/dependency changes require a new qualification baseline. Recognizing the unchanged vec2 v1 identities alone does not qualify an older runtime for the revised operation sequence.
Specify composite operations as sequences
What: dot rounds and checks two products and their sum separately. length uses a scaled sequence of division, multiplication, addition and sqrt.
Why: Avoiding overflow by scaling improves useful input coverage, while specifying every step prevents FMA, wider accumulators or library hypot from silently changing observable bits or faults.
Trade-offs: A prescribed sequence need not equal the single correctly rounded ideal composite function. Intermediate overflow remains observable, even if a hypothetical wider calculation would cancel it.
Patterns and Algorithms
Keep f64 as bit transport. SoftF64 delegates arithmetic/comparison to APFloat; the adapter owns finite admission, signed-zero rules, domain/range faults and explicit integer conversions. Integer-to-Float conversion rounds significand bits with ties to even. Float-to-integer conversion truncates the exact represented value before checking destination bounds.
Validate all declared carriers before all nonfinite parameters, then domain and result range. Reject invalid Float constants and immediate instructions at loading, including unreachable code. Native signature import and public stack import prevent NaN/infinity from entering guest state.
Charge a known mathematical attempt once before validation or scratch reservation. Failed attempts retain the same cost. Zero budget starts no instruction; positive budget can admit a complete operation and overshoot. Keep this independent of actual CPU latency and unchanged unrelated opcode accounting.
Generate consumer catalogs from runtime descriptors and compare checked-in exports to that source in tests. Publishing exact parameter order is especially useful for atan2(y,x), explicit conversions and named-argument lowering.
Use an independent MPFR oracle with exact imports, directed intervals and adaptive precision. Importing a decimal rendering can test the wrong input. Binary64 exponent limits and gradual underflow matter as much as precision. For composite sequences, round each reference step in the same binary64 model.
Pitfalls
- Upstream round uses ties away from zero; matching a function name did not make it compatible with the runtime's ties-to-even contract.
- Int64 MAX rounds to +2^63 as Float. Using that rounded value as an inclusive cast bound would accept an out-of-range conversion; saturating casts would hide the error.
- Signed zeros affect min/max, rounding, axes and vector results despite comparing equal numerically.
- A remainder against approximate tau does not provide the required reduction for every large finite angle.
- Taking abs after an upward-rounded negative subtraction can underestimate an oracle error bound. Round positive endpoint distances upward instead.
- The existing payload-preservation tests used NaN bit patterns. Finite subnormal patterns preserve their original bit-transport coverage, while separate tests assert the new rejection contract.
- An x86_64 oracle process on the same Mac is not x86_64 runtime execution. Cross-compilation and local debug/release equality also do not replace empirical comparison between runtime architectures.
Delivered Evidence and Handoffs
Local macOS/aarch64 dev/release qualification passed 380,946 MPFR cases per profile with identical corpus bytes. The largest sampled strict error upper bounds were approximately 0.733 ULP for sin, 0.699 for cos and 0.514 for atan2. The checked-in 4,747-row fixture runs without MPFR. All 907 workspace tests passed, with nine existing ignored tests; formatting and Clippy passed. The 14 numeric contract tests passed in both debug and release. Sampling plus source/upstream review supports this local baseline without claiming an exhaustive proof over binary64.
Remaining host validation targets macOS/x86_64 and Linux/x86_64 headless. Acceptance requires passing the same oracle/contract tests in debug/release and matching the complete corpus bits, faults and cycles to the published hash. These runs await available infrastructure; the local delivery did not execute or certify them.
The frontend handoff is to consume the runtime catalogs, implement namespace projection and exact overload selection, preserve ordered arguments and calls with literal inputs, and use canonical constant bits. The published spec contains consumer/emission examples. No frontend code or frontend integration tests were implemented in this delivery.
Takeaways
- Deterministic math is a runtime execution contract, including faults and cost.
- Mathematical accuracy and exact agreement between hosts need separate gates.
- Explicit composite sequences and conversion bounds prevent hidden changes.
- Keep local evidence useful and reproducible while naming unexecuted hosts and consumer integration precisely.