67 lines
15 KiB
Markdown
67 lines
15 KiB
Markdown
# Contract runtime dispatch and context candidate
|
|
|
|
Non-normative continuation of [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), [AIR bindings](contract-air-bindings.md) and [invariant boundaries](contract-invariant-boundaries.md). This completes a candidate runtime rule, not an implementation or a feature/code allocation. Format-0 compatibility, source reasons, owner adoption and vertical delivery remain gates.
|
|
|
|
## Continuations and publication
|
|
|
|
A frame retains an explicit continuation describing the invocation it is awaiting: ordinary call, pre, old, post index with pending return, make validation, modify callback or modify validation. Record the installing instruction, evaluated boundary and helper identity as module indices; never infer this from its opcode after an ordinary result assignment. Parent frames remain active until their pending operation/return completes. Returning from a helper goes through the saved continuation rather than the current ordinary `caller result; inst += 1` path. Continuations are per task and frame, with at most one pending operation in each frame; nested callbacks/calls use the ordinary frame stack, not an unbounded side stack.
|
|
|
|
| Initiating instruction | State until helper completion | Successful completion |
|
|
|---|---|---|
|
|
| pre, runtime/assume | invocation views/places, bool helper | inspect bool, end temporary observations, advance prefix once |
|
|
| old | invocation views/places, Data helper | end observations, save one snapshot, advance prefix once |
|
|
| post, any mode | install ordered metadata, no evaluation | advance prefix once |
|
|
| ret with executable posts | retain frame, exact ret and pending value; select first executable post | finish normal return only after every executable post succeeds |
|
|
| checked.make | retain unexposed complete R and whole-R observation | end observation, form checked value and bind result once |
|
|
| checked.modify | retain capsule root, suspend its access; invoke callback through temporary mut<R> | retain callback result, end mutation loan, invoke p through shared whole-R observation; bind callback result only after p succeeds |
|
|
|
|
Pre.document is a paid metadata operation with no helper. Post.document installs metadata but is skipped by return-time dispatch. Proven runtime clauses still execute. Old executes once after all pre groups; documented old notation only reuses the existing snapshot. A callback returning never never reaches validation/publication. Void callbacks carry a pending void value. Normal cleanup is the explicit AIR that preceded ret, not hidden work in these continuations.
|
|
|
|
A helper ret is charged as an ordinary instruction; the same step inspects its bool/Data result and performs its continuation. A false bool stops immediately, before scheduling or beginning another instruction. A true final post completes the original ret: end temporary observations, remove the contracted frame, transfer the pending value to the caller's saved continuation, or mark the task done and expose its result. Task.join cannot observe a pending value. Main completes only at this point. Cascaded completion uses an iterative dispatcher: every transition consumes a completed helper, advances a finite clause list or completes a frame; it cannot reexecute a paid ret or spin through a cyclic continuation.
|
|
|
|
A callback's successful return is not a successful modify. The callback frame ends before the validation frame is pushed, so they do not count simultaneously. Its borrow-free result, including a linear owner, is retained but unavailable to the caller until validation succeeds. No callback mutation or external effect is rolled back on failure. Trap, fuel/task limit and blocked outcomes grant no completed checked/postcondition claim. A failure ends the whole program under format-0 policy, including failure in a child task; no destructor, unwind, rollback, join or cleanup callback is invented.
|
|
|
|
## Fuel, depth and scheduling
|
|
|
|
Every textual instruction pays one fuel and quantum unit when it begins, including all document prefix operations, post installation, ret, make and modify. Helper/callback instructions pay separately. Pushing a helper, processing its returned value, advancing to the next predicate and completing a pending return add no synthetic instruction/unit. Before pushing any helper/callback apply the ordinary 1,024-active-frame bound; a contracted parent still counts. The dispatcher performs that check explicitly, not only through the ordinary call opcode path.
|
|
|
|
Normalize the completed instruction's continuation before the current loop's quantum check: inspect bool, retain/publish values, end temporary loans and push the next helper when required. There is no fuel check inside this normalization. False on the last fuel unit is a trap. If the original ret or callback ret spent the last unit, a needed next predicate frame is ready, but execution stops before its first instruction with limit_exceeded. If the final predicate ret spent the last unit and succeeds, return/update completion still happens; fuel is checked only when another instruction would begin. A depth violation discovered while pushing after a paid instruction is T0007 even when no fuel remains, as with ordinary call.
|
|
|
|
After normalization apply the usual quantum rule to the still-runnable task, except that completing a task/returning main follows today's scheduling/termination path. Switching may occur after the initial ret, between predicate instructions or between callback and validation. No validation region is an atomic section; all saved values/loans must survive switching. Contract execution can change interleavings and schedule.choices; equivalence with a contract-free instruction stream is not claimed. Modes also differ in their executed instructions.
|
|
|
|
P/S operations have no newly visible synchronization/atomic/ambient operation, so prefix/install/validation dispatch adds no exploration choice or scheduler draw of its own. The existing visible operations in an unrestricted callback keep their ordinary exploration, weak-memory and cancellation behavior. Callback waiting retains its continuation and existing fuel_paid handling; resume does not repay the waiting instruction or restart callback/validation. Cancellation of the current task does not skip a predicate/post: only existing explicit cancellation operations observe it. The pending claim is never published because a scheduler selected another task.
|
|
|
|
## Execution memory and observations
|
|
|
|
GC roots include all ordinary frame values plus each frame's pending return/candidate/callback value, persistent snapshot and active observation places. Copy them with the same Copier/memoization as ordinary cells, arrays, graphs and owners, preserving aliasing, backing-frame identity, paths and race shadows. Indices into immutable module data require no execution-heap tracing. Retained runtime context must remain valid after the execution heap is released. No Value/place pointer may live solely in a Zig local across a collection, scheduling point or hosted wait.
|
|
|
|
Linear make and whole linear checked observations use an SSA-backed cell rather than a copied local. Copy observations get distinct complete temporary cells, each covered by the activation formula L+S+max E; temporary helper descendant views cannot escape. Checked representation access needs an explicit runtime representation edge/accessor, not a fake user field 0. Ordinary owner-content adaptation and whole-R validation are distinct. Collection traverses checked representation values without invoking predicates or changing fuel, authority charges, task clocks, schedules or graph identities. An old iref copies only its opaque identity/slot and does not retain a destroyed graph.
|
|
|
|
After each successful helper end its evaluation views/places; after final success bind/transfer the value once. Scratch, snapshots and pending slots are unreachable after their activation completes, except ordinary escaping ancestor storage allowed by existing borrow-return rules. GC every step must produce byte-identical records, including all context positions, to ordinary collection. Retention is bounded by active frames/verified value and activation budgets, not the number of completed calls/updates. This is a requirement for new continuations, not evidence that today's GC already visits them.
|
|
|
|
## False conditions and additive context
|
|
|
|
Candidate false codes/kinds are T0011 trap.contract_precondition, T0012 trap.contract_postcondition and T0013 trap.type_invariant. A false assumed pre/post retains T0009 trap.unsafe_precondition. The primary function/block/inst for these dispatch-generated failures is the installing pre/post or make/modify instruction; existing source_location therefore maps to the clause/checked operation. The helper ret that yielded false is retained as the context's at position. Old returns Data and has no false code. A helper/callback's own trap retains its existing code and actual innermost instruction, including arithmetic/assert/unsafe/depth traps; do not relabel it as a false condition. An implicit frame-push depth failure has the evaluated boundary as its primary instruction and at null because no helper instruction began. No trap code is allocated here.
|
|
|
|
Propose one optional `contract` object on trapped, limit_exceeded, blocked and race_detected records when the failing/current execution unit is inside an active contract evaluation. Race context identifies the same actual detected access and does not turn a verifier defect into a contract-false trap. Omit it on successful return, not_instantiated and ordinary failures outside evaluation. Existing fields/values and the relative order of existing fields remain unchanged. Object field order is:
|
|
|
|
```text
|
|
kind, mode, phase, helper, task, site, boundary, at
|
|
```
|
|
|
|
Kind is pre/post/old/make/modify. Mode is runtime for old/make/modify and ordinary pre/post, assume for assumed pre/post; document starts no active evaluation. Phase is predicate, snapshot (old) or callback (modify). Helper is the directly selected phase function name without @, not an invented source variable. Task is the actual zero-based task identity. Site is the installing prefix/checked operation. Boundary is the evaluated ret for post, otherwise the initiating operation. At is the actual failing/completing instruction; for fuel it is the next instruction prevented from beginning; for task limits/blocked/races it is the actual spawn/wait/access instruction. An implicit push-depth failure has at null. This does not claim that a fuel-stopped instruction executed.
|
|
|
|
Each non-null position is `function,block,inst`, optional file/line/col when exactly source-mapped, then mandatory air_line/air_col. Function/block are AIR names without sigils; inst is zero-based. Map every position independently using its real lowering span, including imported/template/standard-library helpers. AIR-only positions omit source coordinates. No map is inferred from a helper name; missing exact context maps stay omitted. Primary source_location retains existing behavior. A failure inside a helper's ordinary descendant call retains the innermost trap as primary/at but still identifies the directly selected evaluation helper in contract.helper.
|
|
|
|
Use the nearest active evaluation continuation in the same task. Nested callback contracts replace the reported context with their own innermost boundary; there is no unbounded dumped stack or ambiguous outer-root selection. Child tasks do not inherit the creator's active evaluation: their own contracts identify their own boundaries; an ordinary child trap carries no fabricated parent context. For global fuel, use the task selected to begin the prevented instruction. For blocked, use the existing oldest-waiter selection, including that waiter's task and continuation; unrelated pending validations are not reported as its cause.
|
|
|
|
Build/enrich typed context before JSON serialization. writeOutcome emits contract after the base outcome fields and before captured stdout/stderr/files/schedule; the CLI appends primary source_location last as today. Lowered-source position mapping must enrich each context position before serialization, rather than append a second contract object or patch nested JSON text. Position/context values reference immutable module data or result-arena-owned storage, not released execution memory. Hosted result files use the same schema and enforcement; hosted program streams remain owned by the program.
|
|
|
|
Explore keeps today's identity rule: distinct outcomes are the exact bytes produced by writeOutcome, sorted by those bytes. Include the complete AIR-only contract object in that key, task included; do not strip/normalize metadata during deduplication. Schedule-dependent task IDs or different boundaries may therefore produce distinct records for the same trap code, even when the program-visible failure is similar. This is an explicit consequence of factual outcome identity. Explore does not enrich source positions or append primary source_location today; its new context also stays AIR-only for .aji input. Normal run/hosted result mapping remains as specified above. Required tests pin enumeration/dedup/order and bounded max-runs behavior without conflating metadata-distinct records with different returned program values.
|
|
|
|
## Evidence and delivery
|
|
|
|
The [runtime vectors](contract-runtime-vectors.json) record six current-language groups at `2db752d` (16 CLI runs, quantum 1): ordinary return/fuel cuts, assertion at the last unit, depth at 1023/1024 steps, a linear owner across a returned call, exact source mapping of a helper trap, and a child assertion under five schedule seeds. Nine ordinary fixture variants pass normal-versus-GC-every-step comparison (13 schedule cases, 26 interpreter runs, race detection enabled). These executed programs contain no contracts. Six separately marked hypothetical context components pin field/position order, false versus existing trap identity, a depth-null at, callback fuel and an assumed child post. The components are schema vectors, not executed new-contract output. These show constraints on the proposed dispatcher/serializer, not successful new-contract execution.
|
|
|
|
Required vertical coverage includes pre/old/post/install/document fuel, false at the final unit, cuts before/within/between helpers, helper-depth boundaries, several returns/posts, void/never callbacks, nested callback contracts, blocked/cancelled callbacks, unexposed linear callback results, distinct Copy places, graph/owner/checked pending roots under GC every step, joined workers and quantum/weak-memory exploration. Preserve contract-free bytes. New false codes, exact typed context and continuation state must land in spec/reference, verifier/interpreter, source/formatter/Quick Reference and AIR/source conformance together; these research rules alone do not complete P6-6.
|