diff --git a/.github/workflows/oracle-tla.yml b/.github/workflows/oracle-tla.yml new file mode 100644 index 0000000..f325cd4 --- /dev/null +++ b/.github/workflows/oracle-tla.yml @@ -0,0 +1,22 @@ +name: Oracle TLA verification +on: + push: + branches: [main] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: oracle-tla-main + cancel-in-progress: true +jobs: + tlc: + if: github.repository == 'sloik/FunctionalAPI' && github.ref == 'refs/heads/main' + runs-on: [self-hosted, Linux, ARM64, oracle, swift-tla, FunctionalAPI] + timeout-minutes: 15 + steps: + - name: Checkout default-branch revision + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Model-check TLA+ specs (models must pass, mutants must fail) + run: formal/run_tlc.sh diff --git a/formal/FunctionalAPILaws.cfg b/formal/FunctionalAPILaws.cfg new file mode 100644 index 0000000..873e7aa --- /dev/null +++ b/formal/FunctionalAPILaws.cfg @@ -0,0 +1,3 @@ +CONSTANTS Vals = {0, 1} Mutant = "none" +SPECIFICATION Spec +INVARIANTS TypeOK ComposeOrder ComposeAssociative ComposeIdentity CurryUncurryRoundTrip UncurryCurryRoundTrip CurryApplication FlipSwapsArguments FlipInvolution PartialApplication PartialIsCurry ThunkReturnsValue IdentityIsNeutral ForwardApplicationIsCall ForwardCompositionIsCompose KeyPathProjection FunctorialMapMatchesFreeMap ArrayFunctorLaws ArrayFlatMapLaws CompactMapDropsNil CompactMapOfTotalIsMap ResultMapLaws PhantomProcess diff --git a/formal/FunctionalAPILaws.compose_swapped.cfg b/formal/FunctionalAPILaws.compose_swapped.cfg new file mode 100644 index 0000000..a36b3b7 --- /dev/null +++ b/formal/FunctionalAPILaws.compose_swapped.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: ComposeOrder +CONSTANTS Vals = {0, 1} Mutant = "compose_swapped" +SPECIFICATION Spec +INVARIANTS TypeOK ComposeOrder diff --git a/formal/FunctionalAPILaws.flip_noop.cfg b/formal/FunctionalAPILaws.flip_noop.cfg new file mode 100644 index 0000000..3442416 --- /dev/null +++ b/formal/FunctionalAPILaws.flip_noop.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: FlipSwapsArguments +CONSTANTS Vals = {0, 1} Mutant = "flip_noop" +SPECIFICATION Spec +INVARIANTS TypeOK FlipSwapsArguments diff --git a/formal/FunctionalAPILaws.tla b/formal/FunctionalAPILaws.tla new file mode 100644 index 0000000..bb4d062 --- /dev/null +++ b/formal/FunctionalAPILaws.tla @@ -0,0 +1,111 @@ +------------------------- MODULE FunctionalAPILaws ------------------------- +(* Finite model of Sources/FunctionalAPI: compose / curry / uncurry / flip *) +(* / partial / thunk / identity, the operators |>, >>>, <^>, ^keyPath, *) +(* the free map/flatMap/compactMap on arrays and map on Result, and the *) +(* Phantom wrapper. Values range over Vals; functions over the full *) +(* finite function space, so each law holds for every closure. *) +(* Abstractions: arrays are sequences of length <= 2; a KeyPath is a *) +(* field selector on a two-field record; Result is success(v)/failure(e) *) +(* with a single abstract error; Optional is None / Some(v). *) +EXTENDS Naturals, Sequences + +CONSTANTS Vals, \* carrier for values + Mutant \* "none" for the real semantics, otherwise a seeded bug + +None_ == [tag |-> "none"] +Some(v) == [tag |-> "some", v |-> v] +Opts == {None_} \cup {Some(v) : v \in Vals} +Fns == [Vals -> Vals] +Fns2 == [Vals \X Vals -> Vals] +Id == [x \in Vals |-> x] + +\* FunctionsCombinators.swift +Compose(f, g) == \* compose(f, g) = g after f + IF Mutant = "compose_swapped" THEN [x \in Vals |-> f[g[x]]] + ELSE [x \in Vals |-> g[f[x]]] +Curry(f) == [a \in Vals |-> [b \in Vals |-> f[a, b]]] +Uncurry(h) == [t \in Vals \X Vals |-> h[t[1]][t[2]]] +Flip(f) == IF Mutant = "flip_noop" THEN f + ELSE [t \in Vals \X Vals |-> f[t[2], t[1]]] +Thunk(a) == [u \in {0} |-> a] +Partial2(f, a) == [b \in Vals |-> f[a, b]] +Fwd(x, f) == f[x] \* x |> f +Fcomp(f, g) == [x \in Vals |-> g[f[x]]] \* f >>> g +Proj1 == [r \in Vals \X Vals |-> r[1]] \* ^\.first +Proj2 == [r \in Vals \X Vals |-> r[2]] \* ^\.second + +\* FreeMaps.swift on arrays +Seqs == {<<>>} \cup {<> : x \in Vals} \cup {<> : x, y \in Vals} +SMap(s, f) == [i \in 1..Len(s) |-> f[s[i]]] +RECURSIVE SFlatMap(_, _) +SFlatMap(s, k) == IF s = <<>> THEN <<>> ELSE k[Head(s)] \o SFlatMap(Tail(s), k) +\* Optional-returning functions. +OptFns == [Vals -> Opts] +RECURSIVE SCompact(_, _) +SCompact(s, g) == + IF s = <<>> THEN <<>> + ELSE (IF g[Head(s)].tag = "none" THEN <<>> ELSE <>) \o SCompact(Tail(s), g) +\* <^> on Optional and Result +OMap(o, f) == IF o.tag = "none" THEN o ELSE Some(f[o.v]) +RMap(r, f) == IF r.tag = "success" THEN [tag |-> "success", v |-> f[r.v]] ELSE r +Results == {[tag |-> "success", v |-> x] : x \in Vals} \cup {[tag |-> "failure", v |-> 0]} + +\* Phantom.swift: a witness tag plus the wrapped value; process applies transform. +Phantoms == [w : {"A", "B"}, v : Vals] +Retag(w) == [p \in Phantoms |-> [w |-> w, v |-> p.v]] +Process(p, t) == t[p] + +VARIABLES x, y, s, r, p +vars == <> +Init == /\ x \in Vals /\ y \in Vals /\ s \in Seqs /\ r \in Results /\ p \in Phantoms +Next == UNCHANGED vars +Spec == Init /\ [][Next]_vars + +TypeOK == x \in Vals /\ y \in Vals /\ s \in Seqs /\ r \in Results /\ p \in Phantoms + +ComposeOrder == \A f, g \in Fns : Compose(f, g)[x] = g[f[x]] +ComposeAssociative == + \A f, g, h \in Fns : Compose(Compose(f, g), h) = Compose(f, Compose(g, h)) +ComposeIdentity == \A f \in Fns : Compose(Id, f) = f /\ Compose(f, Id) = f +CurryUncurryRoundTrip == + \A f \in Fns2 : Uncurry(Curry(f)) = f +UncurryCurryRoundTrip == + \A f \in Fns2 : Curry(Uncurry(Curry(f))) = Curry(f) +CurryApplication == \A f \in Fns2 : Curry(f)[x][y] = f[x, y] +FlipSwapsArguments == \A f \in Fns2 : Flip(f)[y, x] = f[x, y] +FlipInvolution == \A f \in Fns2 : Flip(Flip(f)) = f +PartialApplication == \A f \in Fns2 : Partial2(f, x)[y] = f[x, y] +PartialIsCurry == \A f \in Fns2 : Partial2(f, x) = Curry(f)[x] +ThunkReturnsValue == Thunk(x)[0] = x +IdentityIsNeutral == Id[x] = x +\* Operators promise to equal the plain functions they sugar. +ForwardApplicationIsCall == \A f \in Fns : Fwd(x, f) = f[x] +ForwardCompositionIsCompose == + \A f, g \in Fns : Fcomp(f, g) = Compose(f, g) /\ Fwd(x, Fcomp(f, g)) = Fwd(Fwd(x, f), g) +KeyPathProjection == + Proj1[<>] = x /\ Proj2[<>] = y +FunctorialMapMatchesFreeMap == \* <^> on [A] is map, on A? is Optional.map + /\ \A f \in Fns : SMap(s, f) = [i \in 1..Len(s) |-> f[s[i]]] + /\ \A f \in Fns : Len(SMap(s, f)) = Len(s) + /\ \A f \in Fns : OMap(Some(x), f) = Some(f[x]) /\ OMap(None_, f) = None_ +ArrayFunctorLaws == + /\ SMap(s, Id) = s + /\ \A f, g \in Fns : SMap(s, Compose(f, g)) = SMap(SMap(s, f), g) +ArrayFlatMapLaws == + /\ \A k \in [Vals -> Seqs] : SFlatMap(<>, k) = k[x] + /\ SFlatMap(s, [v \in Vals |-> <>]) = s + /\ \A f \in Fns : SMap(s, f) = SFlatMap(s, [v \in Vals |-> <>]) +CompactMapDropsNil == + \A g \in OptFns : + /\ Len(SCompact(s, g)) <= Len(s) + /\ \A i \in 1..Len(SCompact(s, g)) : SCompact(s, g)[i] \in Vals +CompactMapOfTotalIsMap == + \A f \in Fns : SCompact(s, [v \in Vals |-> Some(f[v])]) = SMap(s, f) +ResultMapLaws == + /\ RMap(r, Id) = r + /\ r.tag = "failure" => \A f \in Fns : RMap(r, f) = r + /\ \A f, g \in Fns : RMap(r, Compose(f, g)) = RMap(RMap(r, f), g) +PhantomProcess == + /\ \A w \in {"A", "B"} : Process(p, Retag(w)).v = p.v /\ Process(p, Retag(w)).w = w + /\ Process(Process(p, Retag("A")), Retag("B")) = Process(p, Retag("B")) +============================================================================= diff --git a/formal/README.md b/formal/README.md new file mode 100644 index 0000000..3506d34 --- /dev/null +++ b/formal/README.md @@ -0,0 +1,59 @@ +# Formal model (TLA+) + +`FunctionalAPILaws.tla` is a finite TLA+ model of the public semantics of `Sources/FunctionalAPI`. +TLC checks every law over a carrier `Vals = {0, 1}` and **every** function in the finite function +space, so each law holds for all closures, not just hand-picked ones. + +| Invariant | Swift API it abstracts | +|---|---| +| `TypeOK` | domain of the model variables | +| `ComposeOrder`, `ComposeAssociative`, `ComposeIdentity` | `compose(f, g)` applies `f` then `g`; with `identity` it is a monoid | +| `CurryUncurryRoundTrip`, `UncurryCurryRoundTrip`, `CurryApplication` | `curry`, `uncurry` | +| `FlipSwapsArguments`, `FlipInvolution` | `flip` | +| `PartialApplication`, `PartialIsCurry` | `partial(f, a)` equals `curry(f)(a)` | +| `ThunkReturnsValue`, `IdentityIsNeutral` | `thunk`, `identity` | +| `ForwardApplicationIsCall` | `x \|> f == f(x)` | +| `ForwardCompositionIsCompose` | `f >>> g == compose(f, g)` | +| `KeyPathProjection` | prefix `^` turns a KeyPath into a projection function | +| `FunctorialMapMatchesFreeMap`, `ArrayFunctorLaws` | `<^>` on `[A]` and `A?` is `map`; functor identity and composition | +| `ArrayFlatMapLaws` | free `flatMap` on arrays (monad laws, `map` via `flatMap`) | +| `CompactMapDropsNil`, `CompactMapOfTotalIsMap` | free `compactMap` | +| `ResultMapLaws` | free `map` / `<^>` on `Result` | +| `PhantomProcess` | `Phantom.process` applies the transform and keeps the wrapped value | + +## Abstractions + +- Arrays are sequences of length at most 2; a KeyPath is a field selector on a pair; `Result` + has one abstract error (`failure`); `Optional` is a `none`/`some` record. +- `zurry`, `nop` and the DEBUG-only `developmentValue`/`temporayValue` are not modelled + (`zurry` is internal, `nop` has no observable result, `temporayValue` traps). +- Only arities that exist in the code are modelled for `curry`, `partial`, `flip` (2 arguments); + `partial` is modelled for the 2-argument form, whose 3-argument form is the same pattern. +- The generic `A <^> f` overload (plain application) is not modelled; Swift overload resolution + chooses the more specific array/optional/result/either overloads for those types. + +## Non-vacuity + +Each `FunctionalAPILaws..cfg` seeds one bug through the `Mutant` constant and names +the invariant that must catch it (`\* EXPECT_VIOLATION: ...`): + +- `compose_swapped`: `compose` applies `g` before `f` (caught by `ComposeOrder`). +- `flip_noop`: `flip` returns its argument unchanged (caught by `FlipSwapsArguments`). + +`run_tlc.sh` fails if a mutant passes. + +## Running + +```sh +TLA_JAR=/path/to/tla2tools-1.7.4.jar formal/run_tlc.sh # needs Java 11+ +``` + +The script checks the jar's SHA-256 against the pinned tla2tools 1.7.4. CI runs it on a +self-hosted Oracle ARM64 runner, only on pushes to the default branch or by manual dispatch +(`.github/workflows/oracle-tla.yml`). The Swift build and tests stay on hosted macOS. + +## Limits + +The model describes the *intended* semantics, read by hand from the Swift sources. It does not +prove the Swift code conforms; the XCTest suite covers the code. If the Swift behaviour +changes, update the model in the same PR. diff --git a/formal/run_tlc.sh b/formal/run_tlc.sh new file mode 100755 index 0000000..ec6f4d9 --- /dev/null +++ b/formal/run_tlc.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Runs every TLA+ model in formal/ with TLC. +# formal/.cfg must pass with no error. +# formal/..cfg is a mutant: it must contain a line +# "\* EXPECT_VIOLATION: " +# and TLC must report exactly that invariant as violated. +# A mutant that passes, or fails for another reason, fails this script (non-vacuity). +# Env: TLA_JAR (default /opt/tla/tla2tools-1.7.4.jar), JAVA (default java). +set -euo pipefail +cd "$(dirname "$0")" +JAR="${TLA_JAR:-/opt/tla/tla2tools-1.7.4.jar}" +JAVA="${JAVA:-java}" +PINNED_SHA="936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88" +actual_sha="$( (sha256sum "$JAR" 2>/dev/null || shasum -a 256 "$JAR") | cut -d' ' -f1)" +if [[ "$actual_sha" != "$PINNED_SHA" ]]; then + echo "FAIL: $JAR sha256 $actual_sha != pinned $PINNED_SHA" >&2; exit 2 +fi +meta="$(mktemp -d)"; trap 'rm -rf "$meta"' EXIT +pass=0; fail=0; shopt -s nullglob +cfgs=(*.cfg) +(( ${#cfgs[@]} > 0 )) || { echo "FAIL: no .cfg files in formal/" >&2; exit 2; } +for cfg in "${cfgs[@]}"; do + module="${cfg%%.*}" + expect="$(sed -n 's/^\\\* EXPECT_VIOLATION: *\([A-Za-z0-9_]*\).*/\1/p' "$cfg" | head -1)" + out="$("$JAVA" -XX:+UseParallelGC -cp "$JAR" tlc2.TLC -workers 1 -deadlock \ + -metadir "$meta/${cfg%.cfg}" -config "$cfg" "$module.tla" 2>&1)" && rc=0 || rc=$? + if [[ -z "$expect" ]]; then + if [[ $rc -eq 0 ]] && grep -q "No error has been found" <<<"$out"; then + echo "PASS $cfg ($(grep -o '[0-9]* distinct states found' <<<"$out" | head -1))"; pass=$((pass+1)) + else + echo "FAIL $cfg (expected no error)"; echo "$out" | tail -30; fail=$((fail+1)) + fi + else + if [[ $rc -ne 0 ]] && grep -q "Invariant $expect is violated" <<<"$out"; then + echo "PASS $cfg (mutant caught by $expect)"; pass=$((pass+1)) + else + echo "FAIL $cfg (mutant expected to violate $expect)"; echo "$out" | tail -30; fail=$((fail+1)) + fi + fi +done +echo "TLC summary: $pass passed, $fail failed" +[[ $fail -eq 0 ]]