rfc: specify contract prefix and invariant publication constraints

This commit is contained in:
dev committed 2026-10-09 07:14:41 +03:00
1 parent 11725ad1c3
commit 8cd933538b
3 files changed
+61 -13

No files matched your search

+49 -13
View File
@@ -29,9 +29,9 @@ fn main() -> u64 effects [] { return positive(0u64); }
After the same `module` header, both accepted variants produce identical `aji report` JSON. With fuel 10,000, A traps T0002 and B returns zero. A check count cannot establish mandatory coverage.
An `effects []` function taking `mut<u64>` can write through it and return 42; calling it inside `assert` is accepted. Even a no-parameter effects-empty function can call `task.cancelled()` and observe ambient state. Empty effects or parameter restrictions alone do not establish observational purity. Borrowing an owner after `own.take(move owner)` rejects E3001; a postcondition cannot resurrect that owner.
An `effects []` function taking `mut<u64>` can write through it and return 42; calling it inside `assert` is accepted. Even a no-parameter effects-empty function can call `task.cancelled()` and observe ambient state. Empty effects or parameter restrictions alone do not establish observational purity. Borrowing an owner after `own.take(move owner)` rejects E3001; a postcondition cannot resurrect that owner. Conversely, an ordinary shared observation in a nested block before returning `move owner` is accepted; a caller taking the returned owner gets 42. Availability must be checked at the boundary, not banned solely because a parameter is linear.
A candidate AIR `requires @predicate(%x)` header without a new feature rejects E0001 today; declaring unknown feature `contracts` instead rejects E0006 first. This difference matters to format-0 compatibility.
A candidate AIR `requires @predicate(%x)` header without a new feature rejects E0001 today; declaring unknown feature `contracts` instead rejects E0006 first. In contrast, each proposed `contract.pre`, `contract.old` and `contract.post` operation rejects E0004. A snapshot used by a post reports only E0004 for those two operations. Using the unknown `%old` result in an ordinary body instruction additionally reports E5001; the candidate also rejects that snapshot escape. The prefix is an opcode-extension candidate; these probes do not yet prove complete format-0 compatibility.
The intended gains are verifier strength, explicit guarantees and truthful machine-readable audit status. No empirical agent-capability improvement is established.
@@ -45,19 +45,43 @@ Preconditions cover every invocation, including entry instantiation, recursion a
The candidate source spelling is `requires { condition; }` and `ensures { condition; }`, after `effects [...]` and before the body. This retains blocks but deliberately moves the clauses and adds terminators compared with spec 13's illustrative example. Each condition is bool. These words are contextual in headers; `result` and `old(expression)` have meaning only in postconditions. Exact grammar and collision rules still need integration in spec 15.
Safe contracts are enforced, and profiles may reject statuses without disabling checks. Predicate evaluation is read-only, with no heap/region allocation, authority use, ambient-state observation, synchronization, unsafe operation or ownership transfer; callees must satisfy the same restriction. This requires an opcode/call-closure rule in addition to `effects []`: effect-free `arc.clone`, endpoint duplication and `task.cancel` can change state, while `task.cancelled` has no parameter to restrict. The readable types and projection rules remain a gate decision.
Safe contracts are enforced, and profiles may reject statuses without disabling checks. Predicates cannot write caller-visible storage, allocate heap/region storage, use authority, observe ambient state, synchronize, execute unsafe operations or transfer caller ownership. Callees must satisfy the same restriction. This requires an opcode/call-closure rule in addition to `effects []`: effect-free `arc.clone`, endpoint duplication and `task.cancel` can change state, while `task.cancelled` has no parameter to restrict.
The candidate allows arithmetic, Copy aggregate construction, control flow, ordinary trapping checks, read-only data projections and mutation of fresh predicate-frame storage. It excludes all task/atomic/mutex/channel operations, authority intrinsics and ownership duplication/release. An effects-empty callee with a `mut` parameter still needs a proof that its writes target only fresh predicate storage; its signature alone is insufficient. The exact allowed opcodes, readable types, write-root propagation and recursive call-closure algorithm remain gate decisions. Contract operations inside the predicate closure are initially excluded to avoid recursive contract dispatch; that restriction still needs a complete rule for type-invariant evaluation.
`old(expression)` captures a Copy observation after preconditions and before the body. Snapshots belong to the activation, use bounded frame storage, and do not retain borrows or copy an ownership graph. Postconditions may observe the actual result. Referencing a consumed input is rejected; taking an old scalar observation does not make the input available again. A returned exclusive view must not permit a postcondition to bypass its parent's alias restrictions.
## AIR, verifier and runtime candidate
Prefer feature-gated contract descriptors associated with function declarations and independently checked typed predicate bodies. The interpreter enforces preconditions at invocation and postconditions at normal return, so omitting an inline check cannot bypass a descriptor. Source lowering supplies the same descriptors, including generic/package specializations; the verifier checks their types, bindings and predicate restrictions without trusting the frontend.
Prefer a feature-gated entry prefix over new function headers. The following spellings are candidates, not registered instructions:
This adds semantic declaration constructs rather than an opcode solely for syntax sugar. Descriptor binding, snapshot production, return-value observation and execution order need a complete AIR grammar and transfer contract before publication. No existing instruction changes meaning.
```text
entry:
contract.pre @positive(%x)
%old = contract.old @snapshot(%x)
contract.post @unchanged(%old, result)
... ordinary body ...
```
Predicate instructions consume ordinary fuel and quantum steps. False pre/post conditions need distinct stable traps; a predicate's own arithmetic/bounds trap retains its code. Snapshot/dispatch charging and cancellation ordering still need exact rules. Both runtime profiles execute the same contracts; policy may reject statuses but must not silently disable checks.
Only contracted functions gain these rules. Their entry block MUST have no predecessors. The contract operations MUST be its leading, uninterrupted prefix, ordered `pre*`, at most one `old`, then `post*`. A conditionally installed or later contract operation rejects. Existing functions may still branch to entry under existing rules. Constants and projections are computed inside helpers; ordinary instructions MUST NOT precede or interrupt the prefix.
The verifier must check contract access at the relevant boundary, including task loans, returned views and cleanup. A function-entry proof cannot stand in for a return-state proof. Limits on descriptor count, predicate traversal and total snapshot frame size must be explicit and tested with counted cases.
| Candidate operation | Types and result | Verifier transfer | Runtime rule |
|---|---|---|---|
| `contract.pre @p(bindings)` | typed observations → `bool`; no SSA result | validate pure helper and an ordinary observation/call at entry | invoke now; false traps at this clause |
| `%old = contract.old @s(bindings)` | typed observations → bounded Copy record without borrows/authority | validate entry access; produce a contract-only snapshot | invoke once after all preconditions; retain result in this activation |
| `contract.post @q(bindings)` | typed observations → `bool`; no SSA result | register ordered obligation; check its virtual observation/call at every normal `ret` | install now; invoke before each normal return transfers its result; false traps at this clause |
Bindings identify function parameters, the prior snapshot, or the post-only placeholder `result`. They do not capture an entry-time borrow for later reuse. Copy data may bind by value; candidate `ref %parameter`/`ref result` bindings request a temporary shared view at evaluation time. Existing `borrow.ref` shapes apply: `mut<T>` becomes `ref<T>`, `slice_mut<T>` becomes `slice<T>`, owners expose their content, and exclusive results may be shared-reborrowed. Authority and other types excluded by the eventual purity rule cannot bind merely because they are Copy. A void return has no `result`; postconditions on a `never` return are rejected rather than reported as evaluated.
Post installation reads no resource and takes no loan. At each `ret`, the verifier checks the bindings as a virtual ordinary predicate call in the final body state, before return transfer. A still-available owner being returned may be observed without consuming it. A consumed owner remains unavailable (the current owner case gives E3001); a moved binding remains unavailable under E2001. An owner moved through another call can be observed through `result`, without reviving its old parameter binding. An input lent to a returned exclusive view cannot also be read through its parent; ordinary alias checks reject that observation. Temporary views end after each predicate call and before result transfer. Existing leak/return rules still apply; diagnostic ordering between new predicate access errors and return/leak errors needs an explicit stage rule and regression cases. Source typing must specify explicit read-only places and clause-root elaboration; no implicit dereference of owned parameters is adopted here.
The snapshot cannot appear in body expressions, copies, branch arguments or a return; its only use is a post binding, and a snapshot used by no post is rejected. Multiple source `old` expressions lower to fields of one record. Its accounted size is bounded by `max_value_size`; the proposed combined snapshot plus `local.alloc` budget is `max_local_frame`, with checked arithmetic. These limits apply only to new contracted functions and need exact diagnostics. Prefix size and helper argument counts use existing instruction/call limits. Predicate closure traversal still needs a counted complexity bound.
All three operations have empty declared effects, transfer no caller ownership, and perform no synchronization or capability use. `pre` and `old` read permitted observations; `old` additionally writes its bounded activation snapshot. `post` installation stores clause metadata, and its return-time evaluation reads only currently legal observations. Pure helper frame writes are local. No implicit heap allocation or opaque library hook is introduced. The prefix and implicit return obligations are semantic coverage constructs, not abbreviations for optional asserts. Source/package/generic lowering must supply the same verifiable operations; AIR verification cannot trust frontend coverage claims.
Each prefix operation costs one fuel/quantum step; helper instructions use ordinary limits. Every implicit helper frame counts toward the existing 1,024-frame call-depth limit (T0007). A `ret` pays its ordinary step once, then invokes post helpers in installation order, charging their instructions. The proposed spec 11 §7 rule is: post dispatch and pending-return resumption are not new instructions and add no fuel/quantum unit; predicate instructions are charged normally. Resumption performs no new fuel check; stopping before the first predicate instruction already counts the begun `ret`. This dispatch policy needs interpreter tests, including that edge and limits between predicates. Explicit body cleanup occurs before `ret`; return views retain the ordinary permitted ancestor chain. A failed predicate traps without hidden cleanup/unwinding, under existing trap termination rules.
False pre/post conditions need distinct stable trap codes, not allocated here; a predicate's own arithmetic/bounds trap retains its code. Clause identity/location and invocation context need an exact additive run-record schema. Entry predicates run in the invoked task, including spawned workers. Capability exclusions still permit parameter-free conditions on `@main`, including a false condition. Both profiles enforce the same contracts. Predicate execution consumes fuel and can change schedule interleavings: contracts are not observationally free. Fuel exhaustion during a postcondition produces no successful return; cancellation checks and synchronization remain excluded from predicate code.
## Status and diagnostics
@@ -74,21 +98,33 @@ Valid target example: a function with `requires { x > 0u64; }` and `ensures { re
## Invariants and unresolved decisions
Type invariants require a choice between enforcing every construction/write and introducing encapsulation plus checked publication boundaries. Spec 15 §14.1 currently permits imported construction and field access; function-boundary checks alone do not establish a value invariant. Exclusive mutation, nested aggregates, value.swap, outcomes, transfers and partial initialization all need explicit coverage rules.
Type invariants require a choice between enforcing every construction/write and checking publication from exclusive mutation. Spec 15 §14.1 currently permits imported construction and field access; function-boundary checks alone do not establish a value invariant. These current programs contain no invariant declaration: they demonstrate where a future `Range.lo <= Range.hi` rule would need coverage, not current compiler defects.
| Probe at `94414da`, fuel 10,000 | Verified outcome | Design consequence |
|---|---|---|
| `{0,5}` → `r.lo = 10; r.hi = 20` through one exclusive view | returns width 10 | eager checks reject the intermediate `{10,5}`; deferred checks permit repair |
| copy `*r` into another `Range` between those writes | returns 1 for the escaped copy's `lo > hi` | checking only the exclusive borrow's end misses Copy publication |
| call `width(ref r)` between those writes | T0003 at `hi - lo` | shared reborrows need checks if readers may rely on the invariant |
| source `var range: Range = zero` | E7006 `zero_not_zeroable` | source currently prohibits this construction |
| AIR `local.zero` of `local<@Range>` with integer fields | accepted, returns 0 | AIR construction needs coverage: `{0,0}` meets `lo <= hi`, but would violate a strict invariant `lo < hi` |
Eager enforcement requires root/projection tracking for every complete construction, store and swap, including nested invariant types. It forces multi-field updates to use valid whole-value replacements. Exclusive-epoch enforcement permits intermediate invalid states, but must validate Copy publication and shared readers as well as epoch end. It also needs a rule for mutable callees: check entry, or prohibit reliance on a possibly broken invariant. Returned mutable views and task loans can transfer the validation boundary to another function/join. Neither model may bypass initialization or ordinary alias restrictions to read a root for validation. Format 0 tracks whole-local initialization, not partially initialized field states.
Both models must cover AIR `local.zero`, nested aggregates, buffers/graphs, `value.swap`, outcome payloads and ownership transfer; a narrower source constructor policy is insufficient. Source/AIR zeroability wording is a separate question (Q-056). Invariant metadata and its AIR representation remain unresolved: the function prefix does not by itself provide a type/module declaration mechanism.
Module invariants need a definition of their roots and observation boundaries. Source 0.1 has no module-state declarations or visibility modifiers; neither nonexistent globals nor arbitrary private-state semantics may be inferred from spec 13's example. Loop invariants, if included by P6-6, need an explicit initiation/preservation/exit rule. Implementing function contracts alone leaves these requirements and P6-6 open.
Remaining decisions: predicate language/types and totality; mutable/linear result views and cleanup order; snapshot limits; proof and assumption modes; invariant boundaries; AIR grammar and compatibility; traps, fuel and report schema. The RFC stays Draft until these have concrete rules and counterexamples.
Remaining decisions: exact predicate language/types, write-root proofs and termination policy; source clause elaboration and complete AIR binding grammar; snapshot diagnostics; proof and assumption modes; invariant boundaries and metadata representation; traps/report schema and tested pending-return dispatch. The RFC stays Draft until these have concrete rules and counterexamples.
## Compatibility and integration
An AIR0 implementation must preserve all earlier accepted behavior, canonical bytes and rejected codes (spec 07 §8.7). Preserving the old E0001 for an unfeatured header conflicts with §8.1's required E0006; replacing it with E0006 conflicts with §8.7. Q-055 records the existing trusted-header precedent, not an exception contracts may assume. An instruction-based form fits the E0004 exception; the header candidate requires an owner decision on compatibility policy or AIR1.
An AIR0 implementation must preserve all earlier accepted behavior, canonical bytes and rejected codes (spec 07 §8.7). Isolated candidate function operations and the snapshot/post prefix currently reject only E0004; registering them may produce E0006 when their feature is undeclared, matching the named-opcode exception and §8.1. The body-use probe also reports E5001 because the unknown instruction does not define `%old`. That shape remains invalid under the candidate's snapshot restriction; the audit concerns its rejection-code transition, not acceptance of this escape. Establish whether §8.7 covers those dependent errors, and preserve independently invalid cases; precedent alone does not settle that interpretation (Q-055). Full dependency closure and syntax audits are still required. The prefix avoids the header-specific E0001 conflict without changing compatibility policy. New type/module metadata must independently satisfy compatibility or use AIR1.
On acceptance integrate spec 13 §1, spec 08 §8, spec 10 §6.1, spec 07/07a, spec 15, grammar, feature/error registries and the Quick Reference together. Delivery requires source/AIR positive and negative coverage, bypass attempts, generic/package/worker cases, borrow/loan/snapshot failures, deterministic profiles/schedules and independently verified audit statuses. No implementation is authorized by this Draft alone.
On acceptance integrate spec 13 §1, spec 08 §8, spec 10 §6.1, spec 11 §7, spec 07/07a, spec 15, grammar, feature/error registries and the Quick Reference together. Delivery requires source/AIR positive and negative coverage, bypass attempts, generic/package/worker cases, borrow/loan/snapshot failures, deterministic profiles/schedules and independently verified audit statuses. No implementation is authorized by this Draft alone.
## Agent complexity impact
New concepts: boundary obligations, result/old observations and audit statuses. New verifier state: descriptor bindings, predicate restrictions, snapshot and return availability, plus the chosen invariant/proof state. New source forms: contract clauses and contextual result/old; diagnostic and AIR counts await a completed design.
New concepts: boundary obligations, result/old observations and audit statuses. New verifier state: ordered obligations, predicate restrictions, snapshot and return availability, plus the chosen invariant/proof state. New interpreter state: pending return and its next postcondition. New source forms: contract clauses and contextual result/old; diagnostic and AIR counts await a completed design.
Assertions express individual checks today, but the probes show why they do not encode a public guarantee with verified coverage. The cost must be compared with keeping explicit checks and making no contract claim. No SMT solver, implicit allocation or effect inference is proposed.
@@ -100,4 +136,4 @@ The acceptance change must demonstrate: preserved availability/alias/loan invari
## Alternatives considered
Frontend-generated asserts with annotations fail the coverage invariant. Inline contract instructions plus a boundary-coverage verifier could satisfy it, but require explicit entry/return and snapshot state. Callee-enforced descriptors avoid that bypass class while enlarging interpreter invocation semantics. A format-1 design remains an alternative if format-0 compatibility cannot be proved.
Frontend-generated asserts with annotations fail the coverage invariant. Ordinary explicit predicate calls remain useful checks but do not establish public contract coverage. The entry prefix combines verifiable installation with callee-enforced returns; arbitrary inline installation is rejected. Header descriptors could encode the same semantics, but add the Q-055 compatibility conflict. A format-1 design remains an alternative for complete invariant metadata if format-0 compatibility cannot be proved.