rfc: define contract accounting and audit status candidate

This commit is contained in:
dev committed 2026-10-09 10:06:40 +03:00
1 parent 9a3e135f43
commit a4181f2d8d
4 files changed
+107 -3

No files matched your search

@@ -0,0 +1,100 @@
# Contract accounting, diagnostics and status candidate
Non-normative research for [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), following the [invariant-boundary candidate](contract-invariant-boundaries.md). All new constructs, limits and codes here are proposals, not registry allocations. Full P6-6 remains open.
## Evidence and budget rule
At `9a3e135`, the verifier runs limits before CFG, SSA and types, stopping at the first failing stage (spec 08 §14; `src/verifier.zig`). Frame storage counts `local.alloc`; SSA values have the separate maximum-value bound. Nine current-language probes confirm:
- an exactly 1,048,576-byte local accepts and returns 0; one extra byte rejects E5101;
- that local plus a 1,048,576-byte SSA array still accepts and returns 0;
- limits beat malformed CFG (E5101); CFG beats forward SSA use (E5002); forward SSA use beats type mismatch (two E5001s);
- type mismatch beats unsafe-boundary failure (two E1001s); unsafe beats initialization (E6001); initialization beats a live-borrow leak (E1010).
Runs use fuel 10,000. These are baseline constraints, not tests of implemented contracts.
Four complete pre/post assume/document opcode probes each reject E0004 alone. An existing source `assume(false)` in an unsafe function accepts verification and traps T0009 when run with fuel 10,000. These five further baselines constrain compatibility and unsafe enforcement; they do not implement the proposed modes.
Proposed activation storage, using spec 08's checked, platform-independent accounted sizes:
```text
L = sum of all local.alloc content sizes in the function
S = old helper's declared Data return size, or zero
E(clause) = sum of Copy-value places for each explicit ref binding
E(old) = the same sum for old's input bindings
E(checked.make) = size(R) for Copy R; zero for linear R
E(checked.modify) = 0
activation = L + S + max(0, E for executable clause/old/make sites)
```
Each explicit Copy ref binding creates its own temporary place, even when two bindings name the same parameter. Borrow/owner/linear-root observations use in-place views and contribute zero; they MUST NOT copy or transfer ownership. Documented clauses create no runtime places. Their virtual access checks still apply. Locals and S persist for the activation; clauses execute sequentially and their places end before the next evaluation. Helper/callback activations have their own bounds and ordinary call-depth rules.
For make, a Copy representation needs the instruction-internal whole-value place; a linear representation is observed through its existing SSA cell before transfer into the checked value. The latter contributes no new place and cannot be copied, moved during validation or exposed before success. The explicit R operand supplies size/root shape before SSA; both cases retain the ordinary maximum-value bound.
Pending callback/return values remain ordinary SSA values, bounded by `max_value_size` and traced by GC. They are not a new frame term. A Copy `ref result` place is counted once in E; an update result retained during validation is not materialized merely because it is pending. The candidate maximum activation size is 1,048,576 bytes, using E5101's existing `limit: "local frame bytes"`, `max` and `found` fields; overflow is `found: "overflow"`. Functions without the new sites retain their current accounting.
All descriptors MUST be available before SSA inference: clause bindings name original parameters, the snapshot or result; parameter/result types come from the enclosing header, snapshot type from its helper header, and make explicitly names `checked<R,@p>`. Callback result types come from callback signatures. Budget calculation never dereferences an absent parameter or assumes predicate validity. Malformed bindings wait for their later stage; size and Copy/root-shape queries must be total on recursive/invalid types, with cycle detection and memoization, without invoking full type verification. Existing size accounting supplies the size-query precedent; the current recursive linearity query is not a safe pre-types substitute. An arbitrary body SSA binding is forbidden. Accounted size of checked<R,p> is size(R); predicate identity contributes no runtime member.
For this budget query, seed the existing intrinsically linear kinds and propagate linearity backwards through array elements, nominal struct/enum members and checked<R,@p>'s representation R to a least fixed point. Predicate identity contributes no edge. An invalid member cycle with no reachable linear leaf is non-linear (Copy for accounting); one reaching an owner or another linear leaf is linear. Direct borrow/root bindings remain in-place. This matches ordinary linearity on valid types and supplies a deterministic value on cycles, without accepting them. Preserve the existing accounted-size depth cutoff on invalid graphs rather than replacing a whole cyclic type's size with zero. Required candidate vectors include both kinds of cycle next to the frame limit: budget excess still reports E5101 first; otherwise the invalid cycle reaches the ordinary type rejection. These vectors are not among the fourteen executed baselines.
Two sequential clauses each materializing 600,000 bytes fit when L=S=0. One clause materializing both needs 1,200,000 and rejects. Snapshot 600,000 plus locals 500,000 rejects even with no temporary place. This rule does not infer lifetime reuse between arbitrary locals.
## Bound the virtual boundary work
Post bindings are checked at every return, so instruction count alone does not adequately bound the product. Count syntactically, including unreachable blocks, before SSA:
```text
W = sum_pre/old(1 + binding_count)
+ ret_count * sum_post(1 + binding_count)
+ 2 * make_count
+ sum_modify(4 + extra_argument_count)
```
The proposed limit is 1,048,576 virtual binding positions per function: four times the ordinary instruction limit, independent of any benchmark. The extra position covers each virtual invocation; modify covers its callback's first argument, extra arguments and predicate invocation. Count documented clauses because their virtual legality checks still run. Excess/overflow rejects E5101 with `limit: "contract binding positions"` and the existing fields. Actual argument lists retain the 64-argument limit, including modify's generated first argument. P/S closure computation and diagnostic witnesses need independent memoized bounds; this formula is not a bound on every verifier algorithm.
## Four statuses, three enforcement modes
Default `contract.pre/post` and checked make/modify evaluate their predicates at every specified boundary. Source `requires`/`ensures` retain this default. Propose explicit variants `contract.pre.assume/post.assume` and `contract.pre.document/post.document`, with contextual source `requires/ensures assume` and `requires/ensures document` groups.
| Mode | Proof treatment | Spec 13 status | Execution |
|---|---|---|---|
| runtime, all boundaries proved by the closed rule below | proven | PROVEN_STATICALLY | predicate still executes |
| runtime, no complete proof | none | CHECKED_AT_RUNTIME | predicate executes |
| explicit assume | not attempted | ASSUMED_UNSAFE | interpreter evaluates; false is T0009; native unsafe treatment follows assume |
| explicit document | not attempted | UNPROVEN | declaration recorded; predicate is not executed |
Assumed variants require the existing unsafe effect/trusted boundary and appear in the unsafe report; ordinary P/helper typing, availability and lifetime checks remain mandatory. They need a separately gated extension depending on contracts and unsafe, so ordinary contracts need not declare unsafe support solely to be understood. False unsafe assumptions retain the existing unsafe-precondition semantics, rather than becoming a safe guarantee.
Documented variants also retain P membership and the same virtual observation/access checks at entry and every normal return. They grant no fact to a caller or the body. Switching a clause to document removes its guarantee and must remain visible in the report/Quick Reference. A documented post may bind an old snapshot only when an executable runtime/assumed post also uses that snapshot; a snapshot used solely by documents rejects as unused. Checked types have no document/assume construction mode in this candidate: persistent value claims remain enforced.
Every executed prefix operation still costs one fuel step, including document declarations and post installation. Documented clauses invoke no helper at entry or return; executable clauses use ordinary helper instruction and frame accounting. Recording metadata introduces no extra dispatch step. This extends the prefix accounting candidate without making classification change execution.
No successful run, absence of a trap, check count or empty effect set establishes proof. Profiles may reject statuses but MUST NOT alter enforcement or proof classification. Static classification adds no skipped helper instruction or fuel/scheduler change. Even PROVEN_STATICALLY does not promise termination or freedom from other traps. Counts describe declaration/operation sites, separately from the number of covered returns, never invocation frequencies.
## Closed initial proof classification
This is deliberately a restricted classifier, not a restriction on executable contracts. Unsupported predicates remain CHECKED_AT_RUNTIME. It never imports a caller fact into a callee's global pre status and never assumes an unchecked declaration.
An eligible predicate has one block, no calls, and only typed constants, copy, Data struct construction/projection, integer/bool comparisons, bool and/or/xor, and shared binding-derived field views with load/end, ending in ret bool. The same form with a Data return can describe old's snapshot fields. Arithmetic, casts, indexing, graph/buffer/enum operations, calls and multiple blocks are unsupported initially. Normalization uses an immutable DAG, not expanded copies of paths/aggregate trees.
Terms are typed constants, immutable Data parameter identities/projections, stable shared parameter field projections, snapshot terms from an eligible old helper, and the current return operand's Data origin. Resolve return origins through constants, copy, struct.make and struct.get; every other Data SSA definition is an opaque identity at this boundary. A snapshot cannot capture body SSA, so a loop's repeated definition is not conflated with an entry observation. Borrow-return origins remain unsupported. Mutable-root entry/current observations have distinct identities, even when the body happens not to write; no interprocedural write-summary proof is inferred.
Shared field terms are stable because ref cannot become mut, overlapping mutable call arguments and root consumption are forbidden, and task loans exclude writers. Field views in this normal form do not traverse interior-mutable interfaces. P/S alone are not substituted for this exact normal-form condition; future pure observations outside the form stay unsupported.
Decision rules are closed: compare typed constants with their declared signedness; identical typed terms give true for eq/le/ge and false for ne/lt/gt; otherwise an atom is unknown. Bool combinations use three-valued logic (`true or unknown` is true, `false and unknown` is false; xor with unknown is unknown). A runtime clause is proven only if its formula is definitely true at every prescribed boundary. Pre parameters are universally unconstrained; a post must hold at every syntactic ret, including unreachable ones, and zero ret sites give no vacuous proof. A make site may substitute a constant/parameter-derived representation; modify remains runtime initially.
Examples: a Data identity function whose every return is x can prove `result == old(x)` when old merely captures x. A second return of y prevents that classification. A constant Range representation or `{lo:x, hi:x}` can prove lo <= hi through shared field inspection. A pre over unrelated lo/hi remains runtime. `x + 0 == x`, hashing and mutation-based restoration remain runtime even when mathematically true.
Classification also needs an exact work bound. Candidate logical cost per record is helper operand-position work, relevant old-helper work only when used, reachable result/representation-origin DAG work, and boundary_count times the helper's normalized node count. Pre has one boundary and no body-origin work; adding unrelated body instructions cannot make a pre proof exceed its budget. Post/make inspect only their required origin DAG, charging each reachable definition once per record, including shared definitions across return sites. An instruction contributes one plus its operand positions; a normalized instruction produces at most one node. The proposed bound is 1,048,576 per record. Exceeding it, arithmetic overflow or an unsupported form yields proof none with a structured reason, without rejecting or weakening mandatory runtime enforcement. Cache helpers/origin DAGs, but count this logical cost independently of cache hits. Exact operand/node conventions and conformance vectors remain an integration gate; do not claim toolchain-independent PROVEN output until that rule is fully specified.
## Diagnostics and report
Map the new rules into existing stages: limits first; prefix order/entry predecessors in CFG; snapshot-use restrictions and binding identities in SSA; signatures/Data followed by P/S membership at the end of types; callback effects in effects; assumed boundaries in unsafe; ordinary initialization checks unchanged; virtual access/loans/return availability in borrows; existing bounds last. Observation places are materialized from complete parameter/result/snapshot values and introduce no independent initialization failure. Parse/name and feature errors precede verification. Invalid signature errors precede purity classification. Runtime clauses retain ordinary E2001/E3001/E2101 and lifetime codes instead of a generic contract error.
Candidate new codes are E8001 `contract.invalid_binding` (snapshot escape/unused/document-only snapshot with stable reason), E8002 `contract.predicate_not_pure`, E8003 `contract.predicate_not_stable`, and T0011/T0012/T0013 for false runtime pre/post/invariant. None is allocated here; adopting E8xxx also requires a new family entry in spec 10 and the error registry. Existing signature/type errors use E1001, structural errors E5002, limits E5101 and missing unsafe boundary E6001. Source-decided errors follow spec 15 §10's E7xxx policy; semantic new codes retain source provenance. A purity witness must contain real helper/type/op facts, with bounded length and explicit truncation, not invented locations.
At ret, virtual clause checks run before ownership return transfer and leak checks. They cannot resurrect consumed inputs or inspect a parent frozen by an exclusive result. Errors from that stage retain the existing (line, col, code) order. Specify collection when both access and leak errors occur before treating this as a complete ordering rule; a sort key cannot recover a diagnostic suppressed by an early return.
Emit the proposed additive `contracts` section only for modules declaring the relevant feature; contract-free canonical report bytes stay unchanged. Each row identifies function/block/instruction, helper, kind, scope (`boundary` or persistent `value`), status, proof and enforcement, plus covered return sites and positions. A pre row belongs to the callee declaration, not a selected caller. A type guarantee and a relation over listed functions require distinct scopes. Include per-status site totals; totals are not sums over executions or returned branches. Snapshot metadata is not itself a truth obligation. Rejected modules still produce diagnostics and no audit document.
Required tests include max/sum activation cases, invalid descriptors before SSA, argument/work limits, all four modes, mixed executable/documented snapshot use, unsafe/trap/fuel behavior, multi-return and trap-only coverage, proof-budget fallback, old/current mutation counterexamples, callback/GC pending values, exact rejection ordering and identical contract-free report bytes. Predicate/trap rows must survive generic/package/source mapping. Owner adoption, exact proof-cost/schema grammar, module-claim selection, RFC 0040 observations and full vertical implementation remain gates. This file changes no normative bundle.
+2
View File
@@ -403,6 +403,8 @@ P6-6 requires contracts and their four audit statuses, but spec 13 §1/spec 08
[Invariant-boundary research](contract-invariant-boundaries.md) compares eager/epoch coverage with a checked representation and explicit in-place callback update. The latter avoids requiring replacement allocation for borrowed linear state, but still needs stable-observation rules, pending-result semantics and exact type/source representation. Current probes confirm a scalar helper mutating an enclosing Range, public fields bypassing a library wrapper and independent-root relation drift (each returns 1), plus E0001 for a new type declaration versus E0004 for an unknown type constructor. Persistent state-root claims and function-boundary relations must have distinct scope; module roots/declarations and full P6-6 proof/status rules remain open.
[Accounting/status research](contract-accounting-and-status.md) proposes pre-SSA activation and virtual-binding bounds, a restricted proof classifier that preserves predicate execution, and explicit unsafe-assumed/documented modes. Nine current-language probes confirm frame/value separation and verifier-stage priority; four proposed mode opcodes reject E0004 alone, while existing unsafe `assume(false)` accepts and traps T0009. These fourteen cases constrain the candidate, not demonstrate contract implementation. Exact proof costs, diagnostic collection, report schema, source/module metadata and adoption remain open.
## Q-055 — Feature-gated AIR headers and frozen rejection codes
Spec 07 §8.7 permits changes to earlier E0004/E0006 rejections, not E0001. Source inspection of the parser before commit `0086549` shows that an unfeatured `trusted "..."` header was parsed as a block label and failed while expecting `:`; current spec 13 §6.3 and the parser require E0006 `feature_not_declared`. RFC 0009 calls the header additive, although this diagnostic transition is outside the literal exception. The historical parser has not been executed in this audit.
+2
View File
@@ -349,3 +349,5 @@ The [invariant-boundary research](../design/contract-invariant-boundaries.md) ad
Eight further compatibility probes independently reproduce Claude's findings: exact predicate-bearing type spellings in seven positions report E0004 alone, while an opcode-first make/take/result-use shape reports E0004 twice and E5001. All thirteen current-language cases match their recorded outcomes; runs use fuel 10,000. Stable closure membership must be justified separately from point-in-time predicate purity so future interior-mutable reads cannot silently invalidate persistent claims. No complete AIR0 compatibility or implemented invariant is claimed.
Final review identified the need for instruction-internal observation places: ordinary AIR borrow.ref rejects Copy scalar and Copy struct SSA roots with E1001 (two independently verified probes, fifteen total). The candidate states evaluation-scoped materialization without widening general addressability or frame-content rules; RFC 0039 Copy ref-bindings use the same requirement. Exact activation-slot accounting remains a gate. Copy extraction preserves the original checked claim but gives the plain copy no claim; shared interior-mutable interfaces remain outside stable observations. No implementation is authorized by the research.
The [accounting/status candidate](../design/contract-accounting-and-status.md) proposes locals plus snapshot plus maximum simultaneous observation-place storage, separately bounded virtual return bindings, and a restricted proof classifier with unchanged predicate execution. Explicit assumed/documented modes retain ordinary legality checks; only assumptions require an unsafe boundary, and documentation grants no truth guarantee. Nine frame/stage baselines and five mode/unsafe baselines match the existing CLI (runs use fuel 10,000); none tests an implemented contract feature. Claude's independent review led to body-independent pre proof costs, explicit Copy/linear make accounting and total pre-types linearity queries, including invalid cycles. Exact proof-cost conventions, diagnostic collection, report/source/module schema and owner adoption remain gates. RFC 0039 stays Draft; P6-6 and its full four-status/invariant exit criterion remain open.
+3 -3
View File
@@ -76,7 +76,7 @@ Each entry helper named by `contract.pre/old/post` must be in P and have no muta
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.
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; returning false from a runtime-mode pre/post helper uses the new contract-false trap. The assumed-mode candidate instead retains T0009; documented clauses invoke no helper. 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.
@@ -112,7 +112,7 @@ Post installation reads no resource and takes no loan. At each `ret`, the verifi
Explicit `ref` bindings of Copy SSA parameters/results need the instruction-internal temporary-place mechanism described in the [invariant research](../design/contract-invariant-boundaries.md): ordinary `borrow.ref` cannot address such a scalar or struct (both current probes reject E1001). Materialize a complete value only for the evaluation, end every observation view before resuming, and prohibit borrow escape through bool/Data results. Existing owner/borrow-root shapes and alias restrictions remain distinct; materializing a Copy observation cannot bypass them or make ordinary body/source SSA values addressable. Account these bounded activation slots with the snapshot/frame budget before implementation.
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.
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 executable post is rejected. Multiple source `old` expressions lower to fields of one Data record. Its accounted size is bounded by `max_value_size`. The [accounting candidate](../design/contract-accounting-and-status.md) bounds locals plus persistent snapshot plus the maximum simultaneous instruction-internal observation places by `max_local_frame`, with checked arithmetic and descriptors available before SSA inference. Pending callback/return SSA values retain their ordinary value bound rather than becoming frame storage. Documented-only snapshot use does not keep an otherwise unused snapshot. A separate syntactic virtual-binding limit bounds post/return expansion. These rules and diagnostics remain proposals. 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.
@@ -129,7 +129,7 @@ False pre/post conditions need distinct stable trap codes, not allocated here; a
| ASSUMED_UNSAFE | an explicit unsafe assumption and its visible boundary; never inferred from an empty effect list |
| UNPROVEN | no discharged obligation; no caller may rely on it as a fact |
The initial proof calculus and whether unproven/assumed clauses may be accepted remain undecided. The audit table must identify clause, boundary, status and source/AIR position; existing assertion counts remain counts. Proposed E7xxx reason fields and new AIR/contract trap codes are not allocated by this draft.
The [status/accounting research](../design/contract-accounting-and-status.md) proposes a restricted automatic proof classifier, explicit assumed/documented clause modes and a staged diagnostic/report candidate. Proven runtime clauses still execute their predicates; assumption requires an unsafe boundary, documentation grants no truth guarantee, and checked value construction remains enforced. Exact proof-cost conventions, diagnostic collection, report schema and owner adoption remain gates. The audit table must identify clause, boundary, status and source/AIR position; existing assertion counts remain counts. Proposed E7xxx reason fields and new AIR/contract trap codes are not allocated by this draft.
Valid target example: a function with `requires { x > 0u64; }` and `ensures { result == old(x); }` returning x; a positive argument succeeds and zero traps at entry. Rejected target example: a postcondition dereferencing an owner consumed by the body; the existing availability rule must still reject it. These are design targets, not current conformance fixtures.