diff --git a/.github/workflows/coq-proof-gate.yml b/.github/workflows/coq-proof-gate.yml index 18bc2981..b3a156d8 100644 --- a/.github/workflows/coq-proof-gate.yml +++ b/.github/workflows/coq-proof-gate.yml @@ -138,3 +138,42 @@ jobs: exit 1 fi echo "OK: all proofs mechanised; no axioms." + + # Agda theory sources (formal/agda/, PROOF-POLICY §1). FAIL-CLOSED like the + # Coq job: the recipe fails if `agda` is absent, and every `*.agda` under + # formal/agda/ is checked without being listed. + # + # NOT the estate's pinned Agda. The proof lanes pin Agda 2.7.0.1 (mathesis + # `agda-proof-policy.yml`); this job runs Ubuntu 24.04's `agda-bin`, 2.6.3, + # and asserts that version so a silent package change fails the job. A run + # here is a real check under the canonical flags but is not receipt-grade. + # Provisioning 2.7.0.1 is an open owner decision (formal/agda/README.adoc). + agda-proofs: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + defaults: + run: + shell: bash + env: + AGDA_CI_VERSION: "2.6.3" + steps: + - uses: actions/checkout@v7.0.1 + + - name: Install Agda and just (Ubuntu packages) + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y -qq agda-bin just + + - name: Record and assert the prover version + run: | + set -euo pipefail + agda --version + just --version + agda --version | head -1 | grep -qxF "Agda version ${AGDA_CI_VERSION}" + + - name: Check every Agda module under the canonical flags + run: just -f formal/justfile check-agda + + - name: Planted controls — each must fail the gate + run: just -f formal/justfile check-agda-controls diff --git a/.gitignore b/.gitignore index 9924c052..857aa43a 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,8 @@ target/ *.install # Idris2 build artifacts (nested, e.g. under formal-verification dirs) **/solo-core/build/ +# Agda interface files (formal/agda) +*.agdai # Dependencies /node_modules/ diff --git a/docs/EXPLAINME.adoc b/docs/EXPLAINME.adoc index 49bfa51e..969350c6 100644 --- a/docs/EXPLAINME.adoc +++ b/docs/EXPLAINME.adoc @@ -122,7 +122,7 @@ rows are not listed here. | `proven` | coqc 8.18.0 | `formal/QttSemiring.v` -| Theory: no Agda source, so PROOF-POLICY gives it no proof witness grade (it is `ungraded`). The tables match `lib/quantity.ml` `q_add`/`q_mul` by inspection only. The CI gate does not cover 16 of the 21 laws. +| Theory. An Agda source now exists (`formal/agda/QttSemiring.agda`, all 21 statements, compared with this file in `formal/agda/README.adoc`), checked under the canonical flags on Agda 2.6.3 only. It is still `ungraded`: not checked on the pinned Agda 2.7.0.1, no Lean leg, no receipt, comparison not yet reviewed. The tables match `lib/quantity.ml` `q_add`/`q_mul` by inspection only. The CI gate does not cover 16 of the 21 laws. | P-4. QTT typing soundness for the real quantity checker | `open` @@ -238,7 +238,9 @@ row is a statement about a model, not about the shipped OCaml code, as each row's trust boundary says. *Proof Witness Grades.* Of the theory theorems above, 0 are at `PWG-3` or -better. All are `ungraded`, because none has an Agda source (PROOF-POLICY §8.1). +better. All are `ungraded` (PROOF-POLICY §8.1). `QttSemiring` alone has an Agda +source (`formal/agda/`); it has no receipt and no Lean leg yet. The others have +no Agda source. *Policy position.* PROOF-POLICY §1 puts theory proofs in Agda, rechecked in Rocq and Lean, and engineering properties of one system in Idris2. This diff --git a/formal/README.adoc b/formal/README.adoc index aa436f4f..0bc5bc9f 100644 --- a/formal/README.adoc +++ b/formal/README.adoc @@ -335,6 +335,8 @@ lift above (`RealWasm.v` / `RealCompile.v`, R0→R2) and the plan in [source,sh] ---- just -f formal/justfile check +just -f formal/justfile check-agda # Agda theory sources (formal/agda/) +just -f formal/justfile check-agda-controls # planted failures: each must fail the gate # or, by hand (F-1 Requires K-1, so compile K-1 first): cd formal for f in K1_CodegenPreservation K1Let_CodegenPreservation \ diff --git a/formal/agda/BORROW-PROVENANCE-EXPERIMENT.adoc b/formal/agda/BORROW-PROVENANCE-EXPERIMENT.adoc new file mode 100644 index 00000000..2d3b3e4b --- /dev/null +++ b/formal/agda/BORROW-PROVENANCE-EXPERIMENT.adoc @@ -0,0 +1,457 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) += Experiment: a provenance fibre as the soundness specification for the v1 borrow cut +:toc: + +Experiment for #553, run against the ADR-028 draft (PR #845, options D, E and +G) and the unsound programs of #847, including the sixteenth (`U-G1`) and the +revised cut D+R4. Module: `BorrowProvenance.agda`. Date: 2026-12-01 (UTC). +Compiler builds probed: `0c9677d` and this branch's head. + +This is an experiment on a toy model. It is not a proof about `lib/borrow.ml`, +and nothing in `lib/` was changed. + +== Result in brief + +The three obligations are stated and proved separately, in the model. + +[cols="1,3,2",options="header"] +|=== +| Obligation | Statement | Needs + +| (i) provenance inclusion +| The set the checker tracks for a reference contains its provenance fibre + at every program point (`G-holds`, `G-everywhere`). +| D (R1–R3) + +| (ii) exclusivity +| After any execution of an accepted program, two usable references to one + place are both shared (`exclusivity`). +| D and R4 + +| (iii) rejection +| A program that gets stuck on a use after move is rejected + (`stuck-rejected`, needs D). A program that reaches a non-exclusive store + is rejected (`aliasing-rejected`, needs D and R4). +| as stated +|=== + +. *Proved (in the model).* All three hold for D+R4. The #554 `pick` example + is rejected. +. *No refutation inside the model.* No D+R4 program escapes; the theorems + exclude one. Five #847 programs were encoded: `U-A2`, `U-B2`, `U-D1`, + `U-E3` and `U-G1`. The first four violate D and falsify (i). `U-G1` + satisfies D and (i), violates R4, and falsifies (ii). So R4 is needed, and + (i) alone does not catch `U-G1`: it is not a provenance failure. +. *Refuted, by measurement: the production checker is not sound on D+R4 as + worded.* Three unsound programs that satisfy R1–R4 are accepted by + `lib/borrow.ml` today (<>). They use only shared references, so + R4 does not touch them. They are not among #847's sixteen. The model's + checker rejects all three. + +So D+R4 has a proof target, and nothing inside the model argues for E. The +measured holes do: by the ADR's own test ("something inside D+R4 still +escapes"), the present implementation fails. Whether to close three more +holes or to take E is the owner's decision. <> says how the options move. + +== The model + +[cols="1,3",options="header"] +|=== +| Part | Content + +| Language +| Owned locals; `&x` and `&mut x`; ref-to-ref copy, annotated with the + static kind of the reference copied (`copy shr r`, `copy mut r`); + `consume(x)`; `*r`; a call to a reference-returning function, with + arguments passed in `ref` mode or as a shared reference by value; a branch + at the bind site; `expire r`. Also the first-class forms behind #847: a + reference in a tuple (`lettup`, `proj`), re-pointing (`assign`, + `assignif`), `&*r` as a primitive (`reborrow`), and a callee that returns + `(&x, 0).0` (`retwrap`). + +| Dynamic semantics +| A store of moved places and reference locals. A reference value *is* the + loan it came from (`loan x k`). `run` returns `nothing` when a step is + stuck: a use of a moved place, a dereference whose owner was moved, or an + unbound name. Branch outcomes come from an oracle `ℕ → Bool`. There is no + write statement. + +| Checker +| Per reference local, a set of loans (`TEnv`). Verdicts read a count per + place and kind (`cnt`, `free`, `noMut`). A copy's kind annotation is + checked against the set. On the first-class forms the checker drops the + "came from" edge, as the lexical checker is observed to: nothing is + tracked for a tuple, for `&*r`, for a wrapped return, or for an assignment + under `if`. It allows `copy mut r`, as the lexical checker does. + +| Cut D+R4 +| `R1`: a type-formation predicate `WF` (a reference is not a component of + an aggregate), applied to every type a statement forms. `R2`: no + assignment to a reference local. `R3`: no `reborrow` primitive; `elab` + rewrites it to a copy. `R4`: no `copy mut r`. `D p` is R1–R3 on every + statement; `R4 p` is separate. +|=== + +`Echo` is echo-types' definition (`proofs/agda/Echo.agda` at `140002f`), +restated at universe level 0 because this directory takes no library. Nothing +else comes from echo-types. Nothing comes from ephapax. + +== Statements + +The fibre is taken over executions. `valueAt p r` maps an execution (an +oracle) to the loan `r` holds after `p`. The fibre over a loan is the set of +executions that leave that loan in `r`. + +[source,agda] +---- +Echo : {A B : Set} (f : A → B) → B → Set +Echo {A} f y = Σ A (λ x → f x ≡ y) + +valueAt : Prog → Var → Oracle → Maybe Loan +valueAt p r ρ = run ρ init p >>= λ s → lookup r (snd s) + +Fibre : Prog → Var → Loan → Set +Fibre p r ℓ = Echo (valueAt p r) (just ℓ) + +G : Prog → Set +G p = {M : List Var} {Γ : TEnv} → chk initC p ≡ just (M , Γ) → + (r : Var) (ℓ : Loan) → Fibre p r ℓ → + Σ (List Loan) (λ L → (lookup r Γ ≡ just L) × (ℓ ∈ L)) + +-- "v is compatible with the references bound before it" +Compat : Loan → Env Loan → Set +Compat (loan x shr) σ = NoMutH x σ -- none of them is exclusive on x +Compat (loan x mut) σ = FreeH x σ -- none of them is on x + +Excl : Env Loan → Set +Excl [] = ⊤ +Excl ((r , v) ∷ σ) = Compat v σ × Excl σ +---- + +Proved, with no postulate and no warning: + +[source,agda] +---- +-- (i) +G-holds : (p : Prog) → D p → G p +G-everywhere : (p q : Prog) → D (p ++ q) → G p + +safety : (p : Prog) → D p → {M : List Var} {Γ : TEnv} → + chk initC p ≡ just (M , Γ) → (ρ : Oracle) → + Σ (Env Loan) (λ σ → (run ρ init p ≡ just (M , σ)) × Inv M σ Γ) + +-- (ii) +exclusivity : (p : Prog) → D p → R4 p → {M : List Var} {Γ : TEnv} → + chk initC p ≡ just (M , Γ) → (ρ : Oracle) → + Σ (Env Loan) (λ σ → (run ρ init p ≡ just (M , σ)) × Excl σ) + +-- (iii) +stuck-rejected : (p : Prog) → D p → (ρ : Oracle) → + run ρ init p ≡ nothing → chk initC p ≡ nothing +aliasing-rejected : (p : Prog) → D p → R4 p → (ρ : Oracle) {s : Store} → + run ρ init p ≡ just s → ¬ Excl (snd s) → chk initC p ≡ nothing + +K1-rejected : chk initC K1 ≡ nothing -- by running the checker +K1-rejected-by-theorem : chk initC K1 ≡ nothing -- from stuck-rejected +---- + +`K1` is `let r = pick(a); consume(a); *r`. `S10` (a call that may return +either argument, a use, expiry, then a move) and `S12` (a shared reference +copied, both used) are in D+R4 and accepted, so the theorems are not vacuous. + +`Inv` is the invariant that carries (i): the two stores bind the same names, +each held loan is in its tracked set, and no tracked loan is on a moved place. +(ii) is proved on top of it. + +(iii) is the contrapositive of (i)'s safety and of (ii). It says the checker +rejects every *program whose execution goes wrong*. It does not say the +checker rejects only those; the model's checker over-rejects (it has no +inferred liveness). + +== The #847 programs + +`P` is the program point at which the obligation fails. + +[cols="1,3,2,2,3,2",options="header"] +|=== +| Id | Program | In D+R4? | First-class checker | Obligation that fails at `P` | Run + +| `U-A2` (A) +| `let r = &a; let t = (r, 0); consume(a); *(t.0)` +| `UA2-not-D`: fails R1 +| `UA2-accepted` +| (i), `UA2-not-G`: `t` holds `loan a shr`, tracked `[]` +| `UA2-stuck` + +| `U-E3` (E) +| `let r = &x; let r2 = &*r; consume(x); *r2` +| `UE3-not-D`: fails R3 +| `UE3-accepted` +| (i), `UE3-not-G`: `r2` holds `loan x shr`, tracked `[]` +| `UE3-stuck` + +| `U-D1` (D) +| `fn wrap(ref x) -> ref Int { return (&x, 0).0; }` … `let r = wrap(a); consume(a); *r` +| `UD1-not-D`: fails R1 in the callee +| `UD1-accepted` +| (i), `UD1-not-G`: tracked `[]` +| `UD1-stuck` + +| `U-B2` (B) +| `let mut r = pick(a); if c { r = pick(b); } consume(b); *r` +| `UB2-not-D`: fails R2 +| `UB2-accepted` +| (i), `UB2-not-G`: on the taken branch `r` holds `loan b shr`, tracked `[loan a shr]` +| `UB2-stuck` (taken branch) + +| `U-G1` (16th) +| `let r = &mut x; let r2 = r;` (then `*r2 = 99; *r = 100; *r2`) +| in D (`UG1-D`); `UG1-not-R4`: fails R4 +| `UG1-accepted` +| (ii), `UG1-not-Excl`: `r` and `r2` both hold `loan x mut`. (i) *holds*: `UG1-G`. +| `UG1-run` (does not get stuck; the writes are not modelled) +|=== + +For `U-E3`, the elaborated program is in D (`UE3-elab-D`) and is rejected +(`UE3-elab-rejected`). That is R3 followed by the ref-to-ref rule, as the ADR +predicts. The control `K-4` (two direct `&mut x`) is rejected (`K4-rejected`). + +Verdict for each: *D+R4 excludes it.* None satisfies D+R4 and escapes. + +A caveat on how much this shows. In the model the first-class forms are +separate constructors and the cut is defined to exclude them, so "violates +D+R4" is close to true by construction. The informative parts are the +theorems (the cut is enough), the `…-accepted` facts with the failing +obligation (without the cut, the obligation is false), and `UG1-G` (the +provenance statement cannot see `U-G1`). The `expire r` in `U-A2` and `U-E3` +stands for last-use expiry; without it the model's checker rejects them for a +different reason. + +[#measured] +== Measured: three holes inside D+R4 in the production checker + +While choosing what to encode, unsound programs that satisfy the cut were run +through the real compiler (`_build/default/bin/main.exe check`). `pick` and +`consume` are as in the ADR's kit. + +[cols="1,4,2,2",options="header"] +|=== +| Id | Program | Production checker | Model + +| `D-01` +| `fn pass(r: ref Int) -> ref Int { return r; }` … `let r = &a; let s = pass(r); consume(a); *s` +| *accepts* (use after move) +| `D01-rejected`; in D+R4 (`D01-D`, `D01-R4`) + +| `D-06` +| `let r = &a; let s = pick(*r); consume(a); *s` +| *accepts* (use after move) +| `D06-rejected`, reading the argument `*r` as passing `r` + +| `D-19` +| `fn f(ref x: Int, c: Bool) -> ref Int { let r = if c { &x } else { &x }; return r; }` … `let r = f(a, true); consume(a); *r` +| *accepts* (use after move). Also with `match`, and with a block `{ &x }`. +| `D19-rejected`; in D+R4 (`D19-D`, `D19-R4`) +|=== + +A fourth program found the same way, `let r = &mut x; let s = r; *s = 1; +*r = 2; *s`, is `U-G1`, which the #553 thread found independently and added +to #847. R4 excludes it. + +Controls that are rejected, correctly: `pass(&a)` in place of `pass(r)`; +`return if c { &x } else { &x }` and the early-return form in place of the +bound local; `K-1`, `K-2`. Baseline: `U-A2`, `U-B2`, `U-D1`, `U-E3` and +`U-G1` are accepted, as #847 reports. + +Each of the three uses a shared reference only as a parameter type, a +`let`-local or a return type, never re-points one, never writes `&*r`, and +never copies an exclusive reference. So each passes R1–R4 as worded. All +three are obligation (i) failures: the production checker loses a "came +from" edge that the cut does not forbid. + +How they relate to the proof: + +* `D-01` is the `byref` case of `arg-sim`: a reference passed by value must + carry its tracked set through the callee's summary. +* `D-19` is the `retif` case of `F-sim`: the summary must take the union over + the callee's branches. A planted mutation that drops one branch breaks that + proof case (<>). +* `D-06` needs a reading for `*r` in a `ref`-mode argument. R3 covers only + `&*r`. The model treats it as passing `r`. + +Not checked: whether these are recorded elsewhere. A search of +`issues-drafts/`, `docs/SOUNDNESS.adoc`, the "Still deferred" trailer of +`lib/borrow.ml` and the ADR's kit found none of them. No issue was filed from +this session. + +One more observation, not followed up: that trailer says +`let r = if c { &a } else { &b }` is accepted. On `0c9677d` it is rejected +(`consume(b); *r` after it gives a borrow error), as is the `pick` form. + +Reproduction: save each row's program after the kit header from ADR-028 +appendix A.4 and run `main.exe check`. + +== Liveness: a count or a set? + +Only what the proofs used is reported. + +=== For (i) and the use-after-move verdict + +* *The verdict needs a count, and only whether it is zero.* `free` and + `noMut` read `cnt k x Γ`, the number of tracked loans of kind `k` on place + `x`. The proof of (i) reads the counts in one lemma, `Inv-consume`, and + uses one fact: a zero count means no tracked loan is on `x`. +* *Keeping the state needs the sets.* `expire r` removes `r`'s entry. The + counts then fall for exactly the places in `r`'s set. A state made only of + counts cannot take that step. `G` also cannot be stated without the sets. + +=== For (ii), exclusivity + +* *The statement is count-shaped.* `Excl` says: per place, either no usable + exclusive reference, or exactly one usable reference in all. That is a + bound on two counts per place (exclusive ≤ 1; exclusive = 1 implies + shared = 0). No set of loans appears in it. `Excl` is written by recursion + over the store and not as counts; the two forms were not proved equal. +* *The verdicts that establish it read zero or non-zero counts.* `&mut x` + needs both counts on `x` to be zero (`free-held`). `&x` needs the + exclusive count to be zero (`nomut-held`). Those two lemmas are the only + places (ii) reads the checker's state. +* *R4 is not a count.* It is a fact about one reference: its kind. In the + model that is the annotation on `copy`, checked against the reference's + own set (`allKind`). A per-place grade does not carry it; a type does. +* *Maintenance still needs the sets*, for the same reason as above: expiry + must lower the counts of the places one reference held, and a copy of a + shared reference must raise them. + +So a per-place, per-kind occupancy-style grade fits the *verdict* and the +*statement* of (ii), with peak 1 for the exclusive kind. It does not fit the +*bookkeeping*: which entries of the vector change when a reference is made, +copied or dies is given by provenance, which is set-valued. This agrees with +the ADR's paragraph "What survives". Not tested: inferred liveness (expiry +points are given here), loops, two-phase borrows, and whether such a vector +fits occupancy-types' rule that grades are static. + +== Aggregates as a map over fibres + +`lettup-is-letref` is proved by `refl`: dynamically, binding a tuple with one +reference slot is binding that reference. So a checker that gives the +aggregate the set of its component is covered by the `letref` case, and (i) +holds for it with no new proof. + +Argued, not mechanised: for several slots, track the union and let a +projection return the whole union. That is sound and field-insensitive. +Not addressed: field mutation (which is re-pointing, class B, and needs a +union at joins), nested aggregates, closures (class C), and (ii) for +aggregates holding exclusive references. + +For option A this suggests the soundness side of aggregates is cheap for (i). +The constraint-design gap that remains is precision (field sensitivity) and +re-pointing under control flow. The experiment says nothing about either. + +[#adr] +== What changes in ADR-028 + +[cols="1,3",options="header"] +|=== +| Option | Change + +| G +| Verified as *one lemma* of P-3, as the revised ADR treats it: an Agda type + under the canonical flags, provable for D in a model, false for four #847 + programs, and true of `U-G1`. So (i) needs (ii) and (iii) beside it. + +| D+R4 +| *Proved in the model; not yet true of the implementation.* All three + obligations hold for D+R4 against the model's checker, and R4 is shown + necessary (`U-G1`). But `D-01`, `D-06` and `D-19` are inside D+R4 and are + accepted by `lib/borrow.ml`. D+R4's experiment, as the ADR words it, would + fail on them. To pass it D+R4 needs either three checker fixes or three + more rules, for example: no reference-typed by-value parameter (or a + summary for one); a summary through locals bound by `if`, `match` and a + block; `*r` as a `ref`-mode argument is a copy of `r`. + +| E +| Not argued for by the model. Supported by the measurement: each round of + probing the reference surface has found holes the previous rule set did + not cover (15, then `U-G1`, then these three). That is evidence about the + implementation, not a proof that D+R4 cannot be made sound. + +| A +| The aggregate note above; a small narrowing for (i), argued and not proved. +|=== + +Overall: *D+R4 proved against an adequate abstract checker; D+R4 as currently +implemented refuted on three programs.* One result of each kind. + +[#controls] +== What was run + +All under Agda 2.6.3 (Ubuntu 24.04 `agda-bin`). The pinned 2.7.0.1 was not +available, so these are checks and not receipt-grade runs. + +* `just -f formal/justfile check-agda`: 2 modules, exit 0, no warning. +* `just -f formal/justfile check-agda-controls`: all 5 planted controls fail + the gate. +* Nine mutations of `BorrowProvenance.agda`, each in a scratch copy. Each made + Agda fail (exit 42): R3 admits `reborrow`; R1 admits a reference in a + tuple; R2 admits `assignif`; R4 admits `copy mut`; `consume` ignores loans; + `&mut` checks only the exclusive count; a by-value argument is not checked + to be shared; the summary drops a branch; `expire` leaves the dynamic + binding in place. +* The probe programs of <> and `U-G1`, through the real compiler. +* `just check` (lint, `dune runtest`, the five guards): exit 0, 0 test + failures. The container first lacked the `tree-sitter` CLI and the vendored + grammar, which the walker tests require; they were installed + (`cargo install tree-sitter-cli`, `just install-grammar`) and the run + repeated. No test was skipped or changed. + +[cols="2,2",options="header"] +|=== +| Measure | Value + +| `BorrowProvenance.agda`, total lines | 1358 +| of which code (no comments, no blank lines) | 942 +| of which the D+R4 extension (obligations ii and iii, `U-G1`) | about 350 total lines +| Agda check time, both modules | about 4 s +| Agent wall-clock, first read to green gate, obligation (i) | about 20 minutes +| Agent wall-clock, D+R4 extension | about 15 minutes +| First full check of each part | passed with no error and no warning +|=== + +The one tooling cost: under `--cubical-compatible`, a `refl` match that needs +constructor injectivity raises `UnsupportedIndexedMatch`, which the gate +fails. Equations between constructor forms are taken apart with `cong` +(`just-inj`, `state-inv`), and relations are defined by recursion, as the +pilot did. + +== Not established + +* *Any link to `lib/borrow.ml`.* The model's checker was written for this + experiment. The measured holes show the real checker differs from it. +* *Exclusivity under writes.* (ii) is a property of the store of usable + references. There is no write statement, so "a write through one reference + is not seen through another" is not stated. Moving an exclusive reference + (what a user writes instead of the copy R4 forbids) is not modelled either. +* *Completeness.* Nothing says the checker accepts a sound program. +* *Closures (class C), loops, block scopes, a dangling return (`U-A6`, + `K-5`).* Not in the language. +* *Inferred liveness.* Expiry points are part of the program text. +* *Any backend.* #848 (references lowered as copies on core wasm) is outside + the model. +* *Rocq and Lean legs.* None. This is an experiment, so none was attempted, + and the module is `ungraded`. No receipt exists. +* *The pinned Agda.* See above. +* *A different reading of the fibre.* Here the fibre is over executions. If + one reads `f` as the identity on loan-carrying values, the fibre is a + singleton and the statement is the invariant `Inv` itself. + +== Beyond this repository + +* The three holes, if confirmed, belong on the v1 ledger (#563) and in + `docs/SOUNDNESS.adoc`, next to #847. +* If (i) is kept as a lemma of P-3, echo-types could carry a "fibre of a run + map" instance. That is for `hyperpolymath/nextgen-typing` + `docs/TYPE-CONNECTIONS.adoc`, not for this record. +* The liveness note bears on occupancy-types' static-grade rule. It was not + tested there. diff --git a/formal/agda/BorrowProvenance.agda b/formal/agda/BorrowProvenance.agda new file mode 100644 index 00000000..c950abe7 --- /dev/null +++ b/formal/agda/BorrowProvenance.agda @@ -0,0 +1,1358 @@ +{-# OPTIONS --safe --without-K --cubical-compatible #-} +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- BorrowProvenance.agda +-- ═════════════════════ +-- EXPERIMENT for #553 / ADR-0028 (PR #845), option G: is an echo-types +-- provenance fibre a provable soundness SPECIFICATION for the v1 cut "D" +-- (second-class references)? The record, with what is and is not +-- established, is `formal/agda/BORROW-PROVENANCE-EXPERIMENT.adoc`. +-- +-- What is modelled (a toy, NOT `lib/borrow.ml`): +-- * owned locals, `&x` / `&mut x`, ref-to-ref copy, `consume`, `*r`, +-- functions returning a reference (`pick`), a branch at the bind site, +-- and an explicit expiry point `expire r`; +-- * the first-class constructs behind #847's classes A, B, D and E, with +-- the checker dropping the "came from" edge as the lexical checker is +-- observed to; +-- * a dynamic semantics in which a reference value IS the loan it came +-- from, and which gets stuck on a use after move; +-- * ADR-0028's rules R1 (type formation), R2 (no re-pointing), R3 (no +-- reborrow primitive) and R4 (an exclusive reference is not copyable) +-- as predicates. +-- +-- What is NOT modelled: writes (exclusivity is proved as a property of the +-- store of usable references, section (e); nothing is said about a write), +-- moving an exclusive reference, closures (class C), loops, block scopes, dangling returns +-- (U-A6 / K-5), inferred liveness (expiry points are given, not computed), +-- and every backend (#848). +-- +-- `Echo` below is echo-types' definition (`proofs/agda/Echo.agda`, commit +-- 140002f) restated at universe level 0, because this directory takes no +-- library: `Echo f y = Σ x. f x ≡ y`, the standard preimage fibre. Nothing +-- else is taken from echo-types, and nothing from ephapax. +-- +-- Checked with exactly `agda --safe --without-K --cubical-compatible` +-- (`just -f formal/justfile check-agda`). Import cone: this file and +-- `Agda.Builtin.{Nat,Bool,Equality,List,Maybe,Sigma}`. +-- +-- A note on style: under these flags a `refl` match that needs constructor +-- injectivity raises UnsupportedIndexedMatch, which the gate fails. So +-- equations between constructor forms are taken apart with `cong`, and +-- `refl` is matched only where one side is a variable. + +module BorrowProvenance where + +open import Agda.Builtin.Nat using (zero; suc; _+_; _==_) renaming (Nat to ℕ) +open import Agda.Builtin.Bool using (Bool; true; false) +open import Agda.Builtin.Equality using (_≡_; refl) +open import Agda.Builtin.List using (List; []; _∷_) +open import Agda.Builtin.Maybe using (Maybe; just; nothing) +open import Agda.Builtin.Sigma using (Σ; _,_; fst; snd) + +------------------------------------------------------------------------ +-- Logic and small library (defined here; no agda-stdlib) + +data ⊥ : Set where + +record ⊤ : Set where + constructor tt + +infix 3 ¬_ +¬_ : Set → Set +¬ A = A → ⊥ + +infixr 2 _×_ +_×_ : Set → Set → Set +A × B = Σ A (λ _ → B) + +infixr 1 _⊎_ +data _⊎_ (A B : Set) : Set where + inl : A → A ⊎ B + inr : B → A ⊎ B + +sym : {A : Set} {x y : A} → x ≡ y → y ≡ x +sym refl = refl + +trans : {A : Set} {x y z : A} → x ≡ y → y ≡ z → x ≡ z +trans refl e = e + +cong : {A B : Set} (f : A → B) {x y : A} → x ≡ y → f x ≡ f y +cong f refl = refl + +subst : {A : Set} (P : A → Set) {x y : A} → x ≡ y → P x → P y +subst P refl p = p + +infix 0 if_then_else_ +if_then_else_ : {A : Set} → Bool → A → A → A +if true then a else b = a +if false then a else b = b + +not : Bool → Bool +not true = false +not false = true + +infixr 6 _∧_ +_∧_ : Bool → Bool → Bool +true ∧ b = b +false ∧ b = false + +isZero : ℕ → Bool +isZero zero = true +isZero (suc _) = false + +b2n : Bool → ℕ +b2n true = 1 +b2n false = 0 + +infixr 5 _++_ +_++_ : {A : Set} → List A → List A → List A +[] ++ ys = ys +(x ∷ xs) ++ ys = x ∷ (xs ++ ys) + +infixl 1 _>>=_ +_>>=_ : {A B : Set} → Maybe A → (A → Maybe B) → Maybe B +nothing >>= f = nothing +just a >>= f = f a + +when : {A : Set} → Bool → Maybe A → Maybe A +when c m = if c then m else nothing + +fromJust : {A : Set} → A → Maybe A → A +fromJust d nothing = d +fromJust d (just a) = a + +just-inj : {A : Set} {a b : A} → just a ≡ just b → a ≡ b +just-inj {a = a} e = cong (fromJust a) e + +nothing≢just : {A : Set} {a : A} → nothing ≡ just a → ⊥ +nothing≢just () + +false≢true : false ≡ true → ⊥ +false≢true () + +bind-inv : {A B : Set} (m : Maybe A) (f : A → Maybe B) {b : B} → + (m >>= f) ≡ just b → Σ A (λ a → (m ≡ just a) × (f a ≡ just b)) +bind-inv nothing f () +bind-inv (just a) f e = a , refl , e + +bind-intro : {A B : Set} {m : Maybe A} {f : A → Maybe B} {a : A} {b : B} → + m ≡ just a → f a ≡ just b → (m >>= f) ≡ just b +bind-intro refl e = e + +when-inv : {A : Set} (c : Bool) {m : Maybe A} {b : A} → + when c m ≡ just b → (c ≡ true) × (m ≡ just b) +when-inv false () +when-inv true e = refl , e + +when-intro : {A : Set} {c : Bool} {m : Maybe A} → c ≡ true → when c m ≡ m +when-intro refl = refl + +∧-l : (a b : Bool) → (a ∧ b) ≡ true → a ≡ true +∧-l true b e = refl +∧-l false b () + +∧-r : (a b : Bool) → (a ∧ b) ≡ true → b ≡ true +∧-r true b e = e +∧-r false b () + +not-true : (b : Bool) → not b ≡ true → b ≡ false +not-true false e = refl +not-true true () + +zero-+ : (m n : ℕ) → isZero (m + n) ≡ true → + (isZero m ≡ true) × (isZero n ≡ true) +zero-+ zero n e = refl , e +zero-+ (suc m) n () + +b2n-zero : (b : Bool) → isZero (b2n b) ≡ true → b ≡ false +b2n-zero false e = refl +b2n-zero true () + +------------------------------------------------------------------------ +-- The echo fibre (echo-types `Echo`, restated; see the header) + +Echo : {A B : Set} (f : A → B) → B → Set +Echo {A} f y = Σ A (λ x → f x ≡ y) + +------------------------------------------------------------------------ +-- Syntax + +Var : Set +Var = ℕ + +data Kind : Set where + shr mut : Kind + +-- A loan: the place borrowed and the kind of borrow. +data Loan : Set where + loan : Var → Kind → Loan + +owner : Loan → Var +owner (loan x k) = x + +-- Types, only as far as rule R1 needs them. +data Ty : Set where + int ref : Ty + tup : Ty → Ty -- `(T, Int)`: an aggregate with one T slot + +NoRef : Ty → Set +NoRef int = ⊤ +NoRef ref = ⊥ +NoRef (tup t) = NoRef t + +-- R1, type formation: a reference may be a parameter, a let-local or a +-- return type, never a component of an aggregate. +WF : Ty → Set +WF int = ⊤ +WF ref = ⊤ +WF (tup t) = NoRef t + +-- A call argument: an owned local passed in `ref` mode, or a SHARED +-- reference local passed by value (the checker refuses a `&mut` here; the +-- toy has no by-value `&mut` argument). +data Arg : Set where + own : Var → Arg + byref : Var → Arg + +-- The body of a reference-returning function, by parameter index. +data FBody : Set where + ret : ℕ → FBody -- return &p_i (or p_i, a ref) + retif : ℕ → FBody → FBody → FBody -- if c { … } else { … } + retwrap : ℕ → FBody -- return (&p_i, 0).0 (class D) + +data RExp : Set where + borrow : Kind → Var → RExp -- &x, &mut x + copy : Kind → Var → RExp -- r, of type `ref T` (shr) or `mut T` (mut) + reborrow : Kind → Var → RExp -- &*r, &mut *r (class E, first-class) + proj : Var → RExp -- t.0 (class A) + call : FBody → List Arg → RExp -- f(ā) + choose : ℕ → RExp → RExp → RExp -- if c { e₁ } else { e₂ } + +data Stmt : Set where + letref : Var → RExp → Stmt -- let r = e + lettup : Var → RExp → Stmt -- let t = (e, 0) (class A) + assign : Var → RExp → Stmt -- r = e (K-6) + assignif : ℕ → Var → RExp → Stmt -- if c { r = e } (class B) + consume : Var → Stmt -- consume(x): moves x + deref : Var → Stmt -- *r + expire : Var → Stmt -- r is dead from here (given, not inferred) + +Prog : Set +Prog = List Stmt + +------------------------------------------------------------------------ +-- Environments + +Env : Set → Set +Env A = List (Var × A) + +lookup : {A : Set} → Var → Env A → Maybe A +lookup r [] = nothing +lookup r ((s , a) ∷ e) = if r == s then just a else lookup r e + +remove : {A : Set} → Var → Env A → Env A +remove r [] = [] +remove r ((s , a) ∷ e) = if r == s then e else (s , a) ∷ remove r e + +mem : Var → List Var → Bool +mem y [] = false +mem y (x ∷ M) = if x == y then true else mem y M + +nth : {A : Set} → ℕ → List A → Maybe A +nth i [] = nothing +nth zero (a ∷ as) = just a +nth (suc i) (a ∷ as) = nth i as + +------------------------------------------------------------------------ +-- Dynamic semantics (idealised). A reference value is the loan it came +-- from. `nothing` is "stuck": a use after move, or an unbound name. + +Oracle : Set +Oracle = ℕ → Bool -- the run-time value of each branch condition + +Store : Set +Store = List Var × Env Loan -- moved owned locals; reference locals + +alive : List Var → Loan → Bool +alive M ℓ = not (mem (owner ℓ) M) + +evalArg : List Var → Env Loan → Arg → Maybe Loan +evalArg M σ (own x) = when (not (mem x M)) (just (loan x shr)) +evalArg M σ (byref r) = lookup r σ + +evalArgs : List Var → Env Loan → List Arg → Maybe (List Loan) +evalArgs M σ [] = just [] +evalArgs M σ (a ∷ as) = + evalArg M σ a >>= λ v → evalArgs M σ as >>= λ vs → just (v ∷ vs) + +runF : Oracle → FBody → List Loan → Maybe Loan +runF ρ (ret i) vs = nth i vs +runF ρ (retif c b₁ b₂) vs = if ρ c then runF ρ b₁ vs else runF ρ b₂ vs +runF ρ (retwrap i) vs = nth i vs + +evalR : Oracle → List Var → Env Loan → RExp → Maybe Loan +evalR ρ M σ (borrow k x) = when (not (mem x M)) (just (loan x k)) +evalR ρ M σ (copy k r) = lookup r σ +evalR ρ M σ (reborrow k r) = lookup r σ +evalR ρ M σ (proj t) = lookup t σ +evalR ρ M σ (call b as) = evalArgs M σ as >>= runF ρ b +evalR ρ M σ (choose c e₁ e₂) = if ρ c then evalR ρ M σ e₁ else evalR ρ M σ e₂ + +step : Oracle → Store → Stmt → Maybe Store +step ρ (M , σ) (letref r e) = evalR ρ M σ e >>= λ v → just (M , (r , v) ∷ σ) +step ρ (M , σ) (lettup t e) = evalR ρ M σ e >>= λ v → just (M , (t , v) ∷ σ) +step ρ (M , σ) (assign r e) = + lookup r σ >>= λ _ → evalR ρ M σ e >>= λ v → just (M , (r , v) ∷ σ) +step ρ (M , σ) (assignif c r e) = + lookup r σ >>= λ _ → + if ρ c then (evalR ρ M σ e >>= λ v → just (M , (r , v) ∷ σ)) else just (M , σ) +step ρ (M , σ) (consume x) = when (not (mem x M)) (just (x ∷ M , σ)) +step ρ (M , σ) (deref r) = lookup r σ >>= λ v → when (alive M v) (just (M , σ)) +step ρ (M , σ) (expire r) = lookup r σ >>= λ _ → just (M , remove r σ) + +run : Oracle → Store → Prog → Maybe Store +run ρ s [] = just s +run ρ s (c ∷ p) = step ρ s c >>= λ s′ → run ρ s′ p + +------------------------------------------------------------------------ +-- The abstract checker. Per reference local it tracks a SET of loans. +-- Its verdicts read only a count per place and kind (`cnt`). + +TEnv : Set +TEnv = Env (List Loan) + +CState : Set +CState = List Var × TEnv + +hit : Kind → Var → Loan → ℕ +hit shr x (loan y shr) = b2n (x == y) +hit shr x (loan y mut) = 0 +hit mut x (loan y shr) = 0 +hit mut x (loan y mut) = b2n (x == y) + +cntL : Kind → Var → List Loan → ℕ +cntL k x [] = 0 +cntL k x (ℓ ∷ L) = hit k x ℓ + cntL k x L + +-- How many tracked loans of kind k are on place x. +cnt : Kind → Var → TEnv → ℕ +cnt k x [] = 0 +cnt k x ((r , L) ∷ Γ) = cntL k x L + cnt k x Γ + +free : Var → TEnv → Bool -- no loan of either kind on x +free x Γ = isZero (cnt shr x Γ) ∧ isZero (cnt mut x Γ) + +noMut : Var → TEnv → Bool -- no `&mut` loan on x +noMut x Γ = isZero (cnt mut x Γ) + +okBorrow : Kind → Var → TEnv → Bool +okBorrow shr x Γ = noMut x Γ +okBorrow mut x Γ = free x Γ + +isKind : Kind → Loan → Bool +isKind shr (loan y shr) = true +isKind shr (loan y mut) = false +isKind mut (loan y shr) = false +isKind mut (loan y mut) = true + +-- Every loan in the set has kind k: the static type of the reference. +allKind : Kind → List Loan → Bool +allKind k [] = true +allKind k (ℓ ∷ L) = isKind k ℓ ∧ allKind k L + +trackArg : List Var → TEnv → Arg → Maybe (List Loan) +trackArg M Γ (own x) = when (not (mem x M) ∧ noMut x Γ) (just (loan x shr ∷ [])) +trackArg M Γ (byref r) = lookup r Γ >>= λ L → when (allKind shr L) (just L) + +trackArgs : List Var → TEnv → List Arg → Maybe (List (List Loan)) +trackArgs M Γ [] = just [] +trackArgs M Γ (a ∷ as) = + trackArg M Γ a >>= λ L → trackArgs M Γ as >>= λ Ls → just (L ∷ Ls) + +-- The return-borrow summary of a function body (the #554 fix), applied to +-- the tracked sets of the arguments. `retwrap` drops the edge (class D). +summF : FBody → List (List Loan) → Maybe (List Loan) +summF (ret i) Ls = nth i Ls +summF (retif c b₁ b₂) Ls = summF b₁ Ls >>= λ L₁ → summF b₂ Ls >>= λ L₂ → just (L₁ ++ L₂) +summF (retwrap i) Ls = nth i Ls >>= λ _ → just [] + +-- `reborrow` records no loan (class E). +trackR : List Var → TEnv → RExp → Maybe (List Loan) +trackR M Γ (borrow k x) = when (not (mem x M) ∧ okBorrow k x Γ) (just (loan x k ∷ [])) +trackR M Γ (copy k r) = lookup r Γ >>= λ L → when (allKind k L) (just L) +trackR M Γ (reborrow k r) = lookup r Γ >>= λ _ → just [] +trackR M Γ (proj t) = lookup t Γ +trackR M Γ (call b as) = trackArgs M Γ as >>= summF b +trackR M Γ (choose c e₁ e₂) = + trackR M Γ e₁ >>= λ L₁ → trackR M Γ e₂ >>= λ L₂ → just (L₁ ++ L₂) + +-- `lettup` tracks nothing for the aggregate (class A); `assignif` leaves +-- the binder's set as it was before the branch (class B). +check : CState → Stmt → Maybe CState +check (M , Γ) (letref r e) = trackR M Γ e >>= λ L → just (M , (r , L) ∷ Γ) +check (M , Γ) (lettup t e) = trackR M Γ e >>= λ _ → just (M , (t , []) ∷ Γ) +check (M , Γ) (assign r e) = + lookup r Γ >>= λ _ → trackR M Γ e >>= λ L → just (M , (r , L) ∷ Γ) +check (M , Γ) (assignif c r e) = + lookup r Γ >>= λ _ → trackR M Γ e >>= λ _ → just (M , Γ) +check (M , Γ) (consume x) = when (not (mem x M) ∧ free x Γ) (just (x ∷ M , Γ)) +check (M , Γ) (deref r) = lookup r Γ >>= λ _ → just (M , Γ) +check (M , Γ) (expire r) = lookup r Γ >>= λ _ → just (M , remove r Γ) + +chk : CState → Prog → Maybe CState +chk s [] = just s +chk s (c ∷ p) = check s c >>= λ s′ → chk s′ p + +init : Store +init = [] , [] + +initC : CState +initC = [] , [] + +------------------------------------------------------------------------ +-- The cut D (ADR-0028 §4.5): R1, R2, R3 as predicates + +R1F : FBody → Set +R1F (ret i) = WF ref +R1F (retif c b₁ b₂) = R1F b₁ × R1F b₂ +R1F (retwrap i) = WF (tup ref) + +R1R : RExp → Set +R1R (borrow k x) = WF ref +R1R (copy k r) = WF ref +R1R (reborrow k r) = WF ref +R1R (proj t) = WF (tup ref) +R1R (call b as) = R1F b +R1R (choose c e₁ e₂) = R1R e₁ × R1R e₂ + +-- R3: `&*r` is not a primitive; it is elaborated to `copy r` (`elabR`). +R3R : RExp → Set +R3R (borrow k x) = ⊤ +R3R (copy k r) = ⊤ +R3R (reborrow k r) = ⊥ +R3R (proj t) = ⊤ +R3R (call b as) = ⊤ +R3R (choose c e₁ e₂) = R3R e₁ × R3R e₂ + +R1S : Stmt → Set +R1S (letref r e) = WF ref × R1R e +R1S (lettup t e) = WF (tup ref) × R1R e +R1S (assign r e) = R1R e +R1S (assignif c r e) = R1R e +R1S (consume x) = ⊤ +R1S (deref r) = ⊤ +R1S (expire r) = ⊤ + +-- R2: a reference local is not assigned to after its `let`. +R2S : Stmt → Set +R2S (letref r e) = ⊤ +R2S (lettup t e) = ⊤ +R2S (assign r e) = ⊥ +R2S (assignif c r e) = ⊥ +R2S (consume x) = ⊤ +R2S (deref r) = ⊤ +R2S (expire r) = ⊤ + +R3S : Stmt → Set +R3S (letref r e) = R3R e +R3S (lettup t e) = R3R e +R3S (assign r e) = R3R e +R3S (assignif c r e) = R3R e +R3S (consume x) = ⊤ +R3S (deref r) = ⊤ +R3S (expire r) = ⊤ + +DS : Stmt → Set +DS s = R1S s × R2S s × R3S s + +D : Prog → Set +D [] = ⊤ +D (s ∷ p) = DS s × D p + +D-prefix : (p q : Prog) → D (p ++ q) → D p +D-prefix [] q d = tt +D-prefix (s ∷ p) q (ds , d) = ds , D-prefix p q d + +-- R3's elaboration. +elabR : RExp → RExp +elabR (borrow k x) = borrow k x +elabR (copy k r) = copy k r +elabR (reborrow k r) = copy k r +elabR (proj t) = proj t +elabR (call b as) = call b as +elabR (choose c e₁ e₂) = choose c (elabR e₁) (elabR e₂) + +elabS : Stmt → Stmt +elabS (letref r e) = letref r (elabR e) +elabS (lettup t e) = lettup t (elabR e) +elabS (assign r e) = assign r (elabR e) +elabS (assignif c r e) = assignif c r (elabR e) +elabS (consume x) = consume x +elabS (deref r) = deref r +elabS (expire r) = expire r + +elab : Prog → Prog +elab [] = [] +elab (s ∷ p) = elabS s ∷ elab p + +------------------------------------------------------------------------ +-- Option G as a type + +-- The loan held by r after running p, as a function of the execution. +valueAt : Prog → Var → Oracle → Maybe Loan +valueAt p r ρ = run ρ init p >>= λ s → lookup r (snd s) + +-- The provenance fibre of r at the point after p, over the loan ℓ: the +-- executions that leave ℓ in r. It is an `Echo` of the run map. +Fibre : Prog → Var → Loan → Set +Fibre p r ℓ = Echo (valueAt p r) (just ℓ) + +infix 4 _∈_ +_∈_ : Loan → List Loan → Set +ℓ ∈ [] = ⊥ +ℓ ∈ (m ∷ L) = (ℓ ≡ m) ⊎ (ℓ ∈ L) + +-- G at the point after p: every loan whose fibre is inhabited is in the +-- set the checker tracks for r there. +G : Prog → Set +G p = {M : List Var} {Γ : TEnv} → chk initC p ≡ just (M , Γ) → + (r : Var) (ℓ : Loan) → Fibre p r ℓ → + Σ (List Loan) (λ L → (lookup r Γ ≡ just L) × (ℓ ∈ L)) + +------------------------------------------------------------------------ +-- The invariant: stores agree, each held loan is tracked, and no tracked +-- loan is on a moved place. + +Live : List Var → List Loan → Set +Live M [] = ⊤ +Live M (ℓ ∷ L) = (mem (owner ℓ) M ≡ false) × Live M L + +Inv : List Var → Env Loan → TEnv → Set +Inv M [] [] = ⊤ +Inv M [] (_ ∷ _) = ⊥ +Inv M (_ ∷ _) [] = ⊥ +Inv M ((r , v) ∷ σ) ((r′ , L) ∷ Γ) = (r ≡ r′) × (v ∈ L) × Live M L × Inv M σ Γ + +-- "m evaluates to a loan that is in L, and L is live." +Good : List Var → Maybe Loan → List Loan → Set +Good M m L = Σ Loan (λ v → (m ≡ just v) × (v ∈ L) × Live M L) + +∈-++l : {v : Loan} (L₁ L₂ : List Loan) → v ∈ L₁ → v ∈ (L₁ ++ L₂) +∈-++l [] L₂ () +∈-++l (m ∷ L₁) L₂ (inl e) = inl e +∈-++l (m ∷ L₁) L₂ (inr i) = inr (∈-++l L₁ L₂ i) + +∈-++r : {v : Loan} (L₁ L₂ : List Loan) → v ∈ L₂ → v ∈ (L₁ ++ L₂) +∈-++r [] L₂ i = i +∈-++r (m ∷ L₁) L₂ i = inr (∈-++r L₁ L₂ i) + +Live-++ : (M : List Var) (L₁ L₂ : List Loan) → Live M L₁ → Live M L₂ → Live M (L₁ ++ L₂) +Live-++ M [] L₂ l₁ l₂ = l₂ +Live-++ M (m ∷ L₁) L₂ (a , l₁) l₂ = a , Live-++ M L₁ L₂ l₁ l₂ + +Live-∈ : (M : List Var) (L : List Loan) {v : Loan} → Live M L → v ∈ L → + mem (owner v) M ≡ false +Live-∈ M [] l () +Live-∈ M (m ∷ L) (a , l) (inl refl) = a +Live-∈ M (m ∷ L) (a , l) (inr i) = Live-∈ M L l i + +Good-bind : {A : Set} {M : List Var} {m : Maybe A} {f : A → Maybe Loan} {a : A} + {L : List Loan} → m ≡ just a → Good M (f a) L → Good M (m >>= f) L +Good-bind refl g = g + +Good-join : (M : List Var) (b : Bool) {m₁ m₂ : Maybe Loan} (L₁ L₂ : List Loan) → + Good M m₁ L₁ → Good M m₂ L₂ → Good M (if b then m₁ else m₂) (L₁ ++ L₂) +Good-join M true L₁ L₂ (v , e , i , l₁) (_ , _ , _ , l₂) = + v , e , ∈-++l L₁ L₂ i , Live-++ M L₁ L₂ l₁ l₂ +Good-join M false L₁ L₂ (_ , _ , _ , l₁) (v , e , i , l₂) = + v , e , ∈-++r L₁ L₂ i , Live-++ M L₁ L₂ l₁ l₂ + +Good-to : {M : List Var} {m : Maybe Loan} {L L′ : List Loan} → + just L ≡ just L′ → Good M m L → Good M m L′ +Good-to {M} {m} e g = subst (Good M m) (just-inj e) g + +-- A fresh borrow of an unmoved place. +borrow-good : (M : List Var) (x : Var) (k : Kind) {L : List Loan} → + not (mem x M) ≡ true → just (loan x k ∷ []) ≡ just L → + Good M (when (not (mem x M)) (just (loan x k))) L +borrow-good M x k nm e = + Good-to e (loan x k , when-intro nm , inl refl , (not-true (mem x M) nm , tt)) + +lookup-rel : (M : List Var) (σ : Env Loan) (Γ : TEnv) (r : Var) {L : List Loan} → + Inv M σ Γ → lookup r Γ ≡ just L → Good M (lookup r σ) L +lookup-rel M [] [] r inv () +lookup-rel M [] (_ ∷ _) r () +lookup-rel M (_ ∷ _) [] r () +lookup-rel M ((s , v) ∷ σ) ((.s , L′) ∷ Γ) r (refl , i , l , inv) e with r == s +... | true = Good-to e (v , refl , i , l) +... | false = lookup-rel M σ Γ r inv e + +lookup-rel′ : (M : List Var) (σ : Env Loan) (Γ : TEnv) (r : Var) {v : Loan} → + Inv M σ Γ → lookup r σ ≡ just v → + Σ (List Loan) (λ L → (lookup r Γ ≡ just L) × (v ∈ L)) +lookup-rel′ M [] [] r inv () +lookup-rel′ M [] (_ ∷ _) r () +lookup-rel′ M (_ ∷ _) [] r () +lookup-rel′ M ((s , w) ∷ σ) ((.s , L′) ∷ Γ) r {v} (refl , i , l , inv) e with r == s +... | true = L′ , refl , subst (λ u → u ∈ L′) (just-inj e) i +... | false = lookup-rel′ M σ Γ r inv e + +Inv-remove : (M : List Var) (σ : Env Loan) (Γ : TEnv) (r : Var) → + Inv M σ Γ → Inv M (remove r σ) (remove r Γ) +Inv-remove M [] [] r inv = tt +Inv-remove M [] (_ ∷ _) r () +Inv-remove M (_ ∷ _) [] r () +Inv-remove M ((s , v) ∷ σ) ((.s , L) ∷ Γ) r (refl , i , l , inv) with r == s +... | true = inv +... | false = refl , i , l , Inv-remove M σ Γ r inv + +-- Moving x keeps the invariant when no tracked loan is on x. This is the +-- one place the proof reads the counts. +hit-miss : (x : Var) (ℓ : Loan) → isZero (hit shr x ℓ) ≡ true → + isZero (hit mut x ℓ) ≡ true → (x == owner ℓ) ≡ false +hit-miss x (loan y shr) zs zm = b2n-zero (x == y) zs +hit-miss x (loan y mut) zs zm = b2n-zero (x == y) zm + +mem-cons : (x y : Var) (M : List Var) → (x == y) ≡ false → mem y M ≡ false → + mem y (x ∷ M) ≡ false +mem-cons x y M e a with x == y +mem-cons x y M () a | true +mem-cons x y M e a | false = a + +Live-consume : (M : List Var) (x : Var) (L : List Loan) → Live M L → + isZero (cntL shr x L) ≡ true → isZero (cntL mut x L) ≡ true → + Live (x ∷ M) L +Live-consume M x [] l zs zm = tt +Live-consume M x (ℓ ∷ L) (a , l) zs zm = + mem-cons x (owner ℓ) M + (hit-miss x ℓ (fst (zero-+ (hit shr x ℓ) _ zs)) (fst (zero-+ (hit mut x ℓ) _ zm))) a , + Live-consume M x L l (snd (zero-+ (hit shr x ℓ) _ zs)) (snd (zero-+ (hit mut x ℓ) _ zm)) + +Inv-consume : (M : List Var) (x : Var) (σ : Env Loan) (Γ : TEnv) → Inv M σ Γ → + isZero (cnt shr x Γ) ≡ true → isZero (cnt mut x Γ) ≡ true → + Inv (x ∷ M) σ Γ +Inv-consume M x [] [] inv zs zm = tt +Inv-consume M x [] (_ ∷ _) () +Inv-consume M x (_ ∷ _) [] () +Inv-consume M x ((r , v) ∷ σ) ((r′ , L) ∷ Γ) (e , i , l , inv) zs zm = + e , i , + Live-consume M x L l (fst (zero-+ (cntL shr x L) _ zs)) (fst (zero-+ (cntL mut x L) _ zm)) , + Inv-consume M x σ Γ inv (snd (zero-+ (cntL shr x L) _ zs)) (snd (zero-+ (cntL mut x L) _ zm)) + +------------------------------------------------------------------------ +-- Calls: argument sets and the return summary + +ArgsRel : List Var → List Loan → List (List Loan) → Set +ArgsRel M [] [] = ⊤ +ArgsRel M [] (_ ∷ _) = ⊥ +ArgsRel M (_ ∷ _) [] = ⊥ +ArgsRel M (v ∷ vs) (L ∷ Ls) = (v ∈ L) × Live M L × ArgsRel M vs Ls + +arg-sim : (M : List Var) (σ : Env Loan) (Γ : TEnv) (a : Arg) {L : List Loan} → + Inv M σ Γ → trackArg M Γ a ≡ just L → Good M (evalArg M σ a) L +arg-sim M σ Γ (own x) inv e = + borrow-good M x shr + (∧-l _ _ (fst (when-inv (not (mem x M) ∧ noMut x Γ) e))) + (snd (when-inv (not (mem x M) ∧ noMut x Γ) e)) +arg-sim M σ Γ (byref r) inv e with bind-inv (lookup r Γ) _ e +... | L′ , t , e′ = + Good-to (snd (when-inv (allKind shr L′) e′)) (lookup-rel M σ Γ r inv t) + +args-sim : (M : List Var) (σ : Env Loan) (Γ : TEnv) (as : List Arg) + {Ls : List (List Loan)} → Inv M σ Γ → trackArgs M Γ as ≡ just Ls → + Σ (List Loan) (λ vs → (evalArgs M σ as ≡ just vs) × ArgsRel M vs Ls) +args-sim M σ Γ [] inv e = [] , refl , subst (ArgsRel M []) (just-inj e) tt +args-sim M σ Γ (a ∷ as) inv e + with bind-inv (trackArg M Γ a) _ e +... | L , ta , e₁ with bind-inv (trackArgs M Γ as) _ e₁ +... | Ls′ , tas , e₂ with arg-sim M σ Γ a inv ta | args-sim M σ Γ as inv tas +... | v , ev , i , l | vs , evs , rel = + v ∷ vs , bind-intro ev (bind-intro evs refl) , + subst (ArgsRel M (v ∷ vs)) (just-inj e₂) (i , l , rel) + +nth-rel : (M : List Var) (i : ℕ) (vs : List Loan) (Ls : List (List Loan)) + {L : List Loan} → ArgsRel M vs Ls → nth i Ls ≡ just L → Good M (nth i vs) L +nth-rel M i [] [] rel () +nth-rel M i [] (_ ∷ _) () +nth-rel M i (_ ∷ _) [] () +nth-rel M zero (v ∷ vs) (L′ ∷ Ls) (m , l , rel) e = Good-to e (v , refl , m , l) +nth-rel M (suc i) (v ∷ vs) (L′ ∷ Ls) (m , l , rel) e = nth-rel M i vs Ls rel e + +F-sim : (ρ : Oracle) (M : List Var) (b : FBody) (vs : List Loan) + (Ls : List (List Loan)) {L : List Loan} → R1F b → ArgsRel M vs Ls → + summF b Ls ≡ just L → Good M (runF ρ b vs) L +F-sim ρ M (ret i) vs Ls w rel e = nth-rel M i vs Ls rel e +F-sim ρ M (retwrap i) vs Ls () rel e +F-sim ρ M (retif c b₁ b₂) vs Ls (w₁ , w₂) rel e + with bind-inv (summF b₁ Ls) _ e +... | L₁ , s₁ , e₁ with bind-inv (summF b₂ Ls) _ e₁ +... | L₂ , s₂ , e₂ = + Good-to e₂ (Good-join M (ρ c) L₁ L₂ (F-sim ρ M b₁ vs Ls w₁ rel s₁) + (F-sim ρ M b₂ vs Ls w₂ rel s₂)) + +------------------------------------------------------------------------ +-- Simulation: on the D fragment, what the checker accepts does not get +-- stuck, and the invariant is kept. + +evalR-sim : (ρ : Oracle) (M : List Var) (σ : Env Loan) (Γ : TEnv) (e : RExp) + {L : List Loan} → Inv M σ Γ → R1R e → R3R e → + trackR M Γ e ≡ just L → Good M (evalR ρ M σ e) L +evalR-sim ρ M σ Γ (borrow k x) inv w r3 t = + borrow-good M x k + (∧-l _ _ (fst (when-inv (not (mem x M) ∧ okBorrow k x Γ) t))) + (snd (when-inv (not (mem x M) ∧ okBorrow k x Γ) t)) +evalR-sim ρ M σ Γ (copy k r) inv w r3 t with bind-inv (lookup r Γ) _ t +... | L′ , t′ , u = + Good-to (snd (when-inv (allKind k L′) u)) (lookup-rel M σ Γ r inv t′) +evalR-sim ρ M σ Γ (reborrow k r) inv w () t +evalR-sim ρ M σ Γ (proj t′) inv () r3 t +evalR-sim ρ M σ Γ (call b as) inv w r3 t + with bind-inv (trackArgs M Γ as) _ t +... | Ls , ta , sf with args-sim M σ Γ as inv ta +... | vs , ea , rel = Good-bind ea (F-sim ρ M b vs Ls w rel sf) +evalR-sim ρ M σ Γ (choose c e₁ e₂) inv (w₁ , w₂) (p₁ , p₂) t + with bind-inv (trackR M Γ e₁) _ t +... | L₁ , t₁ , u with bind-inv (trackR M Γ e₂) _ u +... | L₂ , t₂ , u′ = + Good-to u′ (Good-join M (ρ c) L₁ L₂ (evalR-sim ρ M σ Γ e₁ inv w₁ p₁ t₁) + (evalR-sim ρ M σ Γ e₂ inv w₂ p₂ t₂)) + +state-inv : {A B : Set} {a a′ : A} {b b′ : B} → + just (a , b) ≡ just (a′ , b′) → (a ≡ a′) × (b ≡ b′) +state-inv e = cong fst (just-inj e) , cong snd (just-inj e) + +Sim : Oracle → List Var → Env Loan → Stmt → List Var → TEnv → Set +Sim ρ M σ s M′ Γ′ = + Σ (Env Loan) (λ σ′ → (step ρ (M , σ) s ≡ just (M′ , σ′)) × Inv M′ σ′ Γ′) + +step-sim : (ρ : Oracle) (M : List Var) (σ : Env Loan) (Γ : TEnv) (s : Stmt) + {M′ : List Var} {Γ′ : TEnv} → Inv M σ Γ → DS s → + check (M , Γ) s ≡ just (M′ , Γ′) → Sim ρ M σ s M′ Γ′ +step-sim ρ M σ Γ (lettup t e) inv ((() , _) , _) c +step-sim ρ M σ Γ (assign r e) inv (_ , () , _) c +step-sim ρ M σ Γ (assignif b r e) inv (_ , () , _) c +step-sim ρ M σ Γ (letref r e) inv ((_ , w) , _ , r3) c + with bind-inv (trackR M Γ e) _ c +... | L , t , c′ with evalR-sim ρ M σ Γ e inv w r3 t | state-inv c′ +... | v , ev , i , l | refl , refl = (r , v) ∷ σ , bind-intro ev refl , (refl , i , l , inv) +step-sim ρ M σ Γ (consume x) inv d c + with when-inv (not (mem x M) ∧ free x Γ) c +... | g , c′ with state-inv c′ +... | refl , refl = + σ , when-intro (∧-l _ _ g) , + Inv-consume M x σ Γ inv (∧-l _ _ (∧-r (not (mem x M)) _ g)) + (∧-r _ _ (∧-r (not (mem x M)) _ g)) +step-sim ρ M σ Γ (deref r) inv d c + with bind-inv (lookup r Γ) _ c +... | L , t , c′ with lookup-rel M σ Γ r inv t | state-inv c′ +... | v , ev , i , l | refl , refl = + σ , bind-intro ev (when-intro (cong not (Live-∈ M L l i))) , inv +step-sim ρ M σ Γ (expire r) inv d c + with bind-inv (lookup r Γ) _ c +... | L , t , c′ with lookup-rel M σ Γ r inv t | state-inv c′ +... | v , ev , i , l | refl , refl = + remove r σ , bind-intro ev refl , Inv-remove M σ Γ r inv + +run-sim : (ρ : Oracle) (p : Prog) (M : List Var) (σ : Env Loan) (Γ : TEnv) + {M′ : List Var} {Γ′ : TEnv} → Inv M σ Γ → D p → + chk (M , Γ) p ≡ just (M′ , Γ′) → + Σ (Env Loan) (λ σ′ → (run ρ (M , σ) p ≡ just (M′ , σ′)) × Inv M′ σ′ Γ′) +run-sim ρ [] M σ Γ inv d c with state-inv c +... | refl , refl = σ , refl , inv +run-sim ρ (s ∷ p) M σ Γ inv (ds , d) c + with bind-inv (check (M , Γ) s) _ c +... | (M₁ , Γ₁) , cs , c′ with step-sim ρ M σ Γ s inv ds cs +... | σ₁ , es , inv₁ with run-sim ρ p M₁ σ₁ Γ₁ inv₁ d c′ +... | σ′ , er , inv′ = σ′ , bind-intro es er , inv′ + +------------------------------------------------------------------------ +-- (a) The theorems + +-- SAFETY. A D program the checker accepts runs to completion under every +-- execution: no use after move. +safety : (p : Prog) → D p → {M : List Var} {Γ : TEnv} → + chk initC p ≡ just (M , Γ) → (ρ : Oracle) → + Σ (Env Loan) (λ σ → (run ρ init p ≡ just (M , σ)) × Inv M σ Γ) +safety p d c ρ = run-sim ρ p [] [] [] tt d c + +-- G. For D programs the tracked set contains the provenance fibre. +G-holds : (p : Prog) → D p → G p +G-holds p d {M} {Γ} c r ℓ (ρ , e) with safety p d c ρ +... | σ , er , inv = + lookup-rel′ M σ Γ r inv + (subst (λ m → (m >>= λ s → lookup r (snd s)) ≡ just ℓ) er e) + +-- G at every program point of a D program (D is prefix-closed). +G-everywhere : (p q : Prog) → D (p ++ q) → G p +G-everywhere p q d = G-holds p (D-prefix p q d) + +-- REJECTION. A D program that gets stuck under some execution is rejected. +maybe-case : {A : Set} (m : Maybe A) → (m ≡ nothing) ⊎ Σ A (λ a → m ≡ just a) +maybe-case nothing = inl refl +maybe-case (just a) = inr (a , refl) + +stuck-rejected : (p : Prog) → D p → (ρ : Oracle) → + run ρ init p ≡ nothing → chk initC p ≡ nothing +stuck-rejected p d ρ stuck with maybe-case (chk initC p) +... | inl e = e +... | inr ((M , Γ) , e) with safety p d e ρ +... | σ , er , inv with nothing≢just (trans (sym stuck) er) +... | () + +------------------------------------------------------------------------ +-- Examples. Owned locals a = 0, b = 1; reference locals r = 10, r₂ = 11, +-- t = 12. `pick` returns `&x` of its `ref` parameter. + +private + a b r r₂ t : Var + a = 0 + b = 1 + r = 10 + r₂ = 11 + t = 12 + + pick : FBody + pick = ret 0 + + yes : Oracle + yes _ = true + + 1≢0 : 1 ≡ 0 → ⊥ + 1≢0 () + + ∈[] : {ℓ : Loan} {L : List Loan} → [] ≡ L → ℓ ∈ L → ⊥ + ∈[] {ℓ} e i = subst (λ L → ℓ ∈ L) (sym e) i + +-- K-1, the #554 `pick` example: let r = pick(a); consume(a); *r +K1 : Prog +K1 = letref r (call pick (own a ∷ [])) ∷ consume a ∷ deref r ∷ [] + +K1-D : D K1 +K1-D = ((tt , tt) , tt , tt) , (tt , tt , tt) , (tt , tt , tt) , tt + +K1-rejected : chk initC K1 ≡ nothing +K1-rejected = refl + +K1-stuck : (ρ : Oracle) → run ρ init K1 ≡ nothing +K1-stuck ρ = refl + +-- The same verdict, obtained from the theorem instead of by running the checker. +K1-rejected-by-theorem : chk initC K1 ≡ nothing +K1-rejected-by-theorem = stuck-rejected K1 K1-D yes (K1-stuck yes) + +-- K-2: let r = &a; consume(a); *r +K2 : Prog +K2 = letref r (borrow shr a) ∷ consume a ∷ deref r ∷ [] + +K2-rejected : chk initC K2 ≡ nothing +K2-rejected = refl + +-- A D program that IS accepted (so the theorems are not vacuous), S-10 with +-- expiry: let r = first_or(a, b, c); *r; (r dead); consume(a) +S10 : Prog +S10 = letref r (call (retif 0 (ret 0) (ret 1)) (own a ∷ own b ∷ [])) ∷ + deref r ∷ expire r ∷ consume a ∷ [] + +S10-D : D S10 +S10-D = ((tt , (tt , tt)) , tt , tt) , (tt , tt , tt) , (tt , tt , tt) , (tt , tt , tt) , tt + +S10-accepted : chk initC S10 ≡ just (a ∷ [] , []) +S10-accepted = refl + +-- At the point after the `let`, r is tracked with both loans; each execution +-- realises one of them. +S10-tracked : chk initC (letref r (call (retif 0 (ret 0) (ret 1)) (own a ∷ own b ∷ [])) ∷ []) + ≡ just ([] , (r , loan a shr ∷ loan b shr ∷ []) ∷ []) +S10-tracked = refl + +------------------------------------------------------------------------ +-- (b) Four #847 programs. For each: it is NOT in D; the first-class +-- checker accepts it; G fails at a point P (a fibre element escapes the +-- tracked set); and it gets stuck (use after move). + +-- U-A2 (class A): let r = &a; let t = (r, 0); consume(a); *(t.0) +UA2-P : Prog -- the point P: after `let t` +UA2-P = letref r (borrow shr a) ∷ lettup t (copy shr r) ∷ expire r ∷ [] + +UA2 : Prog +UA2 = UA2-P ++ (consume a ∷ deref t ∷ []) + +UA2-not-D : ¬ D UA2 -- R1: `(ref Int, Int)` is not well formed +UA2-not-D (_ , ((() , _) , _) , _) + +UA2-accepted : chk initC UA2 ≡ just (a ∷ [] , (t , []) ∷ []) +UA2-accepted = refl + +UA2-stuck : (ρ : Oracle) → run ρ init UA2 ≡ nothing +UA2-stuck ρ = refl + +UA2-not-G : ¬ G UA2-P +UA2-not-G g with g refl t (loan a shr) (yes , refl) +... | L , e , i = ∈[] (just-inj e) i + +-- U-E3 (class E): let r = &x; let r₂ = &*r; consume(x); *r₂ +UE3-P : Prog +UE3-P = letref r (borrow shr a) ∷ letref r₂ (reborrow shr r) ∷ expire r ∷ [] + +UE3 : Prog +UE3 = UE3-P ++ (consume a ∷ deref r₂ ∷ []) + +UE3-not-D : ¬ D UE3 -- R3: `&*r` is not a primitive +UE3-not-D (_ , (_ , _ , ()) , _) + +UE3-accepted : chk initC UE3 ≡ just (a ∷ [] , (r₂ , []) ∷ []) +UE3-accepted = refl + +UE3-stuck : (ρ : Oracle) → run ρ init UE3 ≡ nothing +UE3-stuck ρ = refl + +UE3-not-G : ¬ G UE3-P +UE3-not-G g with g refl r₂ (loan a shr) (yes , refl) +... | L , e , i = ∈[] (just-inj e) i + +-- Under R3 the reborrow is a copy; the elaborated program is in D and is +-- rejected by the ref-to-ref rule. +UE3-elab-D : D (elab UE3) +UE3-elab-D = ((tt , tt) , tt , tt) , ((tt , tt) , tt , tt) , (tt , tt , tt) , + (tt , tt , tt) , (tt , tt , tt) , tt + +UE3-elab-rejected : chk initC (elab UE3) ≡ nothing +UE3-elab-rejected = refl + +-- U-D1 (class D): fn wrap(ref x) -> ref Int { return (&x, 0).0; } +-- let r = wrap(a); consume(a); *r +UD1-P : Prog +UD1-P = letref r (call (retwrap 0) (own a ∷ [])) ∷ [] + +UD1 : Prog +UD1 = UD1-P ++ (consume a ∷ deref r ∷ []) + +UD1-not-D : ¬ D UD1 -- R1, inside the callee +UD1-not-D (((_ , ()) , _) , _) + +UD1-accepted : chk initC UD1 ≡ just (a ∷ [] , (r , []) ∷ []) +UD1-accepted = refl + +UD1-stuck : (ρ : Oracle) → run ρ init UD1 ≡ nothing +UD1-stuck ρ = refl + +UD1-not-G : ¬ G UD1-P +UD1-not-G g with g refl r (loan a shr) (yes , refl) +... | L , e , i = ∈[] (just-inj e) i + +-- U-B2 (class B): let mut r = pick(a); if c { r = pick(b); } consume(b); *r +UB2-P : Prog +UB2-P = letref r (call pick (own a ∷ [])) ∷ assignif 0 r (call pick (own b ∷ [])) ∷ [] + +UB2 : Prog +UB2 = UB2-P ++ (consume b ∷ deref r ∷ []) + +UB2-not-D : ¬ D UB2 -- R2: re-pointing +UB2-not-D (_ , (_ , () , _) , _) + +UB2-accepted : chk initC UB2 ≡ just (b ∷ [] , (r , loan a shr ∷ []) ∷ []) +UB2-accepted = refl + +UB2-stuck : run yes init UB2 ≡ nothing -- on the execution that takes the branch +UB2-stuck = refl + +UB2-not-G : ¬ G UB2-P +UB2-not-G g with g refl r (loan b shr) (yes , refl) +... | L , e , i with subst (λ L′ → loan b shr ∈ L′) (sym (just-inj e)) i +... | inl q = 1≢0 (cong owner q) +... | inr () + +------------------------------------------------------------------------ +-- (c) Aggregates. Dynamically `let t = (e, 0)` binds t to the loan of e, +-- exactly as `let r = e` does. So a checker that gives the aggregate the +-- set of its reference component is covered by the `letref` case above. + +lettup-is-letref : (ρ : Oracle) (s : Store) (t′ : Var) (e : RExp) → + step ρ s (lettup t′ e) ≡ step ρ s (letref t′ e) +lettup-is-letref ρ (M , σ) t′ e = refl + +------------------------------------------------------------------------ +-- (d) Three programs that satisfy D as ADR-0028 words it and that the +-- PRODUCTION checker accepts (measured 2026-12-01, build 0c9677d; see the +-- record). The model's checker rejects each, and each is in D, so by +-- `stuck-rejected` it had to. They are holes in `lib/borrow.ml` inside the +-- cut, not counterexamples to G. + +-- D-01: fn pass(r: ref Int) -> ref Int { return r; } +-- let r = &a; let s = pass(r); consume(a); *s +D01 : Prog +D01 = letref r (borrow shr a) ∷ letref r₂ (call (ret 0) (byref r ∷ [])) ∷ + expire r ∷ consume a ∷ deref r₂ ∷ [] + +D01-D : D D01 +D01-D = ((tt , tt) , tt , tt) , ((tt , tt) , tt , tt) , (tt , tt , tt) , + (tt , tt , tt) , (tt , tt , tt) , tt + +D01-stuck : (ρ : Oracle) → run ρ init D01 ≡ nothing +D01-stuck ρ = refl + +D01-rejected : chk initC D01 ≡ nothing +D01-rejected = stuck-rejected D01 D01-D yes (D01-stuck yes) + +-- D-06: let r = &a; let s = pick(*r); consume(a); *s +-- `*r` in a `ref`-mode argument position is read as passing r (`byref`), the +-- reading R3 gives `&*r`. With that reading it is the same program as D-01. +D06 : Prog +D06 = letref r (borrow shr a) ∷ letref r₂ (call pick (byref r ∷ [])) ∷ + expire r ∷ consume a ∷ deref r₂ ∷ [] + +D06-rejected : chk initC D06 ≡ nothing +D06-rejected = refl + +-- D-19: fn f(ref x: Int, c: Bool) -> ref Int { let r = if c { &x } else { &x }; return r; } +-- let r = f(a, c); consume(a); *r +D19 : Prog +D19 = letref r (call (retif 0 (ret 0) (ret 0)) (own a ∷ [])) ∷ consume a ∷ deref r ∷ [] + +D19-D : D D19 +D19-D = ((tt , (tt , tt)) , tt , tt) , (tt , tt , tt) , (tt , tt , tt) , tt + +D19-stuck : (ρ : Oracle) → run ρ init D19 ≡ nothing +D19-stuck ρ with ρ 0 +... | true = refl +... | false = refl + +D19-rejected : chk initC D19 ≡ nothing +D19-rejected = refl + +------------------------------------------------------------------------ +-- (e) D+R4, and the three obligations stated separately +-- +-- After #847's U-G1 (`let r = &mut x; let r2 = r;` leaves two usable +-- exclusive references) the ADR's surviving cut is D plus +-- R4: an exclusive reference is not copyable. +-- U-G1 is not a provenance failure: G holds for it (`UG1-G`). So the +-- obligations are separate: +-- (i) provenance inclusion — `G-holds` above, needs D only; +-- (ii) exclusivity — `exclusivity` below, needs D and R4; +-- (iii) rejection — `stuck-rejected` above and +-- `aliasing-rejected` below. + +R4R : RExp → Set +R4R (borrow k x) = ⊤ +R4R (copy shr r) = ⊤ +R4R (copy mut r) = ⊥ +R4R (reborrow k r) = ⊤ +R4R (proj t) = ⊤ +R4R (call b as) = ⊤ +R4R (choose c e₁ e₂) = R4R e₁ × R4R e₂ + +R4S : Stmt → Set +R4S (letref r e) = R4R e +R4S (lettup t e) = R4R e +R4S (assign r e) = R4R e +R4S (assignif c r e) = R4R e +R4S (consume x) = ⊤ +R4S (deref r) = ⊤ +R4S (expire r) = ⊤ + +R4 : Prog → Set +R4 [] = ⊤ +R4 (s ∷ p) = R4S s × R4 p + +-- (ii) as a property of the store of usable references. A reference is +-- compatible with the ones bound before it when: if it is exclusive, none of +-- them is on its place; if it is shared, none of them is exclusive on its +-- place. `Excl` asks this of every reference, so any two usable references +-- to one place are both shared. +FreeH : Var → Env Loan → Set +FreeH x [] = ⊤ +FreeH x ((r , v) ∷ σ) = ((x == owner v) ≡ false) × FreeH x σ + +NoMutH : Var → Env Loan → Set +NoMutH x [] = ⊤ +NoMutH x ((r , v) ∷ σ) = (isZero (hit mut x v) ≡ true) × NoMutH x σ + +Compat : Loan → Env Loan → Set +Compat (loan x shr) σ = NoMutH x σ +Compat (loan x mut) σ = FreeH x σ + +Excl : Env Loan → Set +Excl [] = ⊤ +Excl ((r , v) ∷ σ) = Compat v σ × Excl σ + +⊥-elim : {A : Set} → ⊥ → A +⊥-elim () + +==-sym : (m n : ℕ) → (m == n) ≡ (n == m) +==-sym zero zero = refl +==-sym zero (suc n) = refl +==-sym (suc m) zero = refl +==-sym (suc m) (suc n) = ==-sym m n + +∈-miss : (x : Var) (L : List Loan) {v : Loan} → v ∈ L → + isZero (cntL shr x L) ≡ true → isZero (cntL mut x L) ≡ true → + (x == owner v) ≡ false +∈-miss x [] () +∈-miss x (m ∷ L) (inl refl) zs zm = + hit-miss x m (fst (zero-+ (hit shr x m) _ zs)) (fst (zero-+ (hit mut x m) _ zm)) +∈-miss x (m ∷ L) (inr i) zs zm = + ∈-miss x L i (snd (zero-+ (hit shr x m) _ zs)) (snd (zero-+ (hit mut x m) _ zm)) + +∈-nomut : (x : Var) (L : List Loan) {v : Loan} → v ∈ L → + isZero (cntL mut x L) ≡ true → isZero (hit mut x v) ≡ true +∈-nomut x [] () +∈-nomut x (m ∷ L) (inl refl) zm = fst (zero-+ (hit mut x m) _ zm) +∈-nomut x (m ∷ L) (inr i) zm = ∈-nomut x L i (snd (zero-+ (hit mut x m) _ zm)) + +-- Zero counts in the checker's state mean no usable reference is there. +free-held : (M : List Var) (x : Var) (σ : Env Loan) (Γ : TEnv) → Inv M σ Γ → + isZero (cnt shr x Γ) ≡ true → isZero (cnt mut x Γ) ≡ true → FreeH x σ +free-held M x [] [] inv zs zm = tt +free-held M x [] (_ ∷ _) () +free-held M x (_ ∷ _) [] () +free-held M x ((r , v) ∷ σ) ((r′ , L) ∷ Γ) (e , i , l , inv) zs zm = + ∈-miss x L i (fst (zero-+ (cntL shr x L) _ zs)) (fst (zero-+ (cntL mut x L) _ zm)) , + free-held M x σ Γ inv (snd (zero-+ (cntL shr x L) _ zs)) (snd (zero-+ (cntL mut x L) _ zm)) + +nomut-held : (M : List Var) (x : Var) (σ : Env Loan) (Γ : TEnv) → Inv M σ Γ → + isZero (cnt mut x Γ) ≡ true → NoMutH x σ +nomut-held M x [] [] inv zm = tt +nomut-held M x [] (_ ∷ _) () +nomut-held M x (_ ∷ _) [] () +nomut-held M x ((r , v) ∷ σ) ((r′ , L) ∷ Γ) (e , i , l , inv) zm = + ∈-nomut x L i (fst (zero-+ (cntL mut x L) _ zm)) , + nomut-held M x σ Γ inv (snd (zero-+ (cntL mut x L) _ zm)) + +shr-only : (L : List Loan) {y : Var} → allKind shr L ≡ true → loan y mut ∈ L → ⊥ +shr-only [] a () +shr-only (m ∷ L) a (inr i) = shr-only L (∧-r (isKind shr m) _ a) i +shr-only (m ∷ L) a (inl refl) = false≢true a + +FreeH-lookup : (z : Var) (σ : Env Loan) (r : Var) {u : Loan} → FreeH z σ → + lookup r σ ≡ just u → (z == owner u) ≡ false +FreeH-lookup z [] r f () +FreeH-lookup z ((s , w) ∷ σ) r {u} (f , fs) e with r == s +... | true = subst (λ u′ → (z == owner u′) ≡ false) (just-inj e) f +... | false = FreeH-lookup z σ r fs e + +-- A usable shared reference to y means no usable exclusive one to y. +held-here : (y : Var) (σ : Env Loan) (w : Loan) → w ≡ loan y shr → Compat w σ → + (isZero (hit mut y w) ≡ true) × NoMutH y σ +held-here y σ w refl c = refl , c + +newer-ok : (y : Var) (σ : Env Loan) (r : Var) (w : Loan) → Compat w σ → + lookup r σ ≡ just (loan y shr) → isZero (hit mut y w) ≡ true +newer-ok y σ r (loan z shr) c e = refl +newer-ok y σ r (loan z mut) c e = + cong (λ b → isZero (b2n b)) (trans (==-sym y z) (FreeH-lookup z σ r c e)) + +held-shr-nomut : (σ : Env Loan) (r : Var) (y : Var) → Excl σ → + lookup r σ ≡ just (loan y shr) → NoMutH y σ +held-shr-nomut [] r y ex () +held-shr-nomut ((s , w) ∷ σ) r y (c , ex) e with r == s +... | true = held-here y σ w (just-inj e) c +... | false = newer-ok y σ r w c e , held-shr-nomut σ r y ex e + +-- R4 at work: a copy of a reference whose set is all-shared is compatible. +ref-compat : (M : List Var) (σ : Env Loan) (Γ : TEnv) (r : Var) {L : List Loan} + (v : Loan) → Inv M σ Γ → Excl σ → lookup r Γ ≡ just L → + allKind shr L ≡ true → lookup r σ ≡ just v → Compat v σ +ref-compat M σ Γ r (loan y shr) inv ex t a e = held-shr-nomut σ r y ex e +ref-compat M σ Γ r {L} (loan y mut) inv ex t a e with lookup-rel′ M σ Γ r inv e +... | L′ , t′ , i = + ⊥-elim (shr-only L a (subst (λ K → loan y mut ∈ K) (just-inj (trans (sym t′) t)) i)) + +AllC : Env Loan → List Loan → Set +AllC σ [] = ⊤ +AllC σ (v ∷ vs) = Compat v σ × AllC σ vs + +arg-compat : (M : List Var) (σ : Env Loan) (Γ : TEnv) (a′ : Arg) {L : List Loan} + {v : Loan} → Inv M σ Γ → Excl σ → trackArg M Γ a′ ≡ just L → + evalArg M σ a′ ≡ just v → Compat v σ +arg-compat M σ Γ (own x) {v = v} inv ex t e = + subst (λ u → Compat u σ) (just-inj (snd (when-inv (not (mem x M)) e))) + (nomut-held M x σ Γ inv + (∧-r (not (mem x M)) _ (fst (when-inv (not (mem x M) ∧ noMut x Γ) t)))) +arg-compat M σ Γ (byref r) {v = v} inv ex t e with bind-inv (lookup r Γ) _ t +... | L′ , t′ , u = ref-compat M σ Γ r v inv ex t′ (fst (when-inv (allKind shr L′) u)) e + +args-compat : (M : List Var) (σ : Env Loan) (Γ : TEnv) (as : List Arg) + {Ls : List (List Loan)} {vs : List Loan} → Inv M σ Γ → Excl σ → + trackArgs M Γ as ≡ just Ls → evalArgs M σ as ≡ just vs → AllC σ vs +args-compat M σ Γ [] inv ex t e = subst (AllC σ) (just-inj e) tt +args-compat M σ Γ (a′ ∷ as) inv ex t e + with bind-inv (trackArg M Γ a′) _ t | bind-inv (evalArg M σ a′) _ e +... | L , ta , t₁ | v , ea , e₁ + with bind-inv (trackArgs M Γ as) _ t₁ | bind-inv (evalArgs M σ as) _ e₁ +... | Ls′ , tas , t₂ | vs′ , eas , e₂ = + subst (AllC σ) (just-inj e₂) + (arg-compat M σ Γ a′ inv ex ta ea , args-compat M σ Γ as inv ex tas eas) + +nth-compat : (σ : Env Loan) (i : ℕ) (vs : List Loan) {v : Loan} → AllC σ vs → + nth i vs ≡ just v → Compat v σ +nth-compat σ i [] ac () +nth-compat σ zero (u ∷ vs) (c , ac) e = subst (λ w → Compat w σ) (just-inj e) c +nth-compat σ (suc i) (u ∷ vs) (c , ac) e = nth-compat σ i vs ac e + +F-compat : (ρ : Oracle) (σ : Env Loan) (b′ : FBody) (vs : List Loan) {v : Loan} → + R1F b′ → AllC σ vs → runF ρ b′ vs ≡ just v → Compat v σ +F-compat ρ σ (ret i) vs w ac e = nth-compat σ i vs ac e +F-compat ρ σ (retwrap i) vs () ac e +F-compat ρ σ (retif c b₁ b₂) vs (w₁ , w₂) ac e with ρ c +... | true = F-compat ρ σ b₁ vs w₁ ac e +... | false = F-compat ρ σ b₂ vs w₂ ac e + +evalR-compat : (ρ : Oracle) (M : List Var) (σ : Env Loan) (Γ : TEnv) (e : RExp) + {L : List Loan} {v : Loan} → Inv M σ Γ → Excl σ → + R1R e → R3R e → R4R e → trackR M Γ e ≡ just L → + evalR ρ M σ e ≡ just v → Compat v σ +evalR-compat ρ M σ Γ (borrow shr x) inv ex w r3 r4 t e = + subst (λ u → Compat u σ) (just-inj (snd (when-inv (not (mem x M)) e))) + (nomut-held M x σ Γ inv + (∧-r (not (mem x M)) _ (fst (when-inv (not (mem x M) ∧ noMut x Γ) t)))) +evalR-compat ρ M σ Γ (borrow mut x) inv ex w r3 r4 t e = + subst (λ u → Compat u σ) (just-inj (snd (when-inv (not (mem x M)) e))) + (free-held M x σ Γ inv + (∧-l _ _ (∧-r (not (mem x M)) _ (fst (when-inv (not (mem x M) ∧ free x Γ) t)))) + (∧-r _ _ (∧-r (not (mem x M)) _ (fst (when-inv (not (mem x M) ∧ free x Γ) t))))) +evalR-compat ρ M σ Γ (copy shr r) {v = v} inv ex w r3 r4 t e + with bind-inv (lookup r Γ) _ t +... | L′ , t′ , u = ref-compat M σ Γ r v inv ex t′ (fst (when-inv (allKind shr L′) u)) e +evalR-compat ρ M σ Γ (copy mut r) inv ex w r3 () t e +evalR-compat ρ M σ Γ (reborrow k r) inv ex w () r4 t e +evalR-compat ρ M σ Γ (proj t′) inv ex () r3 r4 t e +evalR-compat ρ M σ Γ (call b′ as) inv ex w r3 r4 t e + with bind-inv (trackArgs M Γ as) _ t | bind-inv (evalArgs M σ as) _ e +... | Ls , ta , _ | vs , ea , rf = + F-compat ρ σ b′ vs w (args-compat M σ Γ as inv ex ta ea) rf +evalR-compat ρ M σ Γ (choose c e₁ e₂) inv ex (w₁ , w₂) (p₁ , p₂) (q₁ , q₂) t e + with bind-inv (trackR M Γ e₁) _ t +... | L₁ , t₁ , u with bind-inv (trackR M Γ e₂) _ u +... | L₂ , t₂ , _ with ρ c +... | true = evalR-compat ρ M σ Γ e₁ inv ex w₁ p₁ q₁ t₁ e +... | false = evalR-compat ρ M σ Γ e₂ inv ex w₂ p₂ q₂ t₂ e + +Compat-remove : (v : Loan) (σ : Env Loan) (r : Var) → Compat v σ → Compat v (remove r σ) +FreeH-remove : (x : Var) (σ : Env Loan) (r : Var) → FreeH x σ → FreeH x (remove r σ) +NoMutH-remove : (x : Var) (σ : Env Loan) (r : Var) → NoMutH x σ → NoMutH x (remove r σ) + +FreeH-remove x [] r f = tt +FreeH-remove x ((s , w) ∷ σ) r (f , fs) with r == s +... | true = fs +... | false = f , FreeH-remove x σ r fs + +NoMutH-remove x [] r f = tt +NoMutH-remove x ((s , w) ∷ σ) r (f , fs) with r == s +... | true = fs +... | false = f , NoMutH-remove x σ r fs + +Compat-remove (loan x shr) σ r c = NoMutH-remove x σ r c +Compat-remove (loan x mut) σ r c = FreeH-remove x σ r c + +Excl-remove : (σ : Env Loan) (r : Var) → Excl σ → Excl (remove r σ) +Excl-remove [] r ex = tt +Excl-remove ((s , w) ∷ σ) r (c , ex) with r == s +... | true = ex +... | false = Compat-remove w σ r c , Excl-remove σ r ex + +step-excl : (ρ : Oracle) (M : List Var) (σ : Env Loan) (Γ : TEnv) (s : Stmt) + {M′ M″ : List Var} {Γ′ : TEnv} {σ′ : Env Loan} → + Inv M σ Γ → Excl σ → DS s → R4S s → + check (M , Γ) s ≡ just (M′ , Γ′) → + step ρ (M , σ) s ≡ just (M″ , σ′) → Excl σ′ +step-excl ρ M σ Γ (lettup t e) inv ex ((() , _) , _) r4 c st +step-excl ρ M σ Γ (assign r e) inv ex (_ , () , _) r4 c st +step-excl ρ M σ Γ (assignif b′ r e) inv ex (_ , () , _) r4 c st +step-excl ρ M σ Γ (letref r e) inv ex ((_ , w) , _ , r3) r4 c st + with bind-inv (trackR M Γ e) _ c | bind-inv (evalR ρ M σ e) _ st +... | L , t , _ | v , ev , st′ with state-inv st′ +... | _ , refl = evalR-compat ρ M σ Γ e inv ex w r3 r4 t ev , ex +step-excl ρ M σ Γ (consume x) inv ex d r4 c st + with state-inv (snd (when-inv (not (mem x M)) st)) +... | _ , refl = ex +step-excl ρ M σ Γ (deref r) inv ex d r4 c st + with bind-inv (lookup r σ) _ st +... | v , ev , st′ with state-inv (snd (when-inv (alive M v) st′)) +... | _ , refl = ex +step-excl ρ M σ Γ (expire r) inv ex d r4 c st + with bind-inv (lookup r σ) _ st +... | v , ev , st′ with state-inv st′ +... | _ , refl = Excl-remove σ r ex + +run-excl : (ρ : Oracle) (p : Prog) (M : List Var) (σ : Env Loan) (Γ : TEnv) + {M′ : List Var} {Γ′ : TEnv} → Inv M σ Γ → Excl σ → D p → R4 p → + chk (M , Γ) p ≡ just (M′ , Γ′) → + Σ (Env Loan) (λ σ′ → (run ρ (M , σ) p ≡ just (M′ , σ′)) × Excl σ′) +run-excl ρ [] M σ Γ inv ex d r4 c with state-inv c +... | refl , refl = σ , refl , ex +run-excl ρ (s ∷ p) M σ Γ inv ex (ds , d) (r4s , r4) c + with bind-inv (check (M , Γ) s) _ c +... | (M₁ , Γ₁) , cs , c′ with step-sim ρ M σ Γ s inv ds cs +... | σ₁ , es , inv₁ + with run-excl ρ p M₁ σ₁ Γ₁ inv₁ (step-excl ρ M σ Γ s inv ex ds r4s cs es) d r4 c′ +... | σ′ , er , ex′ = σ′ , bind-intro es er , ex′ + +-- (ii) EXCLUSIVITY. After any execution of an accepted D+R4 program, two +-- usable references to one place are both shared. +exclusivity : (p : Prog) → D p → R4 p → {M : List Var} {Γ : TEnv} → + chk initC p ≡ just (M , Γ) → (ρ : Oracle) → + Σ (Env Loan) (λ σ → (run ρ init p ≡ just (M , σ)) × Excl σ) +exclusivity p d r4 c ρ = run-excl ρ p [] [] [] tt tt d r4 c + +-- (iii) REJECTION, the half for (ii): a D+R4 program some execution of which +-- reaches a store that is not exclusive is rejected. (`stuck-rejected` is +-- the half for use after move.) +aliasing-rejected : (p : Prog) → D p → R4 p → (ρ : Oracle) {s : Store} → + run ρ init p ≡ just s → ¬ Excl (snd s) → chk initC p ≡ nothing +aliasing-rejected p d r4 ρ {s} h nx with maybe-case (chk initC p) +... | inl e = e +... | inr ((M , Γ) , e) with exclusivity p d r4 e ρ +... | σ , er , ex = + ⊥-elim (nx (subst (λ s′ → Excl (snd s′)) (sym (just-inj (trans (sym h) er))) ex)) + +-- U-G1 (#847, the 16th): let r = &mut x; let r2 = r; (then *r2 = …; *r = …) +UG1 : Prog +UG1 = letref r (borrow mut a) ∷ letref r₂ (copy mut r) ∷ [] + +UG1-D : D UG1 -- it passes R1, R2 and R3 +UG1-D = ((tt , tt) , tt , tt) , ((tt , tt) , tt , tt) , tt + +UG1-not-R4 : ¬ R4 UG1 -- R4: an exclusive reference is copied +UG1-not-R4 (_ , () , _) + +UG1-accepted : chk initC UG1 + ≡ just ([] , (r₂ , loan a mut ∷ []) ∷ (r , loan a mut ∷ []) ∷ []) +UG1-accepted = refl + +UG1-run : (ρ : Oracle) → run ρ init UG1 + ≡ just ([] , (r₂ , loan a mut) ∷ (r , loan a mut) ∷ []) +UG1-run ρ = refl + +UG1-not-Excl : ¬ Excl ((r₂ , loan a mut) ∷ (r , loan a mut) ∷ []) +UG1-not-Excl ((() , _) , _) + +-- It is NOT a provenance failure: G holds, because U-G1 is in D. +UG1-G : G UG1 +UG1-G = G-holds UG1 UG1-D + +-- K-4, the control: let r = &mut x; let r2 = &mut x; +K4 : Prog +K4 = letref r (borrow mut a) ∷ letref r₂ (borrow mut a) ∷ [] + +K4-rejected : chk initC K4 ≡ nothing +K4-rejected = refl + +-- A D+R4 program that is accepted, so (ii) is not vacuous: +-- let r = &a; let r2 = r; (both usable) +S12 : Prog +S12 = letref r (borrow shr a) ∷ letref r₂ (copy shr r) ∷ deref r ∷ deref r₂ ∷ [] + +S12-accepted : chk initC S12 + ≡ just ([] , (r₂ , loan a shr ∷ []) ∷ (r , loan a shr ∷ []) ∷ []) +S12-accepted = refl + +-- D-01, D-06 and D-19 above use only shared references, so they are in D+R4 +-- too. R4 does not touch the three production holes they record. +D01-R4 : R4 D01 +D01-R4 = tt , tt , tt , tt , tt , tt + +D19-R4 : R4 D19 +D19-R4 = tt , tt , tt , tt diff --git a/formal/agda/QttSemiring.agda b/formal/agda/QttSemiring.agda new file mode 100644 index 00000000..13b65b10 --- /dev/null +++ b/formal/agda/QttSemiring.agda @@ -0,0 +1,282 @@ +{-# OPTIONS --safe --without-K --cubical-compatible #-} +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- QttSemiring.agda +-- ════════════════ +-- The QTT quantity semiring {0, 1, ω}: the Agda source of truth for the +-- theory statements of `formal/QttSemiring.v` (PROOF-POLICY §1; obligation +-- P-4 of docs/PROOF-NEEDS.adoc). The Rocq file is this source's Rocq leg. +-- The statement-by-statement comparison is in `formal/agda/README.adoc`. +-- +-- Contents, in the order of the Rocq file: +-- * `quant`, context addition `qplus`, scaling `qmult`; +-- * the twelve semiring laws, by exhaustive case analysis; +-- * the usage order 0 ≤ 1 ≤ ω, as `rank p ≤ rank q`; +-- * the affine facts: 1 + 1 = ω, which exceeds the affine bound `≤ 1`; +-- * the bridge `qof (m + n) ≡ qplus (qof m) (qof n)`: occurrences add. +-- +-- What is modelled: the algebra only. Nothing here mentions +-- `lib/quantity.ml`; that the tables below equal `q_add` / `q_mul` there is +-- a separate (engineering) claim, held by inspection today. +-- +-- Checked with exactly `agda --safe --without-K --cubical-compatible` +-- (`just -f formal/justfile check-agda`). `--safe` refuses postulates. +-- +-- The import cone is this file plus `Agda.Builtin.Nat` and +-- `Agda.Builtin.Equality` (and `Agda.Builtin.Bool`, which the former +-- imports). No agda-stdlib. The logic (⊥, ⊤, ¬, ×, ≤) is defined here so that +-- no library enters the cone. + +module QttSemiring where + +open import Agda.Builtin.Nat using (zero; suc; _+_) renaming (Nat to ℕ) +open import Agda.Builtin.Equality using (_≡_; refl) + +------------------------------------------------------------------------ +-- Logic + +data ⊥ : Set where + +record ⊤ : Set where + constructor tt + +infix 3 ¬_ +¬_ : Set → Set +¬ A = A → ⊥ + +infixr 2 _×_ +infixr 4 _,_ +record _×_ (A B : Set) : Set where + constructor _,_ + field + fst : A + snd : B + +-- The order on ℕ, with the constructors of Rocq's `le` (`le_n`, `le_S`), so +-- that `qle` below unfolds to the same inductive family as in the Rocq leg. +infix 4 _≤_ +data _≤_ (n : ℕ) : ℕ → Set where + le-n : n ≤ n + le-S : ∀ {m} → n ≤ m → n ≤ suc m + +≤-trans : ∀ {l m n} → l ≤ m → m ≤ n → l ≤ n +≤-trans p le-n = p +≤-trans p (le-S q) = le-S (≤-trans p q) + +0≤ : ∀ n → 0 ≤ n +0≤ zero = le-n +0≤ (suc n) = le-S (0≤ n) + +-- The same order, computed by recursion. It is used only to refute a closed +-- instance (`2 ≤ 1` below) without matching on `_≤_` at a non-variable +-- index: under --cubical-compatible that match needs injectivity of `suc` +-- and draws the UnsupportedIndexedMatch warning. Every match on `_≤_` in +-- this file is at variable indices. +Le : ℕ → ℕ → Set +Le zero n = ⊤ +Le (suc m) zero = ⊥ +Le (suc m) (suc n) = Le m n + +Le-refl : ∀ n → Le n n +Le-refl zero = tt +Le-refl (suc n) = Le-refl n + +Le-step : ∀ m n → Le m n → Le m (suc n) +Le-step zero n l = tt +Le-step (suc m) zero () +Le-step (suc m) (suc n) l = Le-step m n l + +≤→Le : ∀ {m n} → m ≤ n → Le m n +≤→Le {m} le-n = Le-refl m +≤→Le {m} (le-S {n} p) = Le-step m n (≤→Le p) + +------------------------------------------------------------------------ +-- The carrier and its two operations + +data quant : Set where + Zero One Omega : quant + +-- Context addition: how usages combine when a variable is used in two +-- places. 1 + 1 = ω is the crux: two linear uses exceed the affine bound. +qplus : quant → quant → quant +qplus Zero q = q +qplus One Zero = One +qplus One One = Omega +qplus One Omega = Omega +qplus Omega q = Omega + +-- Scaling: how a usage is multiplied when it passes through a binder of a +-- given multiplicity. +qmult : quant → quant → quant +qmult Zero q = Zero +qmult One q = q +qmult Omega Zero = Zero +qmult Omega One = Omega +qmult Omega Omega = Omega + +------------------------------------------------------------------------ +-- Semiring laws (exhaustive case analysis) + +qplus-0-l : ∀ q → qplus Zero q ≡ q +qplus-0-l q = refl + +qplus-0-r : ∀ q → qplus q Zero ≡ q +qplus-0-r Zero = refl +qplus-0-r One = refl +qplus-0-r Omega = refl + +qplus-comm : ∀ p q → qplus p q ≡ qplus q p +qplus-comm Zero Zero = refl +qplus-comm Zero One = refl +qplus-comm Zero Omega = refl +qplus-comm One Zero = refl +qplus-comm One One = refl +qplus-comm One Omega = refl +qplus-comm Omega Zero = refl +qplus-comm Omega One = refl +qplus-comm Omega Omega = refl + +qplus-assoc : ∀ p q r → qplus p (qplus q r) ≡ qplus (qplus p q) r +qplus-assoc Zero q r = refl +qplus-assoc One Zero r = refl +qplus-assoc One One Zero = refl +qplus-assoc One One One = refl +qplus-assoc One One Omega = refl +qplus-assoc One Omega r = refl +qplus-assoc Omega q r = refl + +qmult-0-l : ∀ q → qmult Zero q ≡ Zero +qmult-0-l q = refl + +qmult-0-r : ∀ q → qmult q Zero ≡ Zero +qmult-0-r Zero = refl +qmult-0-r One = refl +qmult-0-r Omega = refl + +qmult-1-l : ∀ q → qmult One q ≡ q +qmult-1-l q = refl + +qmult-1-r : ∀ q → qmult q One ≡ q +qmult-1-r Zero = refl +qmult-1-r One = refl +qmult-1-r Omega = refl + +qmult-comm : ∀ p q → qmult p q ≡ qmult q p +qmult-comm Zero Zero = refl +qmult-comm Zero One = refl +qmult-comm Zero Omega = refl +qmult-comm One Zero = refl +qmult-comm One One = refl +qmult-comm One Omega = refl +qmult-comm Omega Zero = refl +qmult-comm Omega One = refl +qmult-comm Omega Omega = refl + +qmult-assoc : ∀ p q r → qmult p (qmult q r) ≡ qmult (qmult p q) r +qmult-assoc Zero q r = refl +qmult-assoc One q r = refl +qmult-assoc Omega Zero r = refl +qmult-assoc Omega One Zero = refl +qmult-assoc Omega One One = refl +qmult-assoc Omega One Omega = refl +qmult-assoc Omega Omega Zero = refl +qmult-assoc Omega Omega One = refl +qmult-assoc Omega Omega Omega = refl + +qdistrib-l : ∀ p q r → qmult p (qplus q r) ≡ qplus (qmult p q) (qmult p r) +qdistrib-l Zero q r = refl +qdistrib-l One q r = refl +qdistrib-l Omega Zero Zero = refl +qdistrib-l Omega Zero One = refl +qdistrib-l Omega Zero Omega = refl +qdistrib-l Omega One Zero = refl +qdistrib-l Omega One One = refl +qdistrib-l Omega One Omega = refl +qdistrib-l Omega Omega Zero = refl +qdistrib-l Omega Omega One = refl +qdistrib-l Omega Omega Omega = refl + +qdistrib-r : ∀ p q r → qmult (qplus p q) r ≡ qplus (qmult p r) (qmult q r) +qdistrib-r Zero q r = refl +qdistrib-r One Zero Zero = refl +qdistrib-r One Zero One = refl +qdistrib-r One Zero Omega = refl +qdistrib-r One One Zero = refl +qdistrib-r One One One = refl +qdistrib-r One One Omega = refl +qdistrib-r One Omega Zero = refl +qdistrib-r One Omega One = refl +qdistrib-r One Omega Omega = refl +qdistrib-r Omega Zero Zero = refl +qdistrib-r Omega Zero One = refl +qdistrib-r Omega Zero Omega = refl +qdistrib-r Omega One Zero = refl +qdistrib-r Omega One One = refl +qdistrib-r Omega One Omega = refl +qdistrib-r Omega Omega Zero = refl +qdistrib-r Omega Omega One = refl +qdistrib-r Omega Omega Omega = refl + +------------------------------------------------------------------------ +-- The usage order 0 ≤ 1 ≤ ω + +rank : quant → ℕ +rank Zero = 0 +rank One = 1 +rank Omega = 2 + +qle : quant → quant → Set +qle p q = rank p ≤ rank q + +qle-refl : ∀ q → qle q q +qle-refl q = le-n + +qle-trans : ∀ p q r → qle p q → qle q r → qle p r +qle-trans p q r = ≤-trans + +qle-zero-min : ∀ q → qle Zero q +qle-zero-min q = 0≤ (rank q) + +qle-omega-max : ∀ q → qle q Omega +qle-omega-max Zero = le-S (le-S le-n) +qle-omega-max One = le-S le-n +qle-omega-max Omega = le-n + +------------------------------------------------------------------------ +-- The affine facts + +-- Using a linear (1) value twice overflows to ω: it exceeds the affine +-- bound `≤ 1`. This is the algebraic heart of "a linear value is used once". +linear-used-twice : qplus One One ≡ Omega +linear-used-twice = refl + +affine-bound-exceeded : ¬ qle (qplus One One) One +affine-bound-exceeded p = ≤→Le p + +-- Erased (0) variables contribute nothing and absorb under scaling. +erased-scales-away : ∀ q → qmult Zero q ≡ Zero +erased-scales-away q = refl + +------------------------------------------------------------------------ +-- Bridge: occurrence counts abstract to quantities + +qof : ℕ → quant +qof 0 = Zero +qof 1 = One +qof (suc (suc n)) = Omega + +-- `qof` is a homomorphism on addition: occurrences add under `qplus`. A +-- variable used m times in `f` and n times in `a` is used m + n times in +-- `f a`, which abstracts to `qplus`; if both are 1, the total is ω. +qof-plus : ∀ m n → qof (m + n) ≡ qplus (qof m) (qof n) +qof-plus 0 0 = refl +qof-plus 0 1 = refl +qof-plus 0 (suc (suc n)) = refl +qof-plus 1 0 = refl +qof-plus 1 1 = refl +qof-plus 1 (suc (suc n)) = refl +qof-plus (suc (suc m)) n = refl + +qof-linear-twice : (qof 1 ≡ One) × (qof (1 + 1) ≡ Omega) +qof-linear-twice = refl , refl diff --git a/formal/agda/README.adoc b/formal/agda/README.adoc new file mode 100644 index 00000000..1cc991ce --- /dev/null +++ b/formal/agda/README.adoc @@ -0,0 +1,486 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) += `formal/agda/` — Agda sources for the theory statements +:toc: + +PROOF-POLICY §1 (`metadatastician/standards` `3-practice/PROOF-POLICY.adoc`, +quoted in `docs/COMPLETION-PLAN.adoc` §5.0) makes Agda the source of truth for +*theory* statements, checked with exactly +`agda --safe --without-K --cubical-compatible`, then rechecked in Rocq and in +Lean (no Mathlib). This directory holds those Agda sources. The proofs live +here, in the home repository; `hyperpolymath/mathesis` only describes and +registers them. + +Conventions (those of mathesis, so its census can read the result): the +canonical `OPTIONS` pragma as the first line; no agda-stdlib; one module per +file, checked from this directory. + +[cols="2,3,3",options="header"] +|=== +| Module | Statement | Status (2026-12-01) + +| `QttSemiring.agda` +| The QTT quantity semiring `{0, 1, ω}`: 21 statements, the same as + `formal/QttSemiring.v` (obligation P-4) +| Checks clean under the canonical flags on Agda 2.6.3. *Not yet checked on + the pinned Agda 2.7.0.1.* No Lean leg. No receipt. So still `ungraded`. + +| `BorrowProvenance.agda` +| *Experiment* (#553, ADR-028 option G): on a toy reference calculus, the + checker's tracked loan set contains the provenance fibre for every program + in the second-class cut D; exclusivity and rejection for D+R4 +| Checks clean under the canonical flags on Agda 2.6.3. A toy model, not + `lib/borrow.ml`. No Rocq or Lean leg, no receipt: `ungraded`. Record: + `BORROW-PROVENANCE-EXPERIMENT.adoc`. +|=== + +== Checking + +[source,sh] +---- +just -f formal/justfile check-agda # the gate +just -f formal/justfile check-agda-controls # five planted failures; each must fail the gate +---- + +The gate fails when `agda` is missing, when a module lacks the canonical +pragma, contains `postulate`, exits non-zero, or prints anything but +`Checking` lines (so a warning fails). Every `*.agda` under this directory is +checked; nothing is listed by hand. + +CI runs both recipes in the `agda-proofs` job of +`.github/workflows/coq-proof-gate.yml`, on Ubuntu 24.04's `agda-bin` package +(Agda 2.6.3). + +== What is and is not established + +Established, by runs in this session (2026-12-01, container Ubuntu 24.04): + +* `QttSemiring.agda` checks with exit 0 and no warning under + `agda --safe --without-K --cubical-compatible`, Agda 2.6.3 (Ubuntu 24.04 + `agda-bin` 2.6.3-1build1). `--safe` refuses postulates; a comment-aware scan finds none. +* `formal/QttSemiring.v` checks under `coqc` 8.18.0 (the Rocq version mathesis + pins), and `Print Assumptions` reports "Closed under the global context" + for all 21 lemmas (run in a scratch copy; the `.v` file is unchanged). +* The two developments define the same operations: the 26 values + `qplus p q`, `qmult p q` (9 each), `rank p` (3) and `qof n` for `n = 0..4` + were computed by Rocq and each was then checked by `refl` against the Agda + definitions. A mutated table entry made the Agda check fail. +* The gate fails on each of five planted controls. + +Not established: + +* *The pinned Agda 2.7.0.1.* It could not be installed in the session. The + official release binary was downloaded (SHA-256 + `975b515a14877ab6bce5bfc641e16c4a3ee52ca5d7f846577dee80aa2145db8a`, taken + from the download itself and not checked against an independent record), + but the session's permission policy refused to run it. A build from Hackage + failed because `cabal-install` 3.8.1 (Ubuntu) no longer verifies Hackage's + root keys; building around that check was refused too, correctly. So the + result above is a real check on a different Agda version, and it is *not* + receipt-grade. +* *A Lean leg.* Lean 4.15.0 and 4.13.0 were downloaded and their SHA-256 + digests match the ones `docs/COMPLETION-PLAN.adoc` §5.0 records + (`af71a256…`, `44ceeac7…`), but running them was refused in this session. + No Lean file is committed, because an unchecked proof is not evidence. +* *A receipt.* A PROOF-POLICY §8.5.1 receipt names a run and a commit on the + default branch, and is written by the standards generator + (`scripts/proof-receipt.sh`). None exists for this module, and none is + faked here. +* *Reconciliation.* The comparison below is recorded; it has not been + reviewed by the owner. +* *The link to `lib/quantity.ml`.* As before, that the tables equal `q_add` / + `q_mul` is by inspection only. + +== Statement comparison: Agda source and the Rocq leg + +Rocq statements are as printed by `Check` under coqc 8.18.0. Names differ only +by `_` → `-` (in Agda an underscore in a name marks an operator argument +position). + +[cols="1,3,3,2",options="header"] +|=== +| # | Rocq (`formal/QttSemiring.v`) | Agda (`formal/agda/QttSemiring.agda`) | Difference + +| 1 | `qplus_0_l : forall q, qplus Zero q = q` | `qplus-0-l : ∀ q → qplus Zero q ≡ q` | none +| 2 | `qplus_0_r : forall q, qplus q Zero = q` | `qplus-0-r : ∀ q → qplus q Zero ≡ q` | none +| 3 | `qplus_comm : forall p q, qplus p q = qplus q p` | `qplus-comm : ∀ p q → qplus p q ≡ qplus q p` | none +| 4 | `qplus_assoc : forall p q r, qplus p (qplus q r) = qplus (qplus p q) r` | `qplus-assoc : ∀ p q r → qplus p (qplus q r) ≡ qplus (qplus p q) r` | none +| 5 | `qmult_0_l : forall q, qmult Zero q = Zero` | `qmult-0-l : ∀ q → qmult Zero q ≡ Zero` | none +| 6 | `qmult_0_r : forall q, qmult q Zero = Zero` | `qmult-0-r : ∀ q → qmult q Zero ≡ Zero` | none +| 7 | `qmult_1_l : forall q, qmult One q = q` | `qmult-1-l : ∀ q → qmult One q ≡ q` | none +| 8 | `qmult_1_r : forall q, qmult q One = q` | `qmult-1-r : ∀ q → qmult q One ≡ q` | none +| 9 | `qmult_comm : forall p q, qmult p q = qmult q p` | `qmult-comm : ∀ p q → qmult p q ≡ qmult q p` | none +| 10 | `qmult_assoc : forall p q r, qmult p (qmult q r) = qmult (qmult p q) r` | `qmult-assoc : ∀ p q r → qmult p (qmult q r) ≡ qmult (qmult p q) r` | none +| 11 | `qdistrib_l : forall p q r, qmult p (qplus q r) = qplus (qmult p q) (qmult p r)` | `qdistrib-l : ∀ p q r → qmult p (qplus q r) ≡ qplus (qmult p q) (qmult p r)` | none +| 12 | `qdistrib_r : forall p q r, qmult (qplus p q) r = qplus (qmult p r) (qmult q r)` | `qdistrib-r : ∀ p q r → qmult (qplus p q) r ≡ qplus (qmult p r) (qmult q r)` | none +| 13 | `qle_refl : forall q, qle q q` | `qle-refl : ∀ q → qle q q` | D2, D3 +| 14 | `qle_trans : forall p q r, qle p q -> qle q r -> qle p r` | `qle-trans : ∀ p q r → qle p q → qle q r → qle p r` | D2, D3 +| 15 | `qle_zero_min : forall q, qle Zero q` | `qle-zero-min : ∀ q → qle Zero q` | D2, D3 +| 16 | `qle_omega_max : forall q, qle q Omega` | `qle-omega-max : ∀ q → qle q Omega` | D2, D3 +| 17 | `linear_used_twice : qplus One One = Omega` | `linear-used-twice : qplus One One ≡ Omega` | none +| 18 | `affine_bound_exceeded : ~ qle (qplus One One) One` | `affine-bound-exceeded : ¬ qle (qplus One One) One` | D2, D3, D4 +| 19 | `erased_scales_away : forall q, qmult Zero q = Zero` | `erased-scales-away : ∀ q → qmult Zero q ≡ Zero` | none +| 20 | `qof_plus : forall m n, qof (m + n) = qplus (qof m) (qof n)` | `qof-plus : ∀ m n → qof (m + n) ≡ qplus (qof m) (qof n)` | D1 +| 21 | `qof_linear_twice : qof 1 = One /\ qof (1 + 1) = Omega` | `qof-linear-twice : (qof 1 ≡ One) × (qof (1 + 1) ≡ Omega)` | D1, D5 +|=== + +No statement had to be weakened, strengthened or restated. The differences are +in the ambient definitions each prover supplies: + +D1. *Natural numbers.* Rocq `nat` and `Nat.add` from the standard library; +Agda `Agda.Builtin.Nat` (`zero`/`suc`, `_+_` by recursion on the first +argument, as in Rocq). + +D2. *The order.* Rocq `qle p q := rank p <= rank q` with the library `le` +(constructors `le_n`, `le_S`). Agda defines `_≤_` locally with the same two +constructors (`le-n`, `le-S`), so `qle` is the same inductive family, but it is +a local definition and not a library one. + +D3. *Universe.* Rocq's `le` and `qle` live in `Prop`; Agda's live in `Set`. +Without `Prop`, the Agda statement is about a proof-relevant type. For these +statements (inhabitation and emptiness of `rank p ≤ rank q`) the two readings +agree. + +D4. *Negation.* Rocq `~ A` is `A -> False`; Agda `¬ A` is `A → ⊥` with a +locally defined empty type. + +D5. *Conjunction.* Rocq `/\` in `Prop`; Agda a locally defined record `_×_` +in `Set`. + +Equality is Rocq's `eq` and Agda's `Agda.Builtin.Equality._≡_`, both the +inductive identity type; `--without-K` withholds uniqueness of identity +proofs, which no statement here uses. + +The definitions of `qplus` and `qmult` are written with flat clauses in Agda +where Rocq nests `match`; the table check above shows they agree on all nine +inputs each. + +== Pilot log (measured, 2026-12-01, UTC) + +All times are this agent session's wall clock. They measure an automated +port, not a person's working time. + +[cols="1,4",options="header"] +|=== +| Time | Event + +| 18:10:45 | Session start; read `QttSemiring.v`, the plan §5.0, the manifests. +| 18:11–18:16 | Toolchain. Agda 2.7.0.1 release binary downloaded, run refused. Hackage build: index signature check fails on cabal 3.8.1; build around it refused. Fallback: `apt-get install agda-bin` → Agda 2.6.3, 18:16:06. +| 18:14:46 | Branch cut from `origin/main` (`4248912`); port started. +| 18:16:16 | First check: type-correct, but one `UnsupportedIndexedMatch` warning (see F1). +| 18:16:39 | Warning removed; clean check. *Port proper: about 2 minutes.* Check time 0.28 s. +| 18:17:18 | Rocq leg: coqc 8.18.0, 0.32 s; 21 of 21 "Closed under the global context". +| 18:18 | Gate and five planted controls written and run; table cross-check (26 values) and its mutation control. +| 18:18:52 | Existing `just check` (20 Coq files): pass, 9.6 s. +| 18:20:05–18:20:45 | Calibration probe: `P2_Progress.v` ported in a scratch directory (not committed), 40 s, see below. +|=== + +SHA-256 of the files compared: +`formal/QttSemiring.v` `548dda139161957f418d03e9a803ddd781f7660cbdf0283d56e1a9f3112b5318`. +The Agda file's digest at the commit is `git hash-object`-recoverable; it is +not repeated here because this README is committed with it. + +=== Size + +[cols="2,1,1,1",options="header"] +|=== +| | Rocq | Agda | Ratio + +| Lines, all | 109 | 282 | 2.6 +| Lines, non-blank and non-comment | 51 | 178 | 3.5 +|=== + +The ratio is high for one reason: `destruct p, q, r; reflexivity` is one line +for 27 cases, and Agda writes the cases out. 86 of the 178 Agda code lines +are `… = refl` clauses. Where the first argument decides the result the clauses were +merged by hand (`qplus-assoc` needs 7 clauses, not 27). + +=== Rocq automation that needed manual replacement + +[cols="2,1,4",options="header"] +|=== +| Rocq | Uses | Agda replacement + +| `destruct …; reflexivity` | 9 lemmas | Explicit clauses, each `refl`. Mechanical. +| `reflexivity` alone (one after `split`) | 6 lemmas | `refl` (a pair of them for the conjunction). Same. +| `lia` | 2 | `qle_omega_max`: three explicit derivations (`le-S (le-S le-n)` …). `affine_bound_exceeded`: see F1; about 16 extra lines. +| `apply Nat.le_refl` / `Nat.le_trans` / `Nat.le_0_l`, `eauto` | 3 | `le-n`; a local `≤-trans` (3 lines); a local `0≤` (3 lines). No stdlib, so each library lemma used is re-proved locally. +| nested `destruct m as [\|[\|m]]` | 1 | Seven clauses on the patterns `0`, `1`, `suc (suc n)`. +|=== + +=== `--without-K` / `--cubical-compatible` friction + +F1. `affine-bound-exceeded : ¬ (2 ≤ 1)`. The direct proof matches on `_≤_` at +the closed index `1` (`affine-bound-exceeded (le-S ())`). Agda accepts it, but +under `--cubical-compatible` it warns `UnsupportedIndexedMatch` ("relies on +injectivity of the data constructor suc"). The committed proof avoids the +match: it maps `m ≤ n` into an order computed by recursion (`Le`), where +`Le 2 1` reduces to `⊥`. Cost: about 16 lines for one lemma. Nothing else in the +file touched K or indexed matching: every other proof is `refl` on a closed +finite case, or a match at variable indices. + +The same warning is what `docs/COMPLETION-PLAN.adoc` reports for secret-types +(`-W noUnsupportedIndexedMatch`). mathesis's own gate tests only the exit +code, so it lets the warning through; the gate here does not. Which of the two +the estate wants is an open decision (below). + +=== Calibration probe: `P2_Progress` (scratch, not committed) + +`QttSemiring` is all finite case analysis, so its ratio says little about the +inductive metatheory files. To get a second data point, `P2_Progress.v` +(progress and preservation for a nat/bool language; `inversion`, `eauto`) was +ported in a scratch directory and checked under the same flags. Its statements +were not compared line by line and its `Siblings_Stated` discharge +definitions were not ported, so it is a probe, not a deliverable. + +[cols="3,1,1",options="header"] +|=== +| | Code lines | Ratio to Rocq (65) + +| Agda, direct pattern matching (checks, exit 0, but 6 `UnsupportedIndexedMatch` warnings, all in `preservation`) | 61 | 0.9 +| Agda, warning-free (typing inversion computed from the term, as in F1) | 84 | 1.3 +|=== + +`canon_*` and `progress` were warning-free as first written. `preservation` +matches a typing derivation and a step at the same term, which needs +constructor injectivity; that is the pattern every preservation proof has. +`inversion`/`eauto` cost nothing to replace: dependent pattern matching does +their work. + +== Extrapolation to the remaining theory files + +Method: Rocq non-comment lines × a ratio chosen by proof style. The two +measured ratios are 3.5 (case enumeration) and 0.9–1.3 (inversion-style +metatheory, the upper figure being warning-free). These are two data points; +the ranges below are judgement built on them, not measurements. + +[cols="2,1,1,3,2",options="header"] +|=== +| File | Rocq code lines | Lemmas | What drives the cost | Agda code lines (estimate) + +| shared prelude (new) +| — +| — +| No stdlib: ℕ arithmetic (`+` assoc/comm, `*` distributes), `≤`, decidable equality on ℕ, `List`, `Maybe`, Σ, ⊎. Written once. +| 150–300 + +| `AffineUsage` +| 47 +| 4 +| `count` over terms with `Nat.eqb`; 1 `lia`; `rewrite`. +| 60–130 + +| `QttTyping` +| 47 +| 2 +| 10 `rewrite`s of ℕ identities. Cheap, but the plan (P6) says this file "holds by definition" and is not a usable leg; a port would carry that weakness over. +| 60–140 + +| `QttDynamic` +| 124 +| 8 +| Substitution, 26 `rewrite`s, 21 `subst`, one `lia` closing 27 arithmetic cases, `qof_mult` (needs ℕ multiplication lemmas). +| 200–450 + +| `P2_Progress` +| 65 +| 4 +| Measured in the probe. +| 61–84 (+ ~10 for the discharge) + +| `P2_Stlc` +| 148 +| 7 +| Named variables, contexts as functions, `Nat.eqb` case splits (become `with`), substitution lemma, preservation (F1 pattern). +| 180–350 + +| `Rows` +| 350 +| 14 +| As `P2_Stlc`, plus list rows (`row_lookup`, `row_remove`), 87 `apply`, 16 `inversion`. +| 400–800 + +| Solo core (Idris2, 8 files) +| 2321 lines in all +| — +| Idris2 → Agda is closer than Rocq → Agda (both use dependent matching), but Idris2 has K. Every match the Idris code makes at a constructor-headed index is an F1 site. Not probed: the widest range. +| 2000–3500 + +| *Total* +| +| +| +| *about 3100–5800* +|=== + +What drives the uncertainty, largest first: + +. *The Solo core is unprobed.* It is more than half the total, and it is the + code most likely to lean on K. A probe of `Quantity.idr` or `Subst.idr` + would narrow it. +. *The warning policy.* If `UnsupportedIndexedMatch` must be absent (this + gate), preservation-style proofs cost about 1.3–1.4× their direct form. If + it is allowed (mathesis's gate today), take the lower figures. +. *The prelude.* No stdlib means ℕ and list lemmas are re-proved. `lia` is + used only 4 times across the seven files, so this is bounded, but + `QttDynamic`'s one `lia` closes 27 cases at once. +. *The pinned version.* Nothing here has run on Agda 2.7.0.1. Unification and + warning behaviour changed between 2.6.3 and 2.7; the files may need edits. +. *The other two legs.* Each Agda source also needs its statement comparison + with the Rocq leg and a new Lean leg (no Mathlib). The Lean leg was not + measured at all. +. *Port versus repair.* The plan's P5/P6/P8 say `QttTyping` and `P3_*` state + too little, and `Rows` is monomorphic. Porting a weak statement faithfully + yields a graded weak statement. + +Time: the pilot's port took about 2 minutes of agent time for 51 Rocq lines +and the probe 40 seconds for 65. Agent time per file is therefore small next +to the review, comparison and CI time, which were not measured per file. No +calendar estimate is offered. + +=== Would `Rows` be better as a small `--cubical` module with a quotient? + +Not as a port. `Rows.v` W0 models a row as an *ordered* list of +(label, type) with `row_lookup` / `row_remove`; no statement in it mentions +reordering, so there is nothing for a quotient to do, and the faithful Agda +source needs none. + +A quotient earns its place at W1 (row variables, P8), where `{a, b | ρ}` and +`{b, a | ρ}` must be the same row. Three routes: + +[cols="2,3,3",options="header"] +|=== +| Route | Elegance and correctness | Dependability + +| Cubical set-quotient (or a HIT of finite maps) for rows, in a `--cubical` + module +| Highest: row equality *is* path equality; functions on rows respect + reordering by construction. +| Lowest today. `--cubical` is not the canonical flag set, so the module is + outside PROOF-POLICY's theory lane unless the policy gains an exception. + Needs the `cubical` library (mathesis's pinned toolchain has none), or + about 300–600 lines of local path/quotient prelude. The Rocq and Lean legs + have no matching primitive: Lean has `Quot` (with `Quot.sound` an axiom), + Rocq needs setoids or an axiom, so the three statements stop being the + same statement. + +| Canonical representative under the canonical flags: rows as label-sorted + lists with a sortedness proof (or a finite map keyed by label) +| High: equality of rows is plain `≡`; no quotient needed. Sortedness + proofs must be propositional (true for `<` on ℕ, provable without K). +| Highest: stays in `--cubical-compatible`; ports to Rocq and Lean unchanged. + Cost: an insertion function and its lemmas, roughly 150–300 lines. + +| Setoid: lists up to a permutation relation, carried explicitly +| Lowest: every row-consuming function needs a respect lemma. +| High, and closest to `Rows.v` as written. Cost grows with every lemma. +|=== + +The sorted-representative route gives the same final result as the quotient +(reordering is invisible) without leaving the canonical lane. The cubical +route is the more elegant mathematics but changes the lane, the dependencies +and the cross-prover comparison. + +=== `agda --safe --cubical` throughout, against `--cubical-compatible` + +[cols="2,3,3",options="header"] +|=== +| | `--safe --without-K --cubical-compatible` (canonical) | `--safe --cubical` (full) + +| Policy +| The PROOF-POLICY theory lane. +| Not the canonical flags: every module would need a recorded exception, or + the policy would need to change. That is a `standards` decision, beyond + this repository. + +| Library +| None needed; builtins only. +| Path types come from `Agda.Primitive.Cubical`; anything useful (`≡` ↔ `Path`, + `isSet`, quotients, univalence) comes from the `cubical` library or is + rebuilt locally. mathesis's pinned Guix toolchain has no Agda library. + +| This pilot +| 178 code lines, 1 friction site. +| Measured (Agda 2.6.3): the committed module checks unchanged with its pragma + replaced by `--safe --cubical`, because it uses only the inductive `_≡_`. + `--cubical` does not remove F1: the direct indexed match draws the same + `UnsupportedIndexedMatch` warning under `--safe --cubical`. Not measured: + restating the laws over `Path`, which is what a cubical development would + actually use, and which needs the two equalities bridged. + +| Other legs +| Rocq and Lean state the same thing. +| Statements that use paths, HITs or univalence have no Rocq or Lean + counterpart without axioms, so "rechecked in Rocq and Lean" fails for them. + +| What it buys +| — +| Quotients and function extensionality without axioms. In these seven files + the Rocq proofs are deliberately funext-free and quotient-free, so nothing + in them needs it today. W1 rows are the one place it could matter. + +| Engineering files +| Out of scope either way: the policy sends them to Idris2. +| Same. +|=== + +Cost of the full-cubical route, as far as it can be stated without a probe: +the canonical-route estimate above, plus a path/`isSet` prelude or a library +dependency, plus the loss of the Rocq and Lean legs for any statement that +uses a cubical primitive. A fair comparison needs a probe: one module (`Rows` +W1's row type) written both ways. + +== Does this semiring belong on mathesis's theory shelf? + +mathesis's admission rule (`docs/theory/README.adoc`) has three conditions. +Reasons each way; the decision is the owner's. + +[cols="2,4",options="header"] +|=== +| Condition | Assessment + +| 1. It is theory (true of any implementation) +| Met. The file names no type, function or wire format of this repository. + `{0, 1, ω}` with these tables is the standard QTT semiring. + +| 2. No single system owns it +| Arguable. For: ephapax also uses a QTT semiring, and the laws are not + AffineScript's invention. Against: the file as written is AffineScript's + (it sits in the P-4 ladder, and `qof`, `rank` and the "affine facts" are + phrased for this checker's occurrence counting). Not verified here: that + ephapax's semiring is the *same* carrier and tables. This session has no + access to that repository, and the disambiguation rule says the two + projects share no typing code. If ephapax's differs (for example a + different `ω · 0`, or an added affine `≤ 1` element), there are two + theorems, not one shared one. + +| 3. An estate rule, vocabulary or interface depends on it, and the record + names the dependant +| Not met today, as far as this repository shows. No estate rule or shared + interface is known that cites these laws. The plan's "grade-polymorphic + checking" idea (§5.2: functorise `quantity.ml` over a grade signature) would + create such an interface; it does not exist yet. +|=== + +So, on the evidence here: conditions 1 and possibly 2 hold, condition 3 does +not, and the rule needs all three. The lower-risk reading is that the theorem +stays AffineScript-owned and is registered in mathesis as a claim pin once it +has a receipt. It becomes a shelf candidate if a shared grade interface, or a +rule that both AffineScript and ephapax cite, comes to depend on it; at that +point the core twelve laws and the order (statements 1–16) are the shelf part, +and `qof` and the affine facts (17–21) stay here. + +This touches more than this repository: the ephapax comparison, the mathesis +admission record and any shared grade signature are estate-level items. + +== Open decisions for the owner + +. How to provision the pinned Agda 2.7.0.1 for this repository's CI: the + mathesis route (Guix time-machine with its `build/channels.scm`), or the + checksum-pinned official release binary. Until then the CI job runs + Agda 2.6.3 and says so. +. Whether `UnsupportedIndexedMatch` fails the gate (as here) or passes (as in + mathesis's `check-proofs.sh`). +. Whether to port the remaining theory files as they stand, or first repair + the statements the plan calls weak (`QttTyping`; `Rows` W1). +. The shelf question above. diff --git a/formal/justfile b/formal/justfile index e35ed1f2..3d20b6a7 100644 --- a/formal/justfile +++ b/formal/justfile @@ -27,3 +27,75 @@ check: # Remove Coq build artifacts. clean: rm -f *.vo *.vok *.vos *.glob .*.aux .coqdeps.d + find agda -name "*.agdai" -delete + +# ── Agda (theory source of truth, PROOF-POLICY §1) ────────────────────────── +# The Agda version the estate proof lanes pin (mathesis +# `.github/workflows/agda-proof-policy.yml`, AGDA_VERSION). A run under any +# other version is a real check but is NOT receipt-grade; the recipe says so. +agda_pin := "2.7.0.1" + +# Check every Agda module under DIR (default `agda/`) with exactly the +# canonical flags. Fail-closed: a missing `agda` fails; every `*.agda` on disk +# is checked (nothing is listed by hand, so nothing can be left out); a module +# must carry the canonical OPTIONS pragma as its first line, must not contain +# the word `postulate` outside comments, and must check with no output other +# than `Checking` lines (so a warning, e.g. UnsupportedIndexedMatch, fails). +check-agda DIR="agda": + #!/usr/bin/env bash + set -euo pipefail + export LC_ALL=C.UTF-8 + cd "{{DIR}}" + command -v agda >/dev/null || { echo "::error:: agda is not installed — the gate cannot run, so it fails"; exit 1; } + ver="$(agda --version | head -1)" + echo "$ver" + if [ "$ver" != "Agda version {{agda_pin}}" ]; then + echo "::warning:: not the pinned Agda {{agda_pin}}: this run is a check, not a receipt-grade run" + fi + pragma='{-# OPTIONS --safe --without-K --cubical-compatible #-}' + n=0 + while IFS= read -r m; do + n=$((n+1)) + echo "== agda --safe --without-K --cubical-compatible $m ==" + if [ "$(head -1 "$m")" != "$pragma" ]; then + echo "::error file=$m:: first line is not the canonical OPTIONS pragma"; exit 1 + fi + # Strip `{- … -}` block comments and `--` line comments, then look for + # the keyword. `--safe` already refuses postulates; this is a second, + # independent check that reads the source, not the checker's verdict. + if perl -0pe 's/\{-.*?-\}//gs; s/--.*$//gm' "$m" | grep -qw postulate; then + echo "::error file=$m:: contains a postulate"; exit 1 + fi + rm -f "${m%.agda}.agdai" + set +e + out="$(cd "$(dirname "$m")" && agda --safe --without-K --cubical-compatible "$(basename "$m")" 2>&1)"; rc=$? + set -e + printf '%s\n' "$out" + if [ "$rc" -ne 0 ]; then echo "::error file=$m:: agda exited $rc"; exit 1; fi + if printf '%s\n' "$out" | grep -qvE '^ *(Checking|Finished) |^$'; then + echo "::error file=$m:: agda printed a warning or other diagnostic"; exit 1 + fi + done < <(find . -name '*.agda' | LC_ALL=C sort) + [ "$n" -gt 0 ] || { echo "::error:: no Agda module found under {{DIR}} — refusing to pass on nothing"; exit 1; } + echo "OK: $n Agda module(s) check under the canonical flags; no postulates." + +# Planted controls for `check-agda`: each must make the gate FAIL. A gate that +# has never been watched failing is not evidence. +check-agda-controls: + #!/usr/bin/env bash + set -euo pipefail + t="$(mktemp -d)"; trap 'rm -rf "$t"' EXIT + p='{-# OPTIONS --safe --without-K --cubical-compatible #-}' + plant() { mkdir -p "$t/$1"; printf '%s\n' "$p" "module C where" "$2" > "$t/$1/C.agda"; } + plant postulate $'data ⊥ : Set where\npostulate bad : ⊥' + plant false $'data B : Set where t f : B\ndata _≡_ (x : B) : B → Set where refl : x ≡ x\nbad : t ≡ f\nbad = refl' + plant indexed $'data N : Set where z : N ; s : N → N\ndata ⊥ : Set where\ndata L (n : N) : N → Set where ln : L n n ; lS : ∀ {m} → L n m → L n (s m)\nbad : L (s (s z)) (s z) → ⊥\nbad (lS ())' + mkdir -p "$t/nopragma"; printf 'module C where\n' > "$t/nopragma/C.agda" + mkdir -p "$t/empty" + for c in postulate false indexed nopragma empty; do + if just -f "{{justfile()}}" check-agda "$t/$c" >"$t/$c.log" 2>&1; then + echo "::error:: control '$c' PASSED the gate — the gate is broken"; cat "$t/$c.log"; exit 1 + fi + echo "control '$c': gate failed as it must ($(grep -m1 -o '::error.*' "$t/$c.log" | cut -c1-90))" + done + echo "OK: all 5 planted controls fail the Agda gate."