rfc: define predicate purity and shared observation gate
This commit is contained in:
1 parent
8cd933538b
commit
a5f84eb170
3 files changed
+50
-7
No files matched your search
@@ -47,9 +47,42 @@ The candidate source spelling is `requires { condition; }` and `ensures { condit
|
||||
|
||||
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 Data observation (defined below) 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.
|
||||
|
||||
`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.
|
||||
## Closed predicate-purity candidate
|
||||
|
||||
Define **Data** structurally: integers, bool, the three existing built-in error enums, `iref<U>` as an opaque leaf, and arrays/declared structs/enums whose members are Data. This excludes capabilities, borrows, storage, linear and function-bound values at every member depth. Copy alone is insufficient: `cap<K>` is Copy. Ordinary type validity still applies, including the referent U of an iref.
|
||||
|
||||
Predicate closure functions may hold Data by value, shared `ref<T>`/`slice<T>` observations of otherwise well-formed targets, and `mut<Data>`/`slice_mut<Data>`/`local<Data>` scratch views/storage. Void/never are permitted only in their ordinary signature/control positions. This rule applies to parameters, block parameters, results, allocated content and every instruction result, not just signatures. Shared targets may be linear aggregates or contain authority, but no load, projection or call may produce an owned non-Data value. Thus reading a count field beside an owner is possible; extracting a Copy capability from another field is not. Mutable graph/buffer roots and owned resources cannot occur in the closure.
|
||||
|
||||
The proposed contracts feature depends on `effects` and `ownership`; other types/operations retain their own feature requirements. Its Data definition and allowlist are closed and immutable at publication (spec 07 §8.7). A future registered feature may explicitly classify its own newly introduced constructs for predicates, with their dependency closure; it cannot silently admit or reclassify an already published opcode/type. Such a reclassification needs a new format or a separately specified new construct compatible with §8.7. Ordinary type, borrow, initialization and bounds rules remain mandatory.
|
||||
|
||||
| Allowed class | Operations and additional restriction |
|
||||
|---|---|
|
||||
| Values and arithmetic | `const.T`, `error.const`, `copy`, integer arithmetic, bit operations, comparisons and casts; held values are Data |
|
||||
| Checks/control | `assert`, `guard`, `trap`, `br`, `cbr`, integer `switch`, `enum.switch`, `ret` |
|
||||
| Aggregate values | `struct.make/get/unpack`, `enum.make/take`, `array.make/splat/unpack`; complete operands/results are Data |
|
||||
| Frame storage | `local.alloc/store/zero/load`; content is Data |
|
||||
| Views | `borrow.ref/mut/field/end`, `borrow.index` and `.proven`, `load`, `store`, `value.swap`, `slice.make/len/sub/split/copy`; loaded/written/copied values are Data, view results obey the type rule above |
|
||||
| Graph observations | `island.root/borrow`, `frozen.root/borrow`, `arc.root/borrow`, `iref.eq`; owner/node views are shared, identity results are Data |
|
||||
| Buffer observations | `buffer.len/capacity/view`; buffer views are shared |
|
||||
| Calls | direct `call` to another admissible closure function |
|
||||
|
||||
Heap/region/graph/buffer allocation, authority intrinsics/narrowing, ownership duplication/release/transfer, synchronization, task/cancellation/ambient operations, `assume`, unchecked indexing and contract operations are outside the list. `guard` and proven indexing retain the existing closed bounds calculus; a contract's truth introduces no new body fact under this purity rule.
|
||||
|
||||
Let P be the greatest set of functions satisfying the type/operation rules, declaring exactly `effects []`, containing no trusted boundary, and calling only members of P. Compute local admissibility once, then remove failed callees and their callers with a reverse-edge worklist. After local type/opcode scans this is O(F+C), for functions F and call edges C; repeated whole-graph rescans are unnecessary. Data classification is memoized over finite member graphs, with iref edges treated as leaves. Recursive helper components are admitted when all their local rules hold. Source packages/static specializations lower to this same AIR graph; frontend purity annotations carry no authority.
|
||||
|
||||
Each entry helper named by `contract.pre/old/post` must be in P and have no mutable parameters. Pre/post return bool; old returns Data. P membership makes a helper admissible **inside this closure**, not globally read-only when called elsewhere with a mutable argument.
|
||||
|
||||
Write freshness follows structurally. The entry helper receives no mutable root or owned linear value. Each permitted mutable view comes from a closure frame local, another mutable view, or a helper's declared `from` result. Shared views cannot become mutable; graph/buffer observations above create only shared children. By induction over dynamic calls, every mutable parameter in a helper originates in closure-frame scratch. Second-class borrows cannot escape through Data, and ordinary return/lifetime rules prohibit returning a view into dead frame storage. Helpers may therefore mutate their scratch through ordinary calls without an additional interprocedural write-summary system. Interior-mutability operations stay excluded by opcode, even when they accept a shared view.
|
||||
|
||||
Loops and recursion carry no totality claim: ordinary fuel and call-depth rules apply, and failure to finish a predicate produces no successful contracted return. P membership alone proves neither clause truth nor PROVEN_STATICALLY. Assertions inside predicates retain T0002; only returning false from a pre/post helper uses the new contract-false trap. Purity rejection needs stable function/type/operation facts and a deterministic witness from the clause; codes, diagnostic order and witness bounds remain integration work.
|
||||
|
||||
An old iref snapshots identity, not graph contents; dereferencing it observes current content through a currently available root. It retains no owner and revives none. Old buffer length/capacity are scalar snapshots; copying a dynamic prefix requires an explicitly bounded Data representation rather than an implicit heap copy.
|
||||
|
||||
Additional current-language probes: a slice predicate calling a scratch-mutating helper and `std.hash.fnv1a64` returns 1; a shared linear-record count read returns 7; an iref compared after destroying its graph returns 1. Extracting a capability field through a shared linear-record view is accepted today, so the candidate must reject that instruction result in a predicate. Mutually recursive scalar helpers return 1; a nonterminating helper stops at fuel 10,000, and recursive frame exhaustion traps T0007. These establish design constraints, not an implemented purity check.
|
||||
|
||||
Observation coverage remains a separate gate (Q-057): current `match *ref<LinearEnum>` rejects E1001, and a shared owner field cannot be dereferenced without attempting a forbidden linear load. The allowlist does not manufacture missing tag/payload or owner-content operations. Preconditions/postconditions over the currently readable subset alone do not complete P6-6.
|
||||
|
||||
## AIR, verifier and runtime candidate
|
||||
|
||||
@@ -68,14 +101,14 @@ Only contracted functions gain these rules. Their entry block MUST have no prede
|
||||
| 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 |
|
||||
| `%old = contract.old @s(bindings)` | typed observations → bounded Data | 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.
|
||||
Bindings identify function parameters, the prior snapshot, or the post-only placeholder `result`. They do not capture an entry-time borrow for later reuse. 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-bearing values and other non-Data types cannot bind by value 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.
|
||||
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 Data 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. Counted tests must cover member-edge visits, function removals/call-edge visits and the eventual diagnostic-witness length, including shared type diamonds and recursive helper components.
|
||||
|
||||
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.
|
||||
|
||||
@@ -114,7 +147,7 @@ Both models must cover AIR `local.zero`, nested aggregates, buffers/graphs, `val
|
||||
|
||||
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: 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.
|
||||
Remaining decisions: shared observation coverage (Q-057) and invariant-evaluation interactions; source clause elaboration and complete AIR binding grammar; purity/snapshot diagnostics and ordering; 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
|
||||
|
||||
@@ -124,7 +157,7 @@ On acceptance integrate spec 13 §1, spec 08 §8, spec 10 §6.1, spec 11 §7, sp
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
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.
|
||||
New concepts: boundary obligations, result/old observations and audit statuses. New verifier state: ordered obligations, structural Data and closure membership, snapshot and return availability, plus the chosen invariant/proof state. Scratch freshness reuses ordinary typing/borrow provenance rather than new write summaries. 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.
|
||||
|
||||
|
||||
Reference in new issue
Block a user