diff --git a/AFFIRMATION.adoc b/AFFIRMATION.adoc index 25151646..7e7e64c4 100644 --- a/AFFIRMATION.adoc +++ b/AFFIRMATION.adoc @@ -27,7 +27,7 @@ state and commitments. Companion detail: model checking, which is `tested-only`, not a proof). What each artefact proves, and how strongly, is the proof ledger (`verification/proof-ledger.jsonl`, rendered in - `verification/PROOF-STATUS.adoc#proof-ledger`): 27 proven of 47; + `verification/PROOF-STATUS.adoc#proof-ledger`): 33 proven of 53; 0 proven-with-postulates, 11 tested-only, 2 argued, 7 open. Four of the Lean proofs rested on the Lean kernel axioms `propext` and `Quot.sound`, which a source scan does not see and `Lean.collectAxioms` does; they moved diff --git a/EXPLAINME.adoc b/EXPLAINME.adoc index 8c268540..d7241a9f 100644 --- a/EXPLAINME.adoc +++ b/EXPLAINME.adoc @@ -97,7 +97,7 @@ ____ safety-triangle routing, dispatch thresholds, quarantine, rollback, the Bayesian update and rate limiting), one Agda model of the Logtalk-to-Elixir migration, and a TLA+ model of the Kin gate that is model-checked on a bounded instance. The proofs are about models of - the code, not the Elixir runtime itself. Proof ledger: 27 proven of 47; 0 proven-with-postulates, + the code, not the Elixir runtime itself. Proof ledger: 33 proven of 53; 0 proven-with-postulates, 11 tested-only, 2 argued, 7 open ____ @@ -292,7 +292,7 @@ Census, from `scripts/proof-ledger.sh check`: [source,text] ---- -27 proven of 47; 0 proven-with-postulates, 11 tested-only, 2 argued, 7 open. +33 proven of 53; 0 proven-with-postulates, 11 tested-only, 2 argued, 7 open. ---- Of the three theory rows, `logtalk-migration` is `PWG-3`; diff --git a/README.adoc b/README.adoc index b2fd8fb3..31854362 100644 --- a/README.adoc +++ b/README.adoc @@ -29,7 +29,7 @@ It combines: safety-triangle routing, dispatch thresholds, quarantine, rollback, the Bayesian update and rate limiting), one Agda model of the Logtalk-to-Elixir migration, and a TLA+ model of the Kin gate that is model-checked on a bounded instance. The proofs are about models of - the code, not the Elixir runtime itself. Proof ledger: 27 proven of 47; 0 proven-with-postulates, + the code, not the Elixir runtime itself. Proof ledger: 33 proven of 53; 0 proven-with-postulates, 11 tested-only, 2 argued, 7 open (link:EXPLAINME.adoc#proof-ledger[details]) === Core philosophy diff --git a/scripts/check-verdicts.sh b/scripts/check-verdicts.sh index 5ebf8b08..7bbd0d18 100755 --- a/scripts/check-verdicts.sh +++ b/scripts/check-verdicts.sh @@ -48,7 +48,7 @@ export IDRIS2_PATH="$PWD/build/abi/ttc${IDRIS2_PATH:+:$IDRIS2_PATH}" # 2. No escape hatch in the modules the rejections are about. for module in src/Hypatia/ABI/Verdict.idr src/Hypatia/ABI/Retraction.idr \ src/Hypatia/ABI/RsrProfile.idr src/Hypatia/ABI/SecretAlerts.idr \ - src/Hypatia/ABI/Egress.idr; do + src/Hypatia/ABI/Egress.idr src/Hypatia/ABI/Receipt.idr; do if grep -nE 'believe_me|assert_total|assert_smaller|idris_crash|postulate|sorry|admit|native_decide|Admitted|unsafeCoerce|Obj\.magic' \ "$module"; then echo "ERROR: escape-hatch marker in $module" >&2 diff --git a/src/Hypatia/ABI/Receipt.idr b/src/Hypatia/ABI/Receipt.idr new file mode 100644 index 00000000..2e649944 --- /dev/null +++ b/src/Hypatia/ABI/Receipt.idr @@ -0,0 +1,511 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- Hypatia ABI — The E0 receipt (E0-10) +-- +-- A receipt is the record that says what the single gate did with one learning +-- event and on what evidence. docs/design/e0-receipt.adoc (section 8) names five +-- properties; this module states and proves each, over the Idris2 types only: +-- +-- P1 no two receipts of a ledger share an event_id +-- `appendRefusesDuplicate`, `appendKeepsUnique`, `appendFresh` +-- P2 a receipt cannot claim more than its evidence +-- `verifiedHasEvidence`, `creditedSuccessIsEvidenced`, `verdictIsGate` +-- P3 a revision keeps the history +-- `appendKeepsHistory`, `reviseKeepsHistory` +-- P4 a fill never overwrites +-- `fillNeverOverwrites`, `fillChangesOnlyGaps`, `fillValueIsFromExtra` +-- P5 missing_evidence is exact +-- `missingIff`, `missingEmptyIff`, `receiptMissingExact` +-- +-- What this model is NOT (each row of verification/proof-ledger.jsonl says it too): +-- * It does not cover the Elixir run time. lib/hypatia/receipt.ex is held to it +-- by test/receipt_model_mirror_test.exs for P1, P2 and P5 only. No run-time +-- code builds a revision, a fill or a withdrawal yet (E0-07), so P3 and P4 have +-- no run-time counterpart to hold. +-- * An event_id, a digest and a field value are `Nat`s: identities with decidable +-- equality. What the real strings are is outside the model. +-- * It does not prove that `missing_evidence` is sorted or free of duplicates +-- (the Nickel contract of schema/receipt.ncl and the mirror test check that), +-- that a withdrawal is idempotent or independent of order, or anything about +-- confidence (a withdrawal of a failure row raises confidence). +-- * Retraction: `Retraction.idr` retracts by POSITION and the run time retracts by +-- NAME. This module proves neither. It has no retraction: a withdrawal is a +-- revision (an appended receipt with verdict `Withdrawn` and a parent), so what +-- is proved here is about the append, by event_id. +-- * The runtime `Receipt.write` does not return an error for a duplicate +-- event_id: it writes nothing and returns :ok (an idempotent replay). The +-- model's `Left DuplicateEventId` is "the ledger is unchanged"; that is the +-- property, and the return value is a difference. +-- +-- The gate table `gate` is the table of `verdict_for` in schema/receipt.ncl, which +-- is the one-row case of OutcomeTracker.qualified_outcome_counts/1. +-- +-- Proof-bypass primitives: none (scripts/check-verdicts.sh greps for them). + +module Hypatia.ABI.Receipt + +import Data.List +import Data.List.Elem +import Data.Maybe + +%default total + +------------------------------------------------------------------------ +-- Section 1: The vocabulary +------------------------------------------------------------------------ + +||| The `verification` of a row, as OutcomeTracker.qualified_outcome_counts/1 reads it. +public export +data Qualification = QVerified | QFailed | QIncomplete | QStillPresent + | QRollbackRequested | QUnqualified + +||| What the producer said happened (`assertion.claimed_outcome`). +public export +data Claimed = CSuccess | CFailure | CFalsePositive | CUnknown + +||| What the single gate did with the event. +public export +data Verdict = CreditedSuccess | CreditedFailure | CreditedFalsePositive + | AuditOnly | Withdrawn + +||| The gate: one row, one answer (`verdict_for` in schema/receipt.ncl). +||| `Withdrawn` is never an answer of the gate. +public export +gate : Qualification -> Claimed -> Verdict +gate QVerified CSuccess = CreditedSuccess +gate QVerified CFailure = CreditedFailure +gate QFailed CFailure = CreditedFailure +gate QIncomplete CFailure = CreditedFailure +gate QVerified CFalsePositive = CreditedFalsePositive +gate QStillPresent CFalsePositive = CreditedFalsePositive +gate QRollbackRequested CFalsePositive = CreditedFalsePositive +gate _ _ = AuditOnly + +||| The closed set of names that `missing_evidence` may hold, in the sorted order +||| of the contract (after_hits, before_hits, event_id, exit_code, head_sha, +||| match_kind, pattern_id, rescan, scan_digest, subject_id, subject_identity, +||| test_digest, tool_version, verdict). +public export +data Field = AfterHits | BeforeHits | EventIdF | ExitCode | HeadSha | MatchKind + | PatternId | Rescan | ScanDigest | SubjectId | SubjectIdentity + | TestDigest | ToolVersion | ObsVerdict + +public export +allFields : List Field +allFields = [ AfterHits, BeforeHits, EventIdF, ExitCode, HeadSha, MatchKind + , PatternId, Rescan, ScanDigest, SubjectId, SubjectIdentity + , TestDigest, ToolVersion, ObsVerdict ] + +||| Every field is in the list, so no gap can hide outside it. +public export +fieldListed : (f : Field) -> Elem f Hypatia.ABI.Receipt.allFields +fieldListed AfterHits = Here +fieldListed BeforeHits = There Here +fieldListed EventIdF = There (There Here) +fieldListed ExitCode = There (There (There Here)) +fieldListed HeadSha = There (There (There (There Here))) +fieldListed MatchKind = There (There (There (There (There Here)))) +fieldListed PatternId = There (There (There (There (There (There Here))))) +fieldListed Rescan = There (There (There (There (There (There (There Here)))))) +fieldListed ScanDigest = There (There (There (There (There (There (There (There Here))))))) +fieldListed SubjectId = There (There (There (There (There (There (There (There (There Here)))))))) +fieldListed SubjectIdentity = There (There (There (There (There (There (There (There (There (There Here))))))))) +fieldListed TestDigest = There (There (There (There (There (There (There (There (There (There (There Here)))))))))) +fieldListed ToolVersion = There (There (There (There (There (There (There (There (There (There (There (There Here))))))))))) +fieldListed ObsVerdict = There (There (There (There (There (There (There (There (There (There (There (There (There Here)))))))))))) + +||| The values of the fields that may be absent: `Nothing` is a gap. +public export +Body : Type +Body = Field -> Maybe Nat + +------------------------------------------------------------------------ +-- Section 2: P5 — missing_evidence is exact +------------------------------------------------------------------------ + +public export +gapIf : Maybe Nat -> Field -> List Field -> List Field +gapIf Nothing f rest = f :: rest +gapIf (Just _) _ rest = rest + +public export +missingOf : Body -> List Field -> List Field +missingOf _ [] = [] +missingOf b (f :: fs) = gapIf (b f) f (missingOf b fs) + +||| The fields of a body that are absent, in the order of `allFields`. +public export +missing : Body -> List Field +missing b = missingOf b allFields + +elemGapIfNothing : (m : Maybe Nat) -> m = Nothing -> Elem f (gapIf m f rest) +elemGapIfNothing Nothing Refl = Here +elemGapIfNothing (Just _) Refl impossible + +elemGapIfKeeps : (m : Maybe Nat) -> Elem x rest -> Elem x (gapIf m f rest) +elemGapIfKeeps Nothing e = There e +elemGapIfKeeps (Just _) e = e + +||| A field that is a gap is named. +namedIfGap : (b : Body) -> (fs : List Field) -> (f : Field) -> b f = Nothing + -> Elem f fs -> Elem f (missingOf b fs) +namedIfGap b (f :: fs) f eq Here = elemGapIfNothing (b f) eq +namedIfGap b (g :: fs) f eq (There e) = elemGapIfKeeps (b g) (namedIfGap b fs f eq e) + +gapIfElem : (m : Maybe Nat) -> Elem x (gapIf m f rest) + -> Either (x = f, m = Nothing) (Elem x rest) +gapIfElem Nothing Here = Left (Refl, Refl) +gapIfElem Nothing (There e) = Right e +gapIfElem (Just _) e = Right e + +||| A field that is named is a gap. +gapIfNamed : (b : Body) -> (fs : List Field) -> (f : Field) + -> Elem f (missingOf b fs) -> b f = Nothing +gapIfNamed b (g :: fs) f e = case gapIfElem (b g) e of + Left (prf, eq) => rewrite prf in eq + Right e' => gapIfNamed b fs f e' + +||| P5: a field is named in `missing_evidence` exactly when it is absent. +public export +missingIff : (b : Body) -> (f : Field) -> (Elem f (missing b) -> b f = Nothing, b f = Nothing -> Elem f (missing b)) +missingIff b f = (gapIfNamed b allFields f, \eq => namedIfGap b allFields f eq (fieldListed f)) + +gapIfEmpty : (m : Maybe Nat) -> IsJust m -> rest = [] -> gapIf m f rest = [] +gapIfEmpty (Just _) ItIsJust prf = prf + +allPresentEmpty : (b : Body) -> ((f : Field) -> IsJust (b f)) -> (fs : List Field) -> missingOf b fs = [] +allPresentEmpty b pr [] = Refl +allPresentEmpty b pr (f :: fs) = gapIfEmpty (b f) (pr f) (allPresentEmpty b pr fs) + +justOrNothing : (m : Maybe a) -> Either (m = Nothing) (IsJust m) +justOrNothing Nothing = Left Refl +justOrNothing (Just _) = Right ItIsJust + +||| P5: the set is empty exactly when every field is present. +public export +missingEmptyIff : (b : Body) -> (missing b = [] -> (f : Field) -> IsJust (b f), ((f : Field) -> IsJust (b f)) -> missing b = []) +missingEmptyIff b = (forward, \pr => allPresentEmpty b pr allFields) + where + forward : missing b = [] -> (f : Field) -> IsJust (b f) + forward emp f = case justOrNothing (b f) of + Right j => j + Left eq => absurd (replace {p = Elem f} emp (snd (missingIff b f) eq)) + +------------------------------------------------------------------------ +-- Section 3: Receipts (P2) +------------------------------------------------------------------------ + +||| A receipt. It cannot be built unless: +||| * its verdict is the answer of the gate for its qualification and claimed +||| outcome, or it is a withdrawal that names a parent (`verdictOk`); +||| * a `verified` receipt has a row digest and at least one observation +||| (`verifiedOk`); +||| * `missingEv` is exactly the gaps of `body` (`missingOk`). +public export +record Receipt where + constructor MkReceipt + eventId : Nat + parents : List Nat + qual : Qualification + claimed : Claimed + verdict : Verdict + rowDigest : Maybe Nat + observations : List Nat + body : Body + missingEv : List Field + verdictOk : Either (verdict = Withdrawn, NonEmpty parents) (verdict = gate qual claimed) + verifiedOk : qual = QVerified -> (IsJust rowDigest, NonEmpty observations) + missingOk : missingEv = missing body + +||| Build a first receipt (no parent). The verdict is the gate's; the gaps are computed. +public export +credit : (eid : Nat) -> (q : Qualification) -> (c : Claimed) -> (digest : Maybe Nat) + -> (obs : List Nat) -> (b : Body) + -> (q = QVerified -> (IsJust digest, NonEmpty obs)) -> Receipt +credit eid q c digest obs b ev = + MkReceipt eid [] q c (gate q c) digest obs b (missing b) (Right Refl) ev Refl + +||| The gate never answers `Withdrawn`. +public export +gateNeverWithdrawn : (q : Qualification) -> (c : Claimed) -> Not (gate q c = Withdrawn) +gateNeverWithdrawn QVerified CSuccess Refl impossible +gateNeverWithdrawn QVerified CFailure Refl impossible +gateNeverWithdrawn QVerified CFalsePositive Refl impossible +gateNeverWithdrawn QVerified CUnknown Refl impossible +gateNeverWithdrawn QFailed CSuccess Refl impossible +gateNeverWithdrawn QFailed CFailure Refl impossible +gateNeverWithdrawn QFailed CFalsePositive Refl impossible +gateNeverWithdrawn QFailed CUnknown Refl impossible +gateNeverWithdrawn QIncomplete CSuccess Refl impossible +gateNeverWithdrawn QIncomplete CFailure Refl impossible +gateNeverWithdrawn QIncomplete CFalsePositive Refl impossible +gateNeverWithdrawn QIncomplete CUnknown Refl impossible +gateNeverWithdrawn QStillPresent CSuccess Refl impossible +gateNeverWithdrawn QStillPresent CFailure Refl impossible +gateNeverWithdrawn QStillPresent CFalsePositive Refl impossible +gateNeverWithdrawn QStillPresent CUnknown Refl impossible +gateNeverWithdrawn QRollbackRequested CSuccess Refl impossible +gateNeverWithdrawn QRollbackRequested CFailure Refl impossible +gateNeverWithdrawn QRollbackRequested CFalsePositive Refl impossible +gateNeverWithdrawn QRollbackRequested CUnknown Refl impossible +gateNeverWithdrawn QUnqualified CSuccess Refl impossible +gateNeverWithdrawn QUnqualified CFailure Refl impossible +gateNeverWithdrawn QUnqualified CFalsePositive Refl impossible +gateNeverWithdrawn QUnqualified CUnknown Refl impossible + +successNotWithdrawn : Not (CreditedSuccess = Withdrawn) +successNotWithdrawn Refl impossible + +||| What a credited success needs: the gate answers it only for a verified, claimed success. +public export +gateSuccessInverse : (q : Qualification) -> (c : Claimed) -> gate q c = CreditedSuccess -> (q = QVerified, c = CSuccess) +gateSuccessInverse QVerified CSuccess _ = (Refl, Refl) +gateSuccessInverse QVerified CFailure Refl impossible +gateSuccessInverse QVerified CFalsePositive Refl impossible +gateSuccessInverse QVerified CUnknown Refl impossible +gateSuccessInverse QFailed CSuccess Refl impossible +gateSuccessInverse QFailed CFailure Refl impossible +gateSuccessInverse QFailed CFalsePositive Refl impossible +gateSuccessInverse QFailed CUnknown Refl impossible +gateSuccessInverse QIncomplete CSuccess Refl impossible +gateSuccessInverse QIncomplete CFailure Refl impossible +gateSuccessInverse QIncomplete CFalsePositive Refl impossible +gateSuccessInverse QIncomplete CUnknown Refl impossible +gateSuccessInverse QStillPresent CSuccess Refl impossible +gateSuccessInverse QStillPresent CFailure Refl impossible +gateSuccessInverse QStillPresent CFalsePositive Refl impossible +gateSuccessInverse QStillPresent CUnknown Refl impossible +gateSuccessInverse QRollbackRequested CSuccess Refl impossible +gateSuccessInverse QRollbackRequested CFailure Refl impossible +gateSuccessInverse QRollbackRequested CFalsePositive Refl impossible +gateSuccessInverse QRollbackRequested CUnknown Refl impossible +gateSuccessInverse QUnqualified CSuccess Refl impossible +gateSuccessInverse QUnqualified CFailure Refl impossible +gateSuccessInverse QUnqualified CFalsePositive Refl impossible +gateSuccessInverse QUnqualified CUnknown Refl impossible + +||| P2: a receipt that is not a withdrawal has the verdict of the gate. +public export +verdictIsGate : (r : Receipt) -> Not (r.verdict = Withdrawn) -> r.verdict = gate r.qual r.claimed +verdictIsGate r notW = case r.verdictOk of + Left (w, _) => absurd (notW w) + Right g => g + +||| P2: a receipt that is `verified` has a row digest and an observation. +public export +verifiedHasEvidence : (r : Receipt) -> r.qual = QVerified -> (IsJust r.rowDigest, NonEmpty r.observations) +verifiedHasEvidence r = r.verifiedOk + +||| P2: a verified receipt with no observation does not exist. +public export +noVerifiedWithoutObservations : (r : Receipt) -> r.qual = QVerified -> r.observations = [] -> Void +noVerifiedWithoutObservations r q emp = case (verifiedHasEvidence r q) of + (_, ne) => case replace {p = \o => NonEmpty o} emp ne of + _ impossible + +||| P2: a receipt that credits a success has a row digest and an observation. +public export +creditedSuccessIsEvidenced : (r : Receipt) -> r.verdict = CreditedSuccess + -> (IsJust r.rowDigest, NonEmpty r.observations) +creditedSuccessIsEvidenced r v = case r.verdictOk of + Left (w, _) => absurd (successNotWithdrawn (trans (sym v) w)) + Right g => case gateSuccessInverse r.qual r.claimed (trans (sym g) v) of + (q, _) => verifiedHasEvidence r q + +||| A withdrawal names a parent. +public export +withdrawnHasParent : (r : Receipt) -> r.verdict = Withdrawn -> NonEmpty r.parents +withdrawnHasParent r w = case r.verdictOk of + Left (_, ne) => ne + Right g => absurd (gateNeverWithdrawn r.qual r.claimed (trans (sym g) w)) + +||| P5 on a receipt: a field is named in its `missing_evidence` exactly when it is absent. +public export +receiptMissingExact : (r : Receipt) -> (f : Field) + -> (Elem f r.missingEv -> r.body f = Nothing, r.body f = Nothing -> Elem f r.missingEv) +receiptMissingExact r f = + ( \e => fst (missingIff r.body f) (replace {p = Elem f} r.missingOk e) + , \eq => replace {p = Elem f} (sym r.missingOk) (snd (missingIff r.body f) eq) ) + +------------------------------------------------------------------------ +-- Section 4: P1 and P3 — the ledger +------------------------------------------------------------------------ + +public export +ids : List Receipt -> List Nat +ids = map eventId + +public export +predNat : Nat -> Nat +predNat Z = Z +predNat (S k) = k + +public export +zeroNotSucc : Not (Z = S k) +zeroNotSucc Refl impossible + +public export +succNotZero : Not (S k = Z) +succNotZero Refl impossible + +||| Equality of identities, decided structurally. +public export +decNat : (a, b : Nat) -> Dec (a = b) +decNat Z Z = Yes Refl +decNat Z (S _) = No zeroNotSucc +decNat (S _) Z = No succNotZero +decNat (S a) (S b) = case decNat a b of + Yes Refl => Yes Refl + No c => No (\e => c (cong predNat e)) + +||| Membership of an identity, decided. +public export +decElem : (n : Nat) -> (ns : List Nat) -> Dec (Elem n ns) +decElem n [] = No (\e => case e of _ impossible) +decElem n (m :: ms) = case decNat n m of + Yes Refl => Yes Here + No c => case decElem n ms of + Yes e => Yes (There e) + No c2 => No (\e => case e of + Here => c Refl + There e2 => c2 e2) + +||| The event_ids of a list are pairwise distinct. +public export +data Unique : List Nat -> Type where + UNil : Unique [] + UCons : Not (Elem x xs) -> Unique xs -> Unique (x :: xs) + +public export +data Refusal = DuplicateEventId + +public export +appendWith : (r : Receipt) -> (l : List Receipt) -> Dec (Elem (eventId r) (ids l)) + -> Either Refusal (List Receipt) +appendWith _ _ (Yes _) = Left DuplicateEventId +appendWith r l (No _) = Right (r :: l) + +||| Append a receipt. A ledger that already holds the receipt's event_id is not changed. +public export +append : (r : Receipt) -> (l : List Receipt) -> Either Refusal (List Receipt) +append r l = appendWith r l (decElem (eventId r) (ids l)) + +||| P1: appending to a ledger that holds the event_id is refused. +public export +appendRefusesDuplicate : (r : Receipt) -> (l : List Receipt) -> Elem (eventId r) (ids l) + -> append r l = Left DuplicateEventId +appendRefusesDuplicate r l e = go (decElem (eventId r) (ids l)) + where + go : (d : Dec (Elem (eventId r) (ids l))) -> appendWith r l d = Left DuplicateEventId + go (Yes _) = Refl + go (No c) = absurd (c e) + +||| P1: appending to a ledger that does not hold it succeeds. +public export +appendFresh : (r : Receipt) -> (l : List Receipt) -> Not (Elem (eventId r) (ids l)) + -> append r l = Right (r :: l) +appendFresh r l n = go (decElem (eventId r) (ids l)) + where + go : (d : Dec (Elem (eventId r) (ids l))) -> appendWith r l d = Right (r :: l) + go (Yes e) = absurd (n e) + go (No _) = Refl + +||| P1: a ledger of distinct event_ids stays one. +public export +appendKeepsUnique : (r : Receipt) -> (l : List Receipt) -> Unique (ids l) + -> append r l = Right l' -> Unique (ids l') +appendKeepsUnique r l u prf = go (decElem (eventId r) (ids l)) prf + where + go : {0 m : List Receipt} -> (d : Dec (Elem (eventId r) (ids l))) -> appendWith r l d = Right m -> Unique (ids m) + go (Yes _) Refl impossible + go (No c) Refl = UCons c u + +||| P3: an append keeps every receipt of the ledger before it. +public export +appendKeepsHistory : (r : Receipt) -> (l : List Receipt) -> append r l = Right l' + -> Elem x l -> Elem x l' +appendKeepsHistory r l prf e = go (decElem (eventId r) (ids l)) prf + where + go : {0 m : List Receipt} -> (d : Dec (Elem (eventId r) (ids l))) -> appendWith r l d = Right m -> Elem x m + go (Yes _) Refl impossible + go (No _) Refl = There e + +------------------------------------------------------------------------ +-- Section 5: P4 — a fill never overwrites +------------------------------------------------------------------------ + +||| What a gap-filling revision holds for a field: the old value if there is one, +||| else the new one. +public export +fillBody : (old : Body) -> (extra : Body) -> Body +fillBody old extra f = case old f of + Just v => Just v + Nothing => extra f + +||| P4: a present field is never overwritten. +public export +fillNeverOverwrites : (old, extra : Body) -> (f : Field) -> old f = Just v + -> fillBody old extra f = Just v +fillNeverOverwrites old extra f eq = rewrite eq in Refl + +justInj : Just a = Just b -> a = b +justInj Refl = Refl + +||| P4: a value that the revision holds is the old one or one that came from `extra` +||| into a gap. +public export +fillValueIsFromExtra : (old, extra : Body) -> (f : Field) -> fillBody old extra f = Just v + -> Either (old f = Just v) (old f = Nothing, extra f = Just v) +fillValueIsFromExtra old extra f prf with (old f) proof eq + fillValueIsFromExtra old extra f prf | Just w = Left (cong Just (justInj prf)) + fillValueIsFromExtra old extra f prf | Nothing = Right (Refl, prf) + +||| P4: a field whose value a fill changes was in `missing_evidence`. +public export +fillChangesOnlyGaps : (old, extra : Body) -> (f : Field) + -> Not (fillBody old extra f = old f) -> Elem f (missing old) +fillChangesOnlyGaps old extra f changed = case justOrNothing (old f) of + Left eq => snd (missingIff old f) eq + Right j => absurd (changed (keeps j)) + where + keeps : IsJust (old f) -> fillBody old extra f = old f + keeps j with (old f) proof eq + keeps ItIsJust | Just _ = Refl + +||| A revision that fills gaps: a new receipt with its own event_id whose parent is +||| the receipt it revises. It holds the same assertion, verdict and evidence. +public export +reviseFill : (old : Receipt) -> (newId : Nat) -> (extra : Body) -> Receipt +reviseFill old newId extra = + MkReceipt newId [eventId old] (qual old) (claimed old) (verdict old) + (rowDigest old) (observations old) (fillBody (body old) extra) + (missing (fillBody (body old) extra)) + (reparent (verdictOk old)) (verifiedOk old) Refl + where + reparent : Either (verdict old = Withdrawn, NonEmpty (parents old)) (verdict old = gate (qual old) (claimed old)) + -> Either (verdict old = Withdrawn, NonEmpty [eventId old]) (verdict old = gate (qual old) (claimed old)) + reparent (Left (w, _)) = Left (w, IsNonEmpty) + reparent (Right g) = Right g + +||| P3: a revision appended to a ledger that holds the receipt it revises keeps +||| every receipt of the ledger. +public export +reviseKeepsHistory : (old : Receipt) -> (newId : Nat) -> (extra : Body) -> (l : List Receipt) + -> append (reviseFill old newId extra) l = Right l' -> Elem x l -> Elem x l' +reviseKeepsHistory old newId extra l = appendKeepsHistory (reviseFill old newId extra) l + +||| P4 on the revision: it never overwrites a present field of the receipt. +public export +reviseNeverOverwrites : (old : Receipt) -> (newId : Nat) -> (extra : Body) -> (f : Field) + -> old.body f = Just v -> (reviseFill old newId extra).body f = Just v +reviseNeverOverwrites old newId extra f = fillNeverOverwrites old.body extra f + +||| The revision names the receipt it revises, and keeps what the receipt claimed. +public export +reviseKeepsClaim : (old : Receipt) -> (newId : Nat) -> (extra : Body) + -> ( (reviseFill old newId extra).parents = [old.eventId] + , (reviseFill old newId extra).qual = old.qual + , (reviseFill old newId extra).claimed = old.claimed + , (reviseFill old newId extra).verdict = old.verdict ) +reviseKeepsClaim old newId extra = (Refl, Refl, Refl, Refl) diff --git a/src/abi/hypatia-abi.ipkg b/src/abi/hypatia-abi.ipkg index 3290937f..071b2f32 100644 --- a/src/abi/hypatia-abi.ipkg +++ b/src/abi/hypatia-abi.ipkg @@ -27,6 +27,7 @@ modules = Hypatia.ABI.Types , Hypatia.ABI.Egress , Hypatia.ABI.SecretAlerts , Hypatia.ABI.RsrProfile + , Hypatia.ABI.Receipt builddir = "../../build/abi" diff --git a/test/receipt_model_mirror_test.exs b/test/receipt_model_mirror_test.exs new file mode 100644 index 00000000..22c92926 --- /dev/null +++ b/test/receipt_model_mirror_test.exs @@ -0,0 +1,407 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +defmodule Hypatia.ReceiptModelMirrorTest do + @moduledoc """ + Holds the receipt emitter (`Hypatia.Receipt`) to the model proved in + `src/Hypatia/ABI/Receipt.idr` (E0-10). + + The model covers the Idris2 types, not this run time. This test checks the + run time against it for P1, P2 and P5 of `docs/design/e0-receipt.adoc` + section 8. P3 (a revision keeps the history) and P4 (a fill never + overwrites) are properties of the model only: no run-time code builds a + revision, a fill or a withdrawal yet (E0-07), so there is nothing here to hold. + + The gate table and the list of fields are READ FROM `Receipt.idr`, not copied, + so the model and this test cannot drift apart without a failure. + + Two differences between the model and the run time are pinned below as + tests of their own, so that a change to either is noticed: + + * `Receipt.write/3` of an event_id that has a receipt writes nothing and + returns `:ok`; the model's `append` answers `Left DuplicateEventId`. The + ledger is unchanged in both, which is the property. + * `Receipt.build/2` does not refuse a `verified` row that has no + observations. The model cannot build one (`verifiedOk`), and the Nickel + contract refuses it. The production entry points never make one (see the + P2 tests); `build/2` is not a smart constructor. + """ + use ExUnit.Case, async: true + + alias Hypatia.{EventId, LearningScheduler, Receipt} + + @idris Path.expand("../src/Hypatia/ABI/Receipt.idr", __DIR__) + @contract Path.expand("../schema/receipt.ncl", __DIR__) + + @qualifications ~w(QVerified QFailed QIncomplete QStillPresent QRollbackRequested QUnqualified) + @claims ~w(CSuccess CFailure CFalsePositive CUnknown) + + # ── The model, read from the Idris file ────────────────────────────────── + + # `gate q c = v` clauses, in order, then the fall-through `gate _ _ = v`. + defp model_gate do + lines = File.read!(@idris) |> String.split("\n") + + clauses = + for line <- lines, + [_, q, c, v] <- [Regex.run(~r/^gate (Q\w+) (C\w+) = (\w+)$/, line)], + do: {q, c, v} + + [_, fallthrough] = Regex.run(~r/^gate _ _ = (\w+)$/m, File.read!(@idris)) + + fn q, c -> + case Enum.find(clauses, fn {cq, cc, _} -> cq == q and cc == c end) do + {_, _, v} -> v + nil -> fallthrough + end + end + end + + defp snake(camel) do + camel + |> String.replace(~r/([a-z])([A-Z])/, "\\1_\\2") + |> String.downcase() + end + + defp model_fields do + [_, list] = Regex.run(~r/allFields = \[(.*?)\]/s, File.read!(@idris)) + + list + |> String.split(",", trim: true) + |> Enum.map(&String.trim/1) + |> Enum.map(fn + "EventIdF" -> "event_id" + "ObsVerdict" -> "verdict" + other -> snake(other) + end) + end + + defp contract_fields do + [_, list] = Regex.run(~r/let missing_names = \[(.*?)\]/s, File.read!(@contract)) + + Regex.scan(~r/"([a-z_]+)"/, list) |> Enum.map(fn [_, name] -> name end) + end + + # ── Rows and contexts ──────────────────────────────────────────────────── + + @ctx %{ + kind: :local_caller, + log: "outcomes/2026-11.jsonl", + line: "1", + row_sha256: String.duplicate("a", 64) + } + + defp verification_fields("QVerified"), do: %{"verification" => "verified"} + defp verification_fields("QFailed"), do: %{"verification" => "failed"} + defp verification_fields("QIncomplete"), do: %{"verification" => "incomplete"} + defp verification_fields("QStillPresent"), do: %{"verification" => "still_present"} + defp verification_fields("QUnqualified"), do: %{"verification" => "unverified"} + + defp verification_fields("QRollbackRequested"), + do: %{ + "verification" => "rollback_requested", + "caused_by" => "batch_rollback", + "batch_id" => "batch-1" + } + + defp outcome("CSuccess"), do: "success" + defp outcome("CFailure"), do: "failure" + defp outcome("CFalsePositive"), do: "false_positive" + defp outcome("CUnknown"), do: "something-else" + + defp row(q, c, extra \\ %{}) do + %{"event_id" => EventId.generate(), "outcome" => outcome(c)} + |> Map.merge(verification_fields(q)) + |> Map.merge(extra) + end + + defp verdict_name("CreditedSuccess"), do: "credited_success" + defp verdict_name("CreditedFailure"), do: "credited_failure" + defp verdict_name("CreditedFalsePositive"), do: "credited_false_positive" + defp verdict_name("AuditOnly"), do: "audit_only" + + # ── P2: the verdict is the answer of the gate ──────────────────────────── + + describe "P2: the verdict is the gate's (Receipt.idr `gate`)" do + test "the model's table is read from the file, and is the whole 6 x 4 table" do + gate = model_gate() + answers = for q <- @qualifications, c <- @claims, do: gate.(q, c) + + assert length(answers) == 24 + # Withdrawn is never an answer of the gate (`gateNeverWithdrawn`). + refute "Withdrawn" in answers + assert Enum.count(answers, &(&1 == "CreditedSuccess")) == 1 + assert Enum.count(answers, &(&1 == "CreditedFailure")) == 3 + assert Enum.count(answers, &(&1 == "CreditedFalsePositive")) == 3 + end + + test "the emitter gives the model's verdict for every pair that a row can produce" do + gate = model_gate() + + results = + for q <- @qualifications, c <- @claims do + receipt = Receipt.build(row(q, c), @ctx) + + reachable = + receipt["qualification"] == Macro.underscore(String.slice(q, 1..-1//1)) and + receipt["assertion"]["claimed_outcome"] == claimed_name(c) + + {q, c, reachable, receipt} + end + + reachable = Enum.filter(results, fn {_, _, r, _} -> r end) + # 24 pairs; a rollback that the gate does not credit is recorded as + # "unqualified", so (QRollbackRequested, success | failure | unknown) are not + # pairs that a receipt can carry. + assert length(reachable) == 21 + + for {q, c, true, receipt} <- results do + assert receipt["verdict"] == verdict_name(model_gate().(q, c)), + "#{q} #{c}: the emitter says #{receipt["verdict"]}, the model says #{gate.(q, c)}" + end + + for {"QRollbackRequested", c, false, receipt} <- results do + assert c in ["CSuccess", "CFailure", "CUnknown"] + assert receipt["qualification"] == "unqualified" + assert receipt["verdict"] == "audit_only" + end + + refute Enum.any?(results, fn {_, _, _, r} -> r["verdict"] == "withdrawn" end) + end + + test "a rollback row without its batch fields is not credited" do + receipt = + Receipt.build( + %{ + "event_id" => EventId.generate(), + "outcome" => "false_positive", + "verification" => "rollback_requested" + }, + @ctx + ) + + assert receipt["qualification"] == "unqualified" + assert receipt["verdict"] == "audit_only" + end + end + + defp claimed_name("CSuccess"), do: "success" + defp claimed_name("CFailure"), do: "failure" + defp claimed_name("CFalsePositive"), do: "false_positive" + defp claimed_name("CUnknown"), do: "unknown" + + # ── P2: a verified receipt has evidence ────────────────────────────────── + + describe "P2: a verified receipt has an evidence reference and an observation" do + defp fleet_records do + for verdict <- ["verified", "failed", "incomplete", "unverified", "no_op", nil], + outcome <- ["success", "failure"], + before_hits <- [nil, 0, 2], + after_hits <- [nil, 0, 3], + exit_code <- [nil, 0, 1] do + %{ + "bot" => "robot-repo-automaton", + "recipe_id" => "recipe-x", + "repo" => "owner/repo", + "file" => "a.ex", + "verdict" => verdict, + "outcome" => outcome, + "before_hits" => before_hits, + "after_hits" => after_hits, + "exit_code" => exit_code + } + |> Enum.reject(fn {_, v} -> is_nil(v) end) + |> Map.new() + end + end + + test "a fleet row that classifies as verified always carries its numbers into the receipt" do + verified = + for record <- fleet_records(), + {:ok, _recipe, _repo, _file, outcome, "verified"} <- + [LearningScheduler.classify_fleet_record(record)] do + stored = + %{ + "event_id" => EventId.generate(), + "outcome" => Atom.to_string(outcome), + "verification" => "verified", + "origin" => "gitbot-fleet", + "source_kind" => "fleet_import" + } + |> Map.merge(Map.take(record, ["verdict", "exit_code", "before_hits", "after_hits"])) + + Receipt.build(stored, %{@ctx | kind: :fleet_import}) + end + + assert verified != [], "no case reached verified: the test would be vacuous" + + for receipt <- verified do + assert receipt["qualification"] == "verified" + assert map_size(receipt["observations"]) > 0 + assert receipt["proof_or_test_ref"]["row_sha256"] =~ ~r/\A[0-9a-f]{64}\z/ + # P2's model reading: a credited success is evidenced. + assert receipt["verdict"] == "credited_success" + end + end + + test "a local row that the rescan verified carries the rescan as its observation" do + receipt = + Receipt.build( + row("QVerified", "CSuccess", %{"source_kind" => "local_rescan"}), + %{@ctx | kind: :local_rescan} + ) + + assert receipt["qualification"] == "verified" + assert receipt["observations"]["rescan"] == "verified" + assert receipt["proof_or_test_ref"]["row_sha256"] =~ ~r/\A[0-9a-f]{64}\z/ + end + + test "KNOWN DIFFERENCE: build/2 does not refuse a verified row with no observation" do + receipt = Receipt.build(row("QVerified", "CSuccess"), @ctx) + + # The model cannot build this (`verifiedOk`) and the Nickel contract refuses + # it ("qualification verified needs observations and an evidence reference"). + # No production entry point makes such a row; build/2 is not a smart + # constructor. If build/2 or write/3 gains a guard, change this test and the + # trust-boundary text of the P2 row in verification/proof-ledger.jsonl. + assert receipt["qualification"] == "verified" + assert receipt["observations"] == %{} + end + end + + # ── P5: missing_evidence is exact ──────────────────────────────────────── + + describe "P5: missing_evidence names exactly the absent fields (Receipt.idr `missing`)" do + test "the model's 14 field names are the closed set of the contract" do + fields = model_fields() + + assert length(fields) == 14 + assert Enum.sort(fields) == Enum.sort(contract_fields()) + # The model lists them in the sorted order of the contract. + assert fields == Enum.sort(fields) + end + + # Where a name is looked for in a receipt (`gap_exact` of schema/receipt.ncl). + defp present?(receipt, name) + when name in ~w(event_id head_sha subject_id pattern_id match_kind), + do: Map.has_key?(receipt, name) + + defp present?(receipt, name) when name in ~w(after_hits before_hits exit_code rescan verdict), + do: Map.has_key?(receipt["observations"], name) + + defp present?(receipt, name) when name in ~w(scan_digest test_digest), + do: Map.has_key?(receipt["proof_or_test_ref"], name) + + defp present?(receipt, "tool_version"), + do: Map.has_key?(receipt["provenance"], "tool_version") + + # No stable finding identity exists yet (issue 984, E1). + defp present?(_receipt, "subject_identity"), do: false + + test "a field is named exactly when it is absent, for every combination of observations" do + names = model_fields() + keys = ~w(after_hits before_hits exit_code verdict rescan) + + subsets = Enum.reduce(keys, [[]], fn k, acc -> acc ++ Enum.map(acc, &[k | &1]) end) + assert length(subsets) == 32 + + for subset <- subsets do + extra = + for k <- subset, k != "rescan", into: %{} do + {k, if(k == "verdict", do: "verified", else: 1)} + end + + {kind, extra} = + if "rescan" in subset, + do: {:local_rescan, Map.put(extra, "verification", "verified")}, + else: {:local_caller, extra} + + receipt = + Receipt.build( + row("QUnqualified", "CSuccess", extra), + %{@ctx | kind: kind} + ) + + missing = receipt["missing_evidence"] + + for name <- names do + assert name in missing == not present?(receipt, name), + "#{name} with #{inspect(subset)}: named=#{name in missing}, present=#{present?(receipt, name)}" + end + + # What the model does not prove, checked here: sorted, no duplicates, and + # nothing outside the closed set. + assert missing == Enum.sort(Enum.uniq(missing)) + assert Enum.all?(missing, &(&1 in names)) + end + end + + test "at E0 the set is never empty: subject_identity cannot be filled yet" do + full = + row("QVerified", "CSuccess", %{ + "after_hits" => 0, + "before_hits" => 2, + "exit_code" => 0, + "verdict" => "verified", + "source_kind" => "local_rescan" + }) + + receipt = Receipt.build(full, %{@ctx | kind: :local_rescan}) + + # The model's "empty exactly when all present" holds; it is not reached at E0. + assert receipt["missing_evidence"] != [] + assert "subject_identity" in receipt["missing_evidence"] + end + end + + # ── P1: no two receipts share an event_id ──────────────────────────────── + + describe "P1: no two receipts share an event_id (Receipt.idr `append`)" do + setup do + root = + Path.join(System.tmp_dir!(), "receipt_model_mirror_#{System.unique_integer([:positive])}") + + File.mkdir_p!(root) + on_exit(fn -> File.rm_rf!(root) end) + {:ok, root: root} + end + + test "a second write for an event_id adds nothing, and returns :ok (a known difference)", %{ + root: root + } do + row = row("QFailed", "CFailure") + + assert :ok = Receipt.write(root, row, ctx: @ctx) + before = Receipt.all(root) + assert length(before) == 1 + + # The model answers Left DuplicateEventId; the run time returns :ok and + # leaves the ledger as it was. + assert :ok = Receipt.write(root, row, ctx: @ctx) + assert Receipt.all(root) == before + end + + test "many receipts keep distinct event_ids, and a replay of any of them adds nothing", %{ + root: root + } do + rows = for _ <- 1..40, do: row("QFailed", "CFailure") + + for r <- rows, do: assert(:ok = Receipt.write(root, r, ctx: @ctx)) + for r <- Enum.take_random(rows, 15), do: assert(:ok = Receipt.write(root, r, ctx: @ctx)) + + ids = Receipt.all(root) |> Enum.map(& &1["event_id"]) + assert length(ids) == 40 + assert length(Enum.uniq(ids)) == 40 + end + + test "a receipt is never written for an event_id that is not an id", %{root: root} do + assert {:error, :invalid_event_id} = + Receipt.write(root, %{"event_id" => "not-an-id", "outcome" => "success"}, + ctx: @ctx + ) + + assert {:error, :no_event_id} = Receipt.write(root, %{"outcome" => "success"}, ctx: @ctx) + assert Receipt.all(root) == [] + end + end +end diff --git a/tests/accept/ReceiptP1AppendDistinct.idr b/tests/accept/ReceiptP1AppendDistinct.idr new file mode 100644 index 00000000..c5da7f75 --- /dev/null +++ b/tests/accept/ReceiptP1AppendDistinct.idr @@ -0,0 +1,43 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- POSITIVE CONTROL (E0-10). Counterpart of the rejections under +-- tests/reject/Receipt*.idr and others for the same property of +-- docs/design/e0-receipt.adoc, section 8. The model covers the Idris2 types, +-- not the Elixir run time. +-- +-- P1: appending a receipt with a new event_id to a ledger succeeds and the ids stay distinct. +-- + +module ReceiptP1AppendDistinct + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP1AppendDistinct.noBody (\e => absurd (ReceiptP1AppendDistinct.notVerified e)) + + +r1 : Receipt +r1 = failedReceipt 1 + +r2 : Receipt +r2 = failedReceipt 2 + +appended : append ReceiptP1AppendDistinct.r2 [ReceiptP1AppendDistinct.r1] = Right [ReceiptP1AppendDistinct.r2, ReceiptP1AppendDistinct.r1] +appended = Refl + +refused : append ReceiptP1AppendDistinct.r1 [ReceiptP1AppendDistinct.r1] = Left DuplicateEventId +refused = Refl diff --git a/tests/accept/ReceiptP2GateTable.idr b/tests/accept/ReceiptP2GateTable.idr new file mode 100644 index 00000000..023b0a93 --- /dev/null +++ b/tests/accept/ReceiptP2GateTable.idr @@ -0,0 +1,89 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- POSITIVE CONTROL (E0-10). Pins all 24 entries of the gate table of +-- src/Hypatia/ABI/Receipt.idr to the rule `verdict_for` of schema/receipt.ncl +-- (the one-row case of OutcomeTracker.qualified_outcome_counts/1). The +-- theorems of the model hold of any table that never answers `Withdrawn` and +-- credits a success only for a verified, claimed success; this module is what +-- fixes the table itself. test/receipt_model_mirror_test.exs compares the same +-- 24 entries with the Elixir run time. + +module ReceiptP2GateTable + +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +qverified_csuccess : gate QVerified CSuccess = CreditedSuccess +qverified_csuccess = Refl + +qverified_cfailure : gate QVerified CFailure = CreditedFailure +qverified_cfailure = Refl + +qverified_cfalsepositive : gate QVerified CFalsePositive = CreditedFalsePositive +qverified_cfalsepositive = Refl + +qverified_cunknown : gate QVerified CUnknown = AuditOnly +qverified_cunknown = Refl + +qfailed_csuccess : gate QFailed CSuccess = AuditOnly +qfailed_csuccess = Refl + +qfailed_cfailure : gate QFailed CFailure = CreditedFailure +qfailed_cfailure = Refl + +qfailed_cfalsepositive : gate QFailed CFalsePositive = AuditOnly +qfailed_cfalsepositive = Refl + +qfailed_cunknown : gate QFailed CUnknown = AuditOnly +qfailed_cunknown = Refl + +qincomplete_csuccess : gate QIncomplete CSuccess = AuditOnly +qincomplete_csuccess = Refl + +qincomplete_cfailure : gate QIncomplete CFailure = CreditedFailure +qincomplete_cfailure = Refl + +qincomplete_cfalsepositive : gate QIncomplete CFalsePositive = AuditOnly +qincomplete_cfalsepositive = Refl + +qincomplete_cunknown : gate QIncomplete CUnknown = AuditOnly +qincomplete_cunknown = Refl + +qstillpresent_csuccess : gate QStillPresent CSuccess = AuditOnly +qstillpresent_csuccess = Refl + +qstillpresent_cfailure : gate QStillPresent CFailure = AuditOnly +qstillpresent_cfailure = Refl + +qstillpresent_cfalsepositive : gate QStillPresent CFalsePositive = CreditedFalsePositive +qstillpresent_cfalsepositive = Refl + +qstillpresent_cunknown : gate QStillPresent CUnknown = AuditOnly +qstillpresent_cunknown = Refl + +qrollbackrequested_csuccess : gate QRollbackRequested CSuccess = AuditOnly +qrollbackrequested_csuccess = Refl + +qrollbackrequested_cfailure : gate QRollbackRequested CFailure = AuditOnly +qrollbackrequested_cfailure = Refl + +qrollbackrequested_cfalsepositive : gate QRollbackRequested CFalsePositive = CreditedFalsePositive +qrollbackrequested_cfalsepositive = Refl + +qrollbackrequested_cunknown : gate QRollbackRequested CUnknown = AuditOnly +qrollbackrequested_cunknown = Refl + +qunqualified_csuccess : gate QUnqualified CSuccess = AuditOnly +qunqualified_csuccess = Refl + +qunqualified_cfailure : gate QUnqualified CFailure = AuditOnly +qunqualified_cfailure = Refl + +qunqualified_cfalsepositive : gate QUnqualified CFalsePositive = AuditOnly +qunqualified_cfalsepositive = Refl + +qunqualified_cunknown : gate QUnqualified CUnknown = AuditOnly +qunqualified_cunknown = Refl diff --git a/tests/accept/ReceiptP2VerifiedIsEvidenced.idr b/tests/accept/ReceiptP2VerifiedIsEvidenced.idr new file mode 100644 index 00000000..d7271b83 --- /dev/null +++ b/tests/accept/ReceiptP2VerifiedIsEvidenced.idr @@ -0,0 +1,40 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- POSITIVE CONTROL (E0-10). Counterpart of the rejections under +-- tests/reject/Receipt*.idr and others for the same property of +-- docs/design/e0-receipt.adoc, section 8. The model covers the Idris2 types, +-- not the Elixir run time. +-- +-- P2: a verified receipt with a row digest and an observation is built, its verdict is the gate's, and a credited success is evidenced. +-- + +module ReceiptP2VerifiedIsEvidenced + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP2VerifiedIsEvidenced.noBody (\e => absurd (ReceiptP2VerifiedIsEvidenced.notVerified e)) + + +verified : Receipt +verified = credit 1 QVerified CSuccess (Just 7) [3] ReceiptP2VerifiedIsEvidenced.noBody (\_ => (ItIsJust, IsNonEmpty)) + +isCredited : verdict ReceiptP2VerifiedIsEvidenced.verified = CreditedSuccess +isCredited = Refl + +evidenced : (IsJust (rowDigest ReceiptP2VerifiedIsEvidenced.verified), NonEmpty (observations ReceiptP2VerifiedIsEvidenced.verified)) +evidenced = creditedSuccessIsEvidenced ReceiptP2VerifiedIsEvidenced.verified Refl diff --git a/tests/accept/ReceiptP3RevisionKeepsHistory.idr b/tests/accept/ReceiptP3RevisionKeepsHistory.idr new file mode 100644 index 00000000..2de75ad4 --- /dev/null +++ b/tests/accept/ReceiptP3RevisionKeepsHistory.idr @@ -0,0 +1,50 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- POSITIVE CONTROL (E0-10). Counterpart of the rejections under +-- tests/reject/Receipt*.idr and others for the same property of +-- docs/design/e0-receipt.adoc, section 8. The model covers the Idris2 types, +-- not the Elixir run time. +-- +-- P3: a revision appended to a ledger keeps the receipt it revises. +-- + +module ReceiptP3RevisionKeepsHistory + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP3RevisionKeepsHistory.noBody (\e => absurd (ReceiptP3RevisionKeepsHistory.notVerified e)) + + +extra : Body +extra HeadSha = Just 5 +extra _ = Nothing + +original : Receipt +original = failedReceipt 1 + +revised : Receipt +revised = reviseFill ReceiptP3RevisionKeepsHistory.original 2 ReceiptP3RevisionKeepsHistory.extra + +kept : append ReceiptP3RevisionKeepsHistory.revised [ReceiptP3RevisionKeepsHistory.original] = Right [ReceiptP3RevisionKeepsHistory.revised, ReceiptP3RevisionKeepsHistory.original] +kept = Refl + +stillThere : Elem ReceiptP3RevisionKeepsHistory.original [ReceiptP3RevisionKeepsHistory.revised, ReceiptP3RevisionKeepsHistory.original] +stillThere = There Here + +named : parents ReceiptP3RevisionKeepsHistory.revised = [eventId ReceiptP3RevisionKeepsHistory.original] +named = Refl diff --git a/tests/accept/ReceiptP4FillOnlyGaps.idr b/tests/accept/ReceiptP4FillOnlyGaps.idr new file mode 100644 index 00000000..397a065f --- /dev/null +++ b/tests/accept/ReceiptP4FillOnlyGaps.idr @@ -0,0 +1,49 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- POSITIVE CONTROL (E0-10). Counterpart of the rejections under +-- tests/reject/Receipt*.idr and others for the same property of +-- docs/design/e0-receipt.adoc, section 8. The model covers the Idris2 types, +-- not the Elixir run time. +-- +-- P4: a fill keeps a present field and fills a gap. +-- + +module ReceiptP4FillOnlyGaps + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP4FillOnlyGaps.noBody (\e => absurd (ReceiptP4FillOnlyGaps.notVerified e)) + + +old : Body +old AfterHits = Just 3 +old _ = Nothing + +extra : Body +extra AfterHits = Just 9 +extra HeadSha = Just 5 +extra _ = Nothing + +keeps : fillBody ReceiptP4FillOnlyGaps.old ReceiptP4FillOnlyGaps.extra AfterHits = Just 3 +keeps = Refl + +fills : fillBody ReceiptP4FillOnlyGaps.old ReceiptP4FillOnlyGaps.extra HeadSha = Just 5 +fills = Refl + +gapWasNamed : Elem HeadSha (missing ReceiptP4FillOnlyGaps.old) +gapWasNamed = snd (missingIff ReceiptP4FillOnlyGaps.old HeadSha) Refl diff --git a/tests/accept/ReceiptP5MissingExact.idr b/tests/accept/ReceiptP5MissingExact.idr new file mode 100644 index 00000000..308cd2f1 --- /dev/null +++ b/tests/accept/ReceiptP5MissingExact.idr @@ -0,0 +1,46 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- POSITIVE CONTROL (E0-10). Counterpart of the rejections under +-- tests/reject/Receipt*.idr and others for the same property of +-- docs/design/e0-receipt.adoc, section 8. The model covers the Idris2 types, +-- not the Elixir run time. +-- +-- P5: missing_evidence names exactly the absent fields, and is empty exactly when all are present. +-- + +module ReceiptP5MissingExact + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP5MissingExact.noBody (\e => absurd (ReceiptP5MissingExact.notVerified e)) + + +partial' : Body +partial' AfterHits = Just 1 +partial' ExitCode = Just 0 +partial' _ = Nothing + +named : missing ReceiptP5MissingExact.partial' = [ BeforeHits, EventIdF, HeadSha, MatchKind, PatternId, Rescan + , ScanDigest, SubjectId, SubjectIdentity, TestDigest, ToolVersion, ObsVerdict ] +named = Refl + +complete : Body +complete _ = Just 1 + +none : missing ReceiptP5MissingExact.complete = [] +none = Refl diff --git a/tests/reject/ReceiptP1DuplicateAppended.idr b/tests/reject/ReceiptP1DuplicateAppended.idr new file mode 100644 index 00000000..cb876779 --- /dev/null +++ b/tests/reject/ReceiptP1DuplicateAppended.idr @@ -0,0 +1,38 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- EXPECTED REJECTION (E0-10). scripts/check-verdicts.sh passes only if +-- Idris2 refuses this module, and only at the declaration `invalid`. Every +-- other declaration must typecheck, so that the refusal is for the stated +-- reason and not for a missing import or a typo. +-- +-- P1: a ledger that already holds event_id 1 refuses a second receipt with it. Claiming that the append succeeds must not typecheck. +-- +-- EXPECT: Mismatch between: Right [r1, r1] and Left DuplicateEventId. + +module ReceiptP1DuplicateAppended + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP1DuplicateAppended.noBody (\e => absurd (ReceiptP1DuplicateAppended.notVerified e)) + + +r1 : Receipt +r1 = failedReceipt 1 + +invalid : append ReceiptP1DuplicateAppended.r1 [ReceiptP1DuplicateAppended.r1] = Right [ReceiptP1DuplicateAppended.r1, ReceiptP1DuplicateAppended.r1] +invalid = Refl diff --git a/tests/reject/ReceiptP2VerdictIsNotTheGate.idr b/tests/reject/ReceiptP2VerdictIsNotTheGate.idr new file mode 100644 index 00000000..0e9b59d7 --- /dev/null +++ b/tests/reject/ReceiptP2VerdictIsNotTheGate.idr @@ -0,0 +1,40 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- EXPECTED REJECTION (E0-10). scripts/check-verdicts.sh passes only if +-- Idris2 refuses this module, and only at the declaration `invalid`. Every +-- other declaration must typecheck, so that the refusal is for the stated +-- reason and not for a missing import or a typo. +-- +-- P2: the verdict of a receipt is the gate's answer. A still_present row claimed as a success is audit_only; a receipt that credits it cannot be built. +-- +-- EXPECT: Mismatch between: AuditOnly and CreditedSuccess. + +module ReceiptP2VerdictIsNotTheGate + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP2VerdictIsNotTheGate.noBody (\e => absurd (ReceiptP2VerdictIsNotTheGate.notVerified e)) + + +stillPresentNotVerified : Not (QStillPresent = QVerified) +stillPresentNotVerified Refl impossible + +invalid : Receipt +invalid = MkReceipt 1 [] QStillPresent CSuccess CreditedSuccess Nothing [] ReceiptP2VerdictIsNotTheGate.noBody + (missing ReceiptP2VerdictIsNotTheGate.noBody) (Right Refl) + (\e => absurd (ReceiptP2VerdictIsNotTheGate.stillPresentNotVerified e)) Refl diff --git a/tests/reject/ReceiptP2VerifiedWithoutObservations.idr b/tests/reject/ReceiptP2VerifiedWithoutObservations.idr new file mode 100644 index 00000000..170530ad --- /dev/null +++ b/tests/reject/ReceiptP2VerifiedWithoutObservations.idr @@ -0,0 +1,35 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- EXPECTED REJECTION (E0-10). scripts/check-verdicts.sh passes only if +-- Idris2 refuses this module, and only at the declaration `invalid`. Every +-- other declaration must typecheck, so that the refusal is for the stated +-- reason and not for a missing import or a typo. +-- +-- P2: a verified receipt needs an observation. One with none cannot be built. +-- +-- EXPECT: Mismatch between: ?x :: ?xs and []. + +module ReceiptP2VerifiedWithoutObservations + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP2VerifiedWithoutObservations.noBody (\e => absurd (ReceiptP2VerifiedWithoutObservations.notVerified e)) + + +invalid : Receipt +invalid = credit 1 QVerified CSuccess (Just 7) [] ReceiptP2VerifiedWithoutObservations.noBody (\_ => (ItIsJust, IsNonEmpty)) diff --git a/tests/reject/ReceiptP3RevisionDropsHistory.idr b/tests/reject/ReceiptP3RevisionDropsHistory.idr new file mode 100644 index 00000000..829eb2b7 --- /dev/null +++ b/tests/reject/ReceiptP3RevisionDropsHistory.idr @@ -0,0 +1,45 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- EXPECTED REJECTION (E0-10). scripts/check-verdicts.sh passes only if +-- Idris2 refuses this module, and only at the declaration `invalid`. Every +-- other declaration must typecheck, so that the refusal is for the stated +-- reason and not for a missing import or a typo. +-- +-- P3: a revision appended to a ledger keeps every receipt of it. Claiming that the ledger after the revision is only the revision must not typecheck. +-- +-- EXPECT: Mismatch between: [] and [original]. + +module ReceiptP3RevisionDropsHistory + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP3RevisionDropsHistory.noBody (\e => absurd (ReceiptP3RevisionDropsHistory.notVerified e)) + + +extra : Body +extra HeadSha = Just 5 +extra _ = Nothing + +original : Receipt +original = failedReceipt 1 + +revised : Receipt +revised = reviseFill ReceiptP3RevisionDropsHistory.original 2 ReceiptP3RevisionDropsHistory.extra + +invalid : append ReceiptP3RevisionDropsHistory.revised [ReceiptP3RevisionDropsHistory.original] = Right [ReceiptP3RevisionDropsHistory.revised] +invalid = Refl diff --git a/tests/reject/ReceiptP4FillOverwrites.idr b/tests/reject/ReceiptP4FillOverwrites.idr new file mode 100644 index 00000000..3c8992e7 --- /dev/null +++ b/tests/reject/ReceiptP4FillOverwrites.idr @@ -0,0 +1,43 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- EXPECTED REJECTION (E0-10). scripts/check-verdicts.sh passes only if +-- Idris2 refuses this module, and only at the declaration `invalid`. Every +-- other declaration must typecheck, so that the refusal is for the stated +-- reason and not for a missing import or a typo. +-- +-- P4: a fill never overwrites a present field. Claiming that the fill replaced after_hits Z by S Z must not typecheck. +-- +-- EXPECT: Mismatch between: 1 and 0. + +module ReceiptP4FillOverwrites + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP4FillOverwrites.noBody (\e => absurd (ReceiptP4FillOverwrites.notVerified e)) + + +old : Body +old AfterHits = Just Z +old _ = Nothing + +extra : Body +extra AfterHits = Just (S Z) +extra _ = Nothing + +invalid : fillBody ReceiptP4FillOverwrites.old ReceiptP4FillOverwrites.extra AfterHits = Just (S Z) +invalid = Refl diff --git a/tests/reject/ReceiptP5MissingOmitsAGap.idr b/tests/reject/ReceiptP5MissingOmitsAGap.idr new file mode 100644 index 00000000..25661372 --- /dev/null +++ b/tests/reject/ReceiptP5MissingOmitsAGap.idr @@ -0,0 +1,36 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- EXPECTED REJECTION (E0-10). scripts/check-verdicts.sh passes only if +-- Idris2 refuses this module, and only at the declaration `invalid`. Every +-- other declaration must typecheck, so that the refusal is for the stated +-- reason and not for a missing import or a typo. +-- +-- P5: missing_evidence is exact. A receipt whose body has gaps and whose missing_evidence is empty cannot be built. +-- +-- EXPECT: Mismatch between: AfterHits :: missingOf noBody + +module ReceiptP5MissingOmitsAGap + +import Data.List +import Data.List.Elem +import Data.Maybe +import Hypatia.ABI.Receipt + +%default total +%unbound_implicits off + +noBody : Body +noBody _ = Nothing + +notVerified : Not (QFailed = QVerified) +notVerified Refl impossible + +-- A first receipt of a failed row: not `verified`, so no evidence is demanded. +failedReceipt : Nat -> Receipt +failedReceipt n = credit n QFailed CFailure Nothing [] ReceiptP5MissingOmitsAGap.noBody (\e => absurd (ReceiptP5MissingOmitsAGap.notVerified e)) + + +invalid : Receipt +invalid = MkReceipt 1 [] QFailed CFailure CreditedFailure Nothing [] ReceiptP5MissingOmitsAGap.noBody [] (Right Refl) + (\e => absurd (ReceiptP5MissingOmitsAGap.notVerified e)) Refl diff --git a/verification/PROOF-STATUS.adoc b/verification/PROOF-STATUS.adoc index 09fd9153..43b66143 100644 --- a/verification/PROOF-STATUS.adoc +++ b/verification/PROOF-STATUS.adoc @@ -60,7 +60,7 @@ receipts (`+scripts/proof-ledger.sh derive+`) and fails on an overclaim or a stale underclaim. Checked against PROOF-POLICY as pinned by `+metadatastician/standards 3-practice/PROOF-POLICY.adoc b8f60511e76c9015d86990317162dce653c92fe1+`. -*Census:* 27 proven of 47; 0 proven-with-postulates, 11 tested-only, 2 argued, 7 open. Theory rows: 3 (PWG-1 0, PWG-2ii 0, PWG-2i 0, PWG-3 1, ungraded 2). +*Census:* 33 proven of 53; 0 proven-with-postulates, 11 tested-only, 2 argued, 7 open. Theory rows: 3 (PWG-1 0, PWG-2ii 0, PWG-2i 0, PWG-3 1, ungraded 2). [cols="3,1,2,2,2",options="header"] |=== @@ -347,6 +347,42 @@ Checked against PROOF-POLICY as pinned by `+metadatastician/standards 3-practice |Agda 2.8.0.2, builtins only, --safe --without-K --cubical-compatible (--double-check in the file) |`+verification/proofs/agda/E0ImportInstance.agda+`: `+first-pass+`, `+second-pass+`, `+twice+`, `+failed+`, `+retried+` |One concrete instance with small ids; not a claim about the real id function + +|P1 of the E0 receipt design: appending a receipt whose event_id is already in the ledger is refused and leaves the ledger unchanged; appending one whose id is not in it succeeds; a ledger of distinct event_ids stays one +|proven +|Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total) +|`+src/Hypatia/ABI/Receipt.idr+`: `+appendRefusesDuplicate+`, `+appendFresh+`, `+appendKeepsUnique+`, `+decElem+`, `+decNat+` +|Over the Idris2 types. An event_id is a natural number with a structural decidable equality; the real ids are ADR-008 strings. The run time is held to the append by test/receipt_model_mirror_test.exs, not proved: Receipt.write writes nothing and returns ok where the model answers Left DuplicateEventId (the ledger is unchanged in both). Concurrent writers and the file system are outside the model + +|P2: the verdict of a receipt is the answer of the gate for its qualification and claimed outcome, or a withdrawal that names a parent; a verified receipt has a row digest and at least one observation; a receipt that credits a success is evidenced; the gate never answers withdrawn and credits a success only for a verified, claimed success +|proven +|Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total) +|`+src/Hypatia/ABI/Receipt.idr+`: `+verdictIsGate+`, `+verifiedHasEvidence+`, `+noVerifiedWithoutObservations+`, `+creditedSuccessIsEvidenced+`, `+withdrawnHasParent+`, `+gateNeverWithdrawn+`, `+gateSuccessInverse+` +|Over the Idris2 types. The model cannot build a verified receipt without an observation, but Receipt.build/2 does not refuse one: the Nickel contract of schema/receipt.ncl does, and the production entry points never make one (the mirror test runs every fleet classification and the rescan path; it pins the build/2 difference as a known difference). Whether the real gate computes the table is checked by the mirror test and by tests/accept/ReceiptP2GateTable.idr, not proved + +|The gate table of the receipt model has the 24 entries that verdict_for gives in schema/receipt.ncl, which is the one-row case of OutcomeTracker.qualified_outcome_counts/1 +|proven +|Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total) +|`+src/Hypatia/ABI/Receipt.idr+`: `+gate+` +|A finite table, pinned by tests/accept/ReceiptP2GateTable.idr (24 equations) and compared with the emitter by test/receipt_model_mirror_test.exs, which reads the table from this file. Idris2 checks the equations; it does not show that the Elixir gate computes the table + +|P3: appending a receipt, including a revision that names the receipt it revises, keeps every receipt of the ledger before it; a revision keeps the qualification, claimed outcome and verdict of the receipt it revises and names it as its parent +|proven +|Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total) +|`+src/Hypatia/ABI/Receipt.idr+`: `+appendKeepsHistory+`, `+reviseKeepsHistory+`, `+reviseKeepsClaim+`, `+reviseFill+` +|Over the Idris2 types only. No run-time code builds a revision, a fill or a withdrawal yet (E0-07), so the mirror test has nothing to hold for P3. A withdrawal is modelled as a revision (an appended receipt), by event_id; retraction by position (Retraction.idr) and by name (the run time) is not proved here. Idempotence and order-independence of a withdrawal are not claimed + +|P4: a gap-filling revision keeps every present field, changes a field only if it was in missing_evidence, and every value it holds is the old one or one that came from the filler into a gap +|proven +|Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total) +|`+src/Hypatia/ABI/Receipt.idr+`: `+fillNeverOverwrites+`, `+fillChangesOnlyGaps+`, `+fillValueIsFromExtra+`, `+reviseNeverOverwrites+`, `+fillBody+` +|Over the Idris2 types only. Field values are natural numbers. No run-time code builds a fill yet (E0-07), so P4 has no run-time counterpart and the mirror test does not cover it + +|P5: a field is named in missing_evidence exactly when it is absent, over the 14 names of the closed set; the set is empty exactly when every field is present; a receipt cannot be built with a missing_evidence that differs from the gaps of its body +|proven +|Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total) +|`+src/Hypatia/ABI/Receipt.idr+`: `+missingIff+`, `+missingEmptyIff+`, `+receiptMissingExact+`, `+fieldListed+`, `+allFields+` +|Over the Idris2 types. Order and absence of duplicates in missing_evidence are not proved (the Nickel contract and the mirror test check them). At E0 the set is never empty at run time, because subject_identity has no source yet (issue 984, E1), so the empty case is a property of the model that is not reached. The mirror test reads the 14 names from this file and from the contract and compares them |=== // END GENERATED: proof ledger diff --git a/verification/proof-ledger.jsonl b/verification/proof-ledger.jsonl index 58f5ac79..fca993a6 100644 --- a/verification/proof-ledger.jsonl +++ b/verification/proof-ledger.jsonl @@ -45,3 +45,9 @@ {"axioms":[],"bounds":"","checker":"Agda 2.8.0.2, builtins only, --safe --without-K --cubical-compatible (--double-check in the file)","file":"verification/proofs/agda/E0ModelTables.agda","id":"e0-model-tables","kind":"engineering","lane":"agda","names":["gateAgrees","fleetAgrees","stageAgrees"],"obligation":"The Agda model of the gate, the fleet classifier and the stage and tier gives the same answer as the running Elixir on every row of a generated table: 124 gate rows, 1033 fleet classification rows and 121 stage rows","status":"proven","trust_boundary":"A finite table, not a refinement proof: inputs outside it are not covered. The table is generated from the running Elixir by test/e0_agda_mirror_test.exs, which fails when the committed file is stale; Agda checks the model against the table, and the ExUnit test, not Agda, ties the table to the code"} {"axioms":[],"bounds":"","checker":"Agda 2.8.0.2, builtins only, --safe --without-K --cubical-compatible (--double-check in the file)","file":"verification/proofs/agda/E0Agreement.agda","id":"e0-agreement-checkers","kind":"engineering","lane":"agda","names":["eqOutcome-sound","eqVerification-sound","eqBucket-sound","eqFleet-sound","eqStage-sound","eqTier-sound","checkGate-sound","checkFleet-sound","checkStage-sound"],"obligation":"The equality functions on the finite types of the E0 model are sound, so that the table check of e0-model-tables cannot pass by accident","status":"proven","trust_boundary":"Equality on enumerated finite types only"} {"axioms":[],"bounds":"","checker":"Agda 2.8.0.2, builtins only, --safe --without-K --cubical-compatible (--double-check in the file)","file":"verification/proofs/agda/E0ImportInstance.agda","id":"e0-import-instance","kind":"engineering","lane":"agda","names":["first-pass","second-pass","twice","failed","retried"],"obligation":"The import model is instantiated with natural-number ids, so its parameter and hypotheses are satisfiable and its theorems apply to a concrete log (non-vacuity)","status":"proven","trust_boundary":"One concrete instance with small ids; not a claim about the real id function"} +{"axioms":[],"bounds":"","checker":"Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total)","file":"src/Hypatia/ABI/Receipt.idr","id":"abi-receipt-p1-unique-event-id","kind":"engineering","lane":"idris2","names":["appendRefusesDuplicate","appendFresh","appendKeepsUnique","decElem","decNat"],"obligation":"P1 of the E0 receipt design: appending a receipt whose event_id is already in the ledger is refused and leaves the ledger unchanged; appending one whose id is not in it succeeds; a ledger of distinct event_ids stays one","status":"proven","trust_boundary":"Over the Idris2 types. An event_id is a natural number with a structural decidable equality; the real ids are ADR-008 strings. The run time is held to the append by test/receipt_model_mirror_test.exs, not proved: Receipt.write writes nothing and returns ok where the model answers Left DuplicateEventId (the ledger is unchanged in both). Concurrent writers and the file system are outside the model"} +{"axioms":[],"bounds":"","checker":"Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total)","file":"src/Hypatia/ABI/Receipt.idr","id":"abi-receipt-p2-no-claim-beyond-evidence","kind":"engineering","lane":"idris2","names":["verdictIsGate","verifiedHasEvidence","noVerifiedWithoutObservations","creditedSuccessIsEvidenced","withdrawnHasParent","gateNeverWithdrawn","gateSuccessInverse"],"obligation":"P2: the verdict of a receipt is the answer of the gate for its qualification and claimed outcome, or a withdrawal that names a parent; a verified receipt has a row digest and at least one observation; a receipt that credits a success is evidenced; the gate never answers withdrawn and credits a success only for a verified, claimed success","status":"proven","trust_boundary":"Over the Idris2 types. The model cannot build a verified receipt without an observation, but Receipt.build/2 does not refuse one: the Nickel contract of schema/receipt.ncl does, and the production entry points never make one (the mirror test runs every fleet classification and the rescan path; it pins the build/2 difference as a known difference). Whether the real gate computes the table is checked by the mirror test and by tests/accept/ReceiptP2GateTable.idr, not proved"} +{"axioms":[],"bounds":"","checker":"Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total)","file":"src/Hypatia/ABI/Receipt.idr","id":"abi-receipt-gate-table","kind":"engineering","lane":"idris2","names":["gate"],"obligation":"The gate table of the receipt model has the 24 entries that verdict_for gives in schema/receipt.ncl, which is the one-row case of OutcomeTracker.qualified_outcome_counts/1","status":"proven","trust_boundary":"A finite table, pinned by tests/accept/ReceiptP2GateTable.idr (24 equations) and compared with the emitter by test/receipt_model_mirror_test.exs, which reads the table from this file. Idris2 checks the equations; it does not show that the Elixir gate computes the table"} +{"axioms":[],"bounds":"","checker":"Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total)","file":"src/Hypatia/ABI/Receipt.idr","id":"abi-receipt-p3-revision-keeps-history","kind":"engineering","lane":"idris2","names":["appendKeepsHistory","reviseKeepsHistory","reviseKeepsClaim","reviseFill"],"obligation":"P3: appending a receipt, including a revision that names the receipt it revises, keeps every receipt of the ledger before it; a revision keeps the qualification, claimed outcome and verdict of the receipt it revises and names it as its parent","status":"proven","trust_boundary":"Over the Idris2 types only. No run-time code builds a revision, a fill or a withdrawal yet (E0-07), so the mirror test has nothing to hold for P3. A withdrawal is modelled as a revision (an appended receipt), by event_id; retraction by position (Retraction.idr) and by name (the run time) is not proved here. Idempotence and order-independence of a withdrawal are not claimed"} +{"axioms":[],"bounds":"","checker":"Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total)","file":"src/Hypatia/ABI/Receipt.idr","id":"abi-receipt-p4-fill-never-overwrites","kind":"engineering","lane":"idris2","names":["fillNeverOverwrites","fillChangesOnlyGaps","fillValueIsFromExtra","reviseNeverOverwrites","fillBody"],"obligation":"P4: a gap-filling revision keeps every present field, changes a field only if it was in missing_evidence, and every value it holds is the old one or one that came from the filler into a gap","status":"proven","trust_boundary":"Over the Idris2 types only. Field values are natural numbers. No run-time code builds a fill yet (E0-07), so P4 has no run-time counterpart and the mirror test does not cover it"} +{"axioms":[],"bounds":"","checker":"Idris2 0.7.0, idris2 --build src/abi/hypatia-abi.ipkg (--total)","file":"src/Hypatia/ABI/Receipt.idr","id":"abi-receipt-p5-missing-evidence-exact","kind":"engineering","lane":"idris2","names":["missingIff","missingEmptyIff","receiptMissingExact","fieldListed","allFields"],"obligation":"P5: a field is named in missing_evidence exactly when it is absent, over the 14 names of the closed set; the set is empty exactly when every field is present; a receipt cannot be built with a missing_evidence that differs from the gaps of its body","status":"proven","trust_boundary":"Over the Idris2 types. Order and absence of duplicates in missing_evidence are not proved (the Nickel contract and the mirror test check them). At E0 the set is never empty at run time, because subject_identity has no source yet (issue 984, E1), so the empty case is a property of the model that is not reached. The mirror test reads the 14 names from this file and from the contract and compares them"}