diff --git a/docs/design/contract-invariant-boundaries.md b/docs/design/contract-invariant-boundaries.md new file mode 100644 index 0000000..3c4f63c --- /dev/null +++ b/docs/design/contract-invariant-boundaries.md @@ -0,0 +1,71 @@ +# Contract invariant boundaries: candidate and counterexamples + +Non-normative research for [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), 2026-10-09. No feature, type, opcode, code or source spelling below is adopted. The full P6-6 gate remains open, including module scope, statuses and proof rules. + +## Verified constraints + +Probes with the existing compiler at `d041c07` contain no invariant declarations. They expose coverage requirements, not compiler defects. Runs use fuel 10,000. + +| Probe | Result | Consequence | +|---|---|---| +| `Range {lo:0, hi:5}`; call `change(mut r.lo)` where `change(part: mut)` stores 10 | returns 1 for `lo > hi` | the callee's canonical AIR contains only `store %part, %value`; its signature/provenance does not identify the enclosing Range | +| ordinary `ValidRange {rep: Rep}` built by a checking library function; subsequently set `v.rep.lo = 10` | returns 1 for `lo > hi` | public fields bypass a constructor convention; spec 15 §14.2 permits imported construction and field access | +| two Counter roots; check `a.n <= b.n`, then change only a | returns 1 for failed relation | individual type claims or checks on a selected function set cannot imply a persistent relation between independent roots | +| AIR `type @Range = invariant @Rep @ordered` | E0001 | this declaration extension is outside spec 07 §8.7's E0004/E0006 exception | +| AIR parameter `checked<@Rep>` | E0004 alone, unknown type | a new type constructor has a different compatibility path | + +The earlier RFC probes also demonstrate invalid Copy publication and shared-reader overflow during a repaired exclusive update. End-of-borrow checks alone miss both. A complete eager alternative must find every affected invariant ancestor after projected writes, including scalar callees, graph nodes and buffer storage in other cells. Current interpreter places carry a cell/path, not enclosing invariant instances. It would require additional provenance and predicate access rules, including how to read a whole root while an exclusive child freezes it. + +## Leading type candidate: checked representation plus explicit update + +Investigate `checked` in AIR, source `checked`. Identity is structural over representation and resolved function identity. The predicate takes exactly `ref`, returns bool, and has no captures or implicit roots. Source uses existing explicit function resolution/specialization rules; a new nominal naming declaration is a separate choice, not an assumed alias feature. A generic representation is checked after concrete substitution. + +The claim is: every exposed checked value/shared content view satisfies its predicate. An explicit update temporarily exposes ordinary R under exclusive access; R carries no such claim. Whole checked values retain R's Copy/linear, size and structural concurrency classifications, subject to a complete property audit. Copies and transfers need no additional check. The representation is initialized as a complete value, and checked types have no zero constructor even when R is zeroable. + +| Candidate operation | Type/transfer | Validation boundary | +|---|---|---| +| `checked.make checked, %r` | R → checked; move linear R, copy Copy R | observe the complete candidate through a temporary shared view; run p before exposing the result; false traps | +| `checked.view %c` | ref> → ref, dependent owned shared child | no new check; ordinary lifetime/loan rules preserve the established claim | +| `checked.take %c` | checked → R; consume linear capsule, copy Copy content | output is ordinary R with no invariant claim; live views block consuming the root | +| `checked.modify %m, @f(args)` | mut>; direct callback f receives a temporary lent mut first, then ordinary typed arguments | suspend capsule access, call f, end its temporary mutation view, run p on the resulting R, then expose f's result | + +`make` needs an explicit new instruction-internal place for the complete R candidate, including Copy SSA values. Its predicate receives a dependent `ref` to that place, preserving R itself rather than unwrapping an owner root. The view and every child end before exposure of the result and cannot escape through bool. This adds no general AIR/source addressability for Copy SSA or partially initialized/linear frame locals. Use bounded activation storage, no program heap allocation; exact accounting and interaction with pending-result/local-frame budgets require integration. Existing `borrow.ref` on a Copy scalar or Copy struct SSA root rejects E1001; both baseline cases were independently verified. Their attempted `borrow.end` adds a dependent second E1001 because the invalid result has placeholder type void. + +These are proposed operation contracts, not syntax sugar for optional assertions. Ordinary operations cannot project mutable R from a checked value. Interior changes through shared atomic/mutex/endpoint/arc interfaces do not affect the claim because their mutable observations are outside S below. Whole-value store/exchange replaces it with another checked value. Existing `local.alloc`, owners, regions, arrays, buffers, graph storage, channels and mutexes must transport the complete new type under their existing content restrictions; no field write can manufacture it from R. Nested checked values remain checked when an enclosing representation is extracted. A Copy `take` leaves the capsule and its claim intact, while its plain R copy carries no claim. + +**Explicit update is necessary.** A linear representation with `buffer` held behind a borrow cannot be consumed and rebuilt directly. Replacing its capsule would otherwise need another complete buffer and allocation authority even for an in-capacity update. `checked.modify` must permit this update without allocating a replacement. Limiting the candidate to Copy reconstruction would omit required linear-state behavior. + +The callback can perform ordinary multi-field updates and use disjoint fields in structured tasks. Its complete effects and authority requirements propagate to the caller; ordinary critical-section/no-wait checks apply. It may return an ordinary borrow-free result, including an owned value removed through a complete initialized exchange. Void and never keep ordinary call/control rules: void binds no result, and a never callback cannot complete normally or publish an update. A borrow result or loan surviving the callback would escape unvalidated storage and must reject. It cannot re-enter the frozen capsule through another argument; ordinary overlapping-argument checks apply. No general borrow joins, holes or implicit cleanup are introduced. + +Successful callback completion is not yet successful update completion. Predicate false, callback/predicate traps or fuel exhaustion publish no checked result. Failure traps with no rollback of state or external effects. Pending borrow-free results, including linear ones, must be retained and traced until validation finishes. Candidate fuel accounting is one unit for the make/modify operation, then ordinary helper instructions, with no synthetic callback-to-predicate instruction. Callback and predicate use normal call frames, sequentially; the callback frame ends before the predicate starts. Exact dispatch, temporary-view and trap rules still require RFC integration and tests. Checking after a callback must use a legal shared view after its exclusive loan has ended, not privileged access through a frozen ancestor. + +Candidate source surface is an explicit function-based API: a shared `ref raw = checked.view(parent)` binding, whole-value `checked.make`/`checked.take`, and `checked.modify(parent, fn update, args...)` on a named exclusive binding. Callback specialization uses existing static function identity, not a runtime function value. Exact make/type grammar, source diagnostics and any later scoped block form remain decisions. A block form must specify captures and effects before adoption. + +## Stability is stronger than purity + +The predicate closure P in RFC 0039 excludes atomic, mutex, channel, authority and ambient observations. Caller-visible observations currently either require exclusive access to change or are deeply immutable; opaque iref identity retains no external graph root. This is a soundness premise for persistent checked claims. A read-only predicate over interior-mutable data could become false after construction without any capsule update. + +Define a candidate stable-observation closure S within P. All its caller-state observations must remain stable while the checked shared content is exposed. It uses the same direct-call closure and fresh-scratch proof; it does not imply totality. Initially the existing allowed observations satisfy this restriction. Future features must separately justify stable membership for their new operations; admitting a new operation to P alone is insufficient. Freeze each published classification rather than silently extending old invariants. Predicate construction/modification of checked values is excluded to avoid implicit validation dispatch; shared `checked.view` and Copy extraction of Data content are candidates for P/S. Data may admit checked when R is Data, subject to publication rules. Compute membership with memoized opcode/type scans and direct-call edge elimination, O(F+C) per closure after local scans. Predicate membership is checked after ordinary SSA/type validation, before accepting the new type; exact diagnostic ordering remains a delivery rule. + +Interior-mutable members need not be banned when the predicate ignores their mutable interior. A mutex containing ordinary data, an atomic field or a shared arc handle can still be held by R under ordinary rules. Their read/synchronization/count-changing operations stay outside S. Other allocations reached through unique owner/buffer/island roots inside R remain protected by the checked borrow ancestry; immutable frozen/arc content is stable. Audit this reasoning for every new observable primitive, rather than equating `effects []` with stability. + +## Module claims require explicit roots and scope + +AIR has one linked module, and source modules contain types/functions without globals or visibility. A module-state identity, hidden singleton or private-field policy cannot be inferred from spec 13's example. + +Two claims need distinct representations and audit scopes: + +- A persistent state-root invariant uses one caller-owned checked. A State struct can own several correlated roots. Shared views are valid everywhere, including across modules; updates use the explicit primitive. Independent subroots can be lent to joined tasks during an update, but moving a root out relinquishes the joint state claim unless a complete valid replacement remains. +- A boundary relation over separately owned roots is a predicate mapped to the explicit input/result bindings of listed functions. It holds only at covered entry/normal-exit boundaries, through RFC 0039 pre/post obligations. Unlisted code or public field access can break it between calls. Reports must identify boundary scope and covered functions, never present it as an all-values invariant. + +Choosing which source declaration spec 13 means by a module invariant, its root mapping and coverage rules remains part of the full gate. The state-root candidate supports explicit module state without adding globals; the boundary candidate does not provide hidden-state encapsulation. Neither closes that decision by changing the P6-6 requirement. + +## Compatibility, cost and remaining delivery + +The isolated type probe is not a complete AIR0 audit. Both Claude and the root independently checked full `checked<@Rep,@p>` spellings in seven positions: field, payload, parameter, return, borrowed parameter, block parameter and local allocation. Each aborts with E0004 alone. An opcode-first module with `checked.make`, `checked.take` and a normal use of the latter's result reports E0004, E0004, E5001. Together with the five initial probes and the two Copy-SSA borrow probes, all fifteen baseline cases were verified. These dependent errors retain the RFC 0039/0040 compatibility question (Q-055). No E0001 policy exception or format version is adopted here. + +This candidate adds a type form, four semantic operations, stable-closure classification and pending update dispatch. It avoids hidden per-write checks and runtime ancestor hooks. That cost must be compared against complete eager/epoch models, not only their simplest examples. The feature must depend on the published predicate rules; nested linear observations additionally need RFC 0040. Definition-only paths must not weaken verifier budgets or initialization. + +Delivery still needs registered features; exact grammar/type/function identity; closure and boundary diagnostics; false-invariant trap/status/report schemas; legal update/result/loan transfer rules; deterministic interpreter/native semantics; source lowering/formatter/generic/package coverage; and AIR/source positive/reject, GC and schedule tests. Mandatory cases include projected-callee bypass, invalid Copy escape, shared readers, borrowed linear in-place updates without new allocation, nested predicates, buffer/graph storage, mutex critical sections, callback results/traps/fuel, early exits and correlated roots. Measure normative/source/Quick Reference growth before acceptance; this research file is outside their manifests. + +Claude's read-only review identified the missing linear update in the extraction-only design and distinguished state-root from boundary claims. The proposal remains a candidate; no static proof, unsafe construction mode or completed P6-6 implementation is claimed. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 35c460e..5cc3649 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -401,6 +401,8 @@ P6-6 requires contracts and their four audit statuses, but spec 13 §1/spec 08 2026-10-09: the candidate function representation now uses a leading `contract.pre/old/post` prefix; all three isolated spellings currently reject E0004, avoiding Q-055's header-specific E0001 conflict. The used-result probe additionally reports E5001; complete rejection-code compatibility remains to be audited. Deferred post bindings require ordinary access checks at every return. Verified Range probes distinguish a repaired exclusive update from an invalid Copy escape and shared-reader overflow; exclusive-borrow end alone cannot establish publication coverage. Type/module invariant representation and predicate purity remain unresolved; no implementation is authorized. +[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. + ## 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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index a710524..ba73004 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -343,3 +343,9 @@ The purity increment supplies a closed opcode/type candidate, authority-free Cop RFC 0040 Draft develops Q-057 as a separate vertical prerequisite: selective shared enum dispatch and nested scalar/array owner views. Explicit `match ref place` creates only named payload views; skipped payloads stay owned, with no partial moves or general borrowed block joins. Current probes confirm a legal 65-payload enum returning 0 and E5101 for its value match. Unknown enum-view forms report E0004 alone; isolated owner-view forms report E0004, and a used owner-view result also reports E5001. All seven baseline probes are checked with the existing compiler; executed programs use fuel 10,000. Q-055's dependent-error interpretation remains open. These Draft rules allocate no feature/code and change no normative bundle, compiler or conformance fixture; type/module invariants, contract statuses and full P6-6 delivery remain open. Claude independently reviewed RFC 0040; corrections preserve existing E0004 name lookup, distinguish E2102 SSA origins from E2108 frame roots, count unreachable ingress and clarify unchanged complete-state joins and pattern-binder status. Three further source probes independently confirm both ref-parameter place spellings (combined result 6), wrong SSA-root return E2102 and Copy-frame escape E2108. All ten probes confirm only current-language constraints, not the proposed operations' implementation. + +The [invariant-boundary research](../design/contract-invariant-boundaries.md) advances RFC 0039's type/module gate. Five baseline probes confirm projected scalar mutation, a library-wrapper bypass and independent-root drift (all return 1), plus E0001 for a new declaration and E0004 for a new type constructor. Claude's independent review identified the need for explicit in-place update of borrowed linear representations; extraction/replacement alone can require new allocation authority. The checked-type candidate separates unvalidated representation updates from persistent shared claims and requires stable observations, callback effects/loan checks and pending-result validation. Module state-root and boundary-only relations retain distinct scopes; exact metadata, source rules, statuses/proofs and vertical delivery remain open. No feature, normative bundle or implementation changes; P6-6 remains doing. + +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. diff --git a/docs/rfcs/0039-verifier-visible-contracts.md b/docs/rfcs/0039-verifier-visible-contracts.md index 1d8358f..2d90c3b 100644 --- a/docs/rfcs/0039-verifier-visible-contracts.md +++ b/docs/rfcs/0039-verifier-visible-contracts.md @@ -110,6 +110,8 @@ Bindings identify function parameters, the prior snapshot, or the post-only plac 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. +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. 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. @@ -147,8 +149,12 @@ Eager enforcement requires root/projection tracking for every complete construct 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. +The [invariant-boundary research](../design/contract-invariant-boundaries.md) develops a third, leading candidate: a new checked representation type with explicit make/shared-view/extraction/update operations. Ordinary representation R has no invariant claim during a scoped callback update; validation precedes publication of the checked value/result. An extraction-only version is insufficient for borrowed linear state, so explicit in-place update is required. Stable observations, not merely observational purity, are a soundness premise. Five new current-language probes confirm projected scalar mutation, a library-wrapper bypass, independent-root drift and E0001 versus E0004 metadata spellings. The research preserves the unresolved full type/module gate and supplies no implementation authorization. + 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. +The candidate distinguishes a persistent checked state root owning correlated values from a named boundary relation over separately owned roots and an explicit function set. Their audit scopes and coverage claims must differ. Source module declarations, root mappings and any hidden-state abstraction still require a decision; ordinary pre/post reuse alone must not silently redefine module invariants. + 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