diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 11b01f5..0e4119c 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -414,3 +414,11 @@ The opcode candidate needs a separate dependent-error audit: at `94414da`, `%old Spec 15 §4 calls `var x: T = zero` a lowering to `local.zero` for zeroable types, without naming a narrower source set. Spec 07a's `local.zero` includes structs whose fields are zeroable. At `94414da`, source `var range: Range = zero` with two u64 fields rejects E7006 `zero_not_zeroable`; AIR `local.alloc @Range` followed by `local.zero` accepts and runs. `src/frontend/lower.zig` restricts source zeroability to integers, bool and arrays of those types. Decide whether source intentionally exposes that narrower set (and make spec 15 precise), or whether the missing structural lowering is an implementation gap. This entry changes neither layer. P6-6 invariant coverage must independently include the existing AIR construction path, regardless of the source decision. + +## Q-057 — Shared observation of linear variants and nested owner content + +Current `match *value` with `value: ref` and `Outcome = enum { ok(own), err(u64) }` rejects E1001 at the linear load, even when both arms only return bool. Spec 03 §25 forbids observational `enum.switch` on a linear enum; `enum.take` consumes it. There is no borrowed tag/payload projection. Similarly, `*p.payload` through `p: ref` with a field `payload: own` rejects E1001; AIR `borrow.ref` on `ref>` keeps that type, and its load cannot copy the owner. A direct `own` root can expose its contents through existing `borrow.ref`, so distinguish this nested/shared-owner case. + +These are specified observation limits, not new verifier bugs. A shared linear struct's Copy field is readable (a count probe returns 7); a read-only contract could likewise need to inspect a linear result's success variant or owned nested data without consuming either. RFC 0039's purity candidate cannot supply missing observation semantics, and the full P6-6 gate remains open. + +Decide the required source/AIR observation surface. Candidate directions include a shared-view variant operation yielding borrowed payloads and an explicit shared content view through `ref>`; neither is adopted here. Any new primitive requires a registered feature, its full AIR contract, ordinary alias/loan/lifetime enforcement, deterministic behavior, format compatibility and vertical source/Quick Reference/conformance coverage. Do not enable consumption, hidden owner copies or unrestricted partial moves to make predicates expressible. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 236dc94..5dd1591 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -337,3 +337,5 @@ Spec 15's initial Phase 6A limits now point to its existing extensions. Its intr Q-054/RFC 0039 Draft identifies the missing executable contract model. Public probes at `94414da` demonstrate identical audit reports for mandatory/bypassable assertions, effects-empty mutation and ambient task.cancelled observation, E3001 after consuming an observed owner, and E0001 versus E0006 for candidate unfeatured/featured AIR headers. All runs use fuel 10,000. Claude independently audited the architecture and compatibility constraints. Predicate rules, old/result lifetime, coverage, statuses and type/module invariant boundaries need concrete normative rules before implementation; function contracts alone do not complete P6-6. Q-055 records the historical header-compatibility question from source inspection, without claiming an executed old-parser result. No compiler, semantic rule, registry, conformance fixture or normative bundle changes. The next design increment prefers leading `contract.pre/old/post` operations, isolated uses currently E0004, with no entry predecessors, contract-only snapshots and per-return access checks. The candidate specifies pending-return dispatch, ordinary fuel/quantum accounting and temporary observations without resurrecting consumed values. Current ordinary observations before returning an owner accept and preserve 42; observing its old binding after a call transfer rejects E2001. Verified invariant probes return width 10 after a repaired exclusive update, expose an invalid mid-update Copy and trap T0003 in a shared reader. Source struct-zero rejects E7006, while AIR struct-zero accepts; Q-056 records that separate surface question. Claude independently reviewed the candidate and identified dispatch/availability clarifications. A body use of an unknown snapshot additionally yields E5001; use only by a post yields E0004s alone. Q-055 retains the invalid body-use rejection-code audit. All twelve targeted probes match their reported results, and local documentation links/diff checks pass. These are current-language probes of design obligations, not conformance tests for an implemented contract feature. Type/module boundaries, predicate closure and status rules remain open; Draft status and the full P6-6 exit criterion are unchanged. + +The purity increment supplies a closed opcode/type candidate, authority-free Copy Data (including opaque iref identity), and greatest-fixed-point call closure. Read-only linear-record fields are admitted without loading owners/capabilities; auxiliary mut helpers can write fresh frame scratch, proved from entry signature restrictions and ordinary borrow rules. No write-summary subsystem or totality proof is claimed. Current probes confirm a scratch/helper/hash predicate (1), linear count read (7), identity after graph destruction (1), accepted Copy capability extraction, and E1001 for borrowed linear variant/nested owner inspection. Mutual recursion returns 1; nontermination is stopped by fuel and recursive frame exhaustion by T0007. Claude independently reviewed the freshness proof and identified the need to freeze predicate classification under §8.7; proposed feature dependencies and immutable classifications are explicit. Q-057 records the missing non-consuming observation surface required before full contract coverage. Type/module invariants, audit statuses, diagnostics and vertical implementation remain open; RFC 0039 stays Draft and normative bundles are unchanged. diff --git a/docs/rfcs/0039-verifier-visible-contracts.md b/docs/rfcs/0039-verifier-visible-contracts.md index 13c9845..d490cf9 100644 --- a/docs/rfcs/0039-verifier-visible-contracts.md +++ b/docs/rfcs/0039-verifier-visible-contracts.md @@ -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` 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` is Copy. Ordinary type validity still applies, including the referent U of an iref. + +Predicate closure functions may hold Data by value, shared `ref`/`slice` observations of otherwise well-formed targets, and `mut`/`slice_mut`/`local` 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` 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` becomes `ref`, `slice_mut` becomes `slice`, 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` becomes `ref`, `slice_mut` becomes `slice`, 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.