diff --git a/.github/workflows/oracle-tla.yml b/.github/workflows/oracle-tla.yml new file mode 100644 index 0000000..7af720f --- /dev/null +++ b/.github/workflows/oracle-tla.yml @@ -0,0 +1,22 @@ +name: Oracle TLA verification +on: + push: + branches: [master] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: oracle-tla-master + cancel-in-progress: true +jobs: + tlc: + if: github.repository == 'sloik/OptionalAPI' && github.ref == 'refs/heads/master' + runs-on: [self-hosted, Linux, ARM64, oracle, swift-tla, OptionalAPI] + 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/OptionalCoreLaws.ap_ignores_none_value.cfg b/formal/OptionalCoreLaws.ap_ignores_none_value.cfg new file mode 100644 index 0000000..8cd97c0 --- /dev/null +++ b/formal/OptionalCoreLaws.ap_ignores_none_value.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: ApNoneValue +CONSTANTS Vals = {0, 1} Mutant = "ap_ignores_none_value" +SPECIFICATION Spec +INVARIANTS TypeOK ApNoneValue diff --git a/formal/OptionalCoreLaws.async_fold_wrong_none_case.cfg b/formal/OptionalCoreLaws.async_fold_wrong_none_case.cfg new file mode 100644 index 0000000..4e2970a --- /dev/null +++ b/formal/OptionalCoreLaws.async_fold_wrong_none_case.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: AsyncAgreesWithSync +CONSTANTS Vals = {0, 1} Mutant = "async_fold_wrong_none_case" +SPECIFICATION Spec +INVARIANTS TypeOK AsyncAgreesWithSync diff --git a/formal/OptionalCoreLaws.cast_ignores_type.cfg b/formal/OptionalCoreLaws.cast_ignores_type.cfg new file mode 100644 index 0000000..0992e06 --- /dev/null +++ b/formal/OptionalCoreLaws.cast_ignores_type.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: CastOtherTypeIsNone +CONSTANTS Vals = {0, 1} Mutant = "cast_ignores_type" +SPECIFICATION Spec +INVARIANTS TypeOK CastOtherTypeIsNone diff --git a/formal/OptionalCoreLaws.cfg b/formal/OptionalCoreLaws.cfg new file mode 100644 index 0000000..ec6ccd1 --- /dev/null +++ b/formal/OptionalCoreLaws.cfg @@ -0,0 +1,3 @@ +CONSTANTS Vals = {0, 1} Mutant = "none" +SPECIFICATION Spec +INVARIANTS TypeOK PropertiesAreComplements MapIdentity MapComposition MonadLeftIdentity MonadRightIdentity MonadAssociativity AndThenNoneAbsorbs AsyncAgreesWithSync ApSomeSome ApNoneValue ApNoneFunction ApIsMap ApIdentity FilterIsSubset FilterKeepsIffPredicate FilterNoneIsNone FilterIdempotent FilterFusion FilterViaFlatMap SomeWhenIsFilterOfSome NoneWhenComplementsSomeWhen FlattenCases FlattenIsFlatMapId FlattenIsJoin FlattenUnit FlattenOfNestedNone FoldCases FoldWithIdIsOr OrValue OrIsLazy OrProducerRunsOnceWhenNone MapNoneAlwaysSome MapNoneEqualsDefaultSome OrOptionalOfSomeIsMapNone OrOptionalLaws CoalesceMatchesFold CoalesceEmptyIsNone CoalesceIsFirstSome CoalesceAllNone CoalesceAgreesWithOrOptional CastSameTypeKeeps CastOtherTypeIsNone CastNoneIsNone CastResultIsSomeOnlyIfSome EncodeDecodeRoundTrip DecodeFailureIsNone diff --git a/formal/OptionalCoreLaws.coalesce_last_wins.cfg b/formal/OptionalCoreLaws.coalesce_last_wins.cfg new file mode 100644 index 0000000..8b133f4 --- /dev/null +++ b/formal/OptionalCoreLaws.coalesce_last_wins.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: CoalesceIsFirstSome +CONSTANTS Vals = {0, 1} Mutant = "coalesce_last_wins" +SPECIFICATION Spec +INVARIANTS TypeOK CoalesceIsFirstSome diff --git a/formal/OptionalCoreLaws.decode_junk_becomes_some.cfg b/formal/OptionalCoreLaws.decode_junk_becomes_some.cfg new file mode 100644 index 0000000..27a72ef --- /dev/null +++ b/formal/OptionalCoreLaws.decode_junk_becomes_some.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: DecodeFailureIsNone +CONSTANTS Vals = {0, 1} Mutant = "decode_junk_becomes_some" +SPECIFICATION Spec +INVARIANTS TypeOK DecodeFailureIsNone diff --git a/formal/OptionalCoreLaws.filter_keeps_all.cfg b/formal/OptionalCoreLaws.filter_keeps_all.cfg new file mode 100644 index 0000000..19d4bd6 --- /dev/null +++ b/formal/OptionalCoreLaws.filter_keeps_all.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: FilterKeepsIffPredicate +CONSTANTS Vals = {0, 1} Mutant = "filter_keeps_all" +SPECIFICATION Spec +INVARIANTS TypeOK FilterKeepsIffPredicate diff --git a/formal/OptionalCoreLaws.flatten_inner_none_becomes_some.cfg b/formal/OptionalCoreLaws.flatten_inner_none_becomes_some.cfg new file mode 100644 index 0000000..fd0b65e --- /dev/null +++ b/formal/OptionalCoreLaws.flatten_inner_none_becomes_some.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: FlattenCases +CONSTANTS Vals = {0, 1} Mutant = "flatten_inner_none_becomes_some" +SPECIFICATION Spec +INVARIANTS TypeOK FlattenCases diff --git a/formal/OptionalCoreLaws.nonewhen_same_as_somewhen.cfg b/formal/OptionalCoreLaws.nonewhen_same_as_somewhen.cfg new file mode 100644 index 0000000..8277de4 --- /dev/null +++ b/formal/OptionalCoreLaws.nonewhen_same_as_somewhen.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: NoneWhenComplementsSomeWhen +CONSTANTS Vals = {0, 1} Mutant = "nonewhen_same_as_somewhen" +SPECIFICATION Spec +INVARIANTS TypeOK NoneWhenComplementsSomeWhen diff --git a/formal/OptionalCoreLaws.or_eager.cfg b/formal/OptionalCoreLaws.or_eager.cfg new file mode 100644 index 0000000..8212b71 --- /dev/null +++ b/formal/OptionalCoreLaws.or_eager.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: OrIsLazy +CONSTANTS Vals = {0, 1} Mutant = "or_eager" +SPECIFICATION Spec +INVARIANTS TypeOK OrIsLazy diff --git a/formal/OptionalCoreLaws.tla b/formal/OptionalCoreLaws.tla new file mode 100644 index 0000000..85171e9 --- /dev/null +++ b/formal/OptionalCoreLaws.tla @@ -0,0 +1,222 @@ +--------------------------- MODULE OptionalCoreLaws --------------------------- +(* Finite model of Sources/OptionalAPI, part 1: the operator families map / *) +(* flatMap(andThen) / ap / filter / flatten / fold / or / mapNone / defaultSome *) +(* / orOptional / coalesce / someWhen / noneWhen / isSome-family / cast / *) +(* encode+decode, plus the async twins which are hand-written switches. *) +(* Optional is [tag, v]. Transforms range over the FULL finite function *) +(* space, so each law holds for every closure. "Producer" closures are modelled *) +(* by a call counter so laziness (autoclosure) is checkable. *) +(* Abstractions: T is Vals = {0,1}; Foundation JSON and Swift `as?` bridging are *) +(* abstracted (see README Limits). Throwing/collection/traversal: see *) +(* OptionalEffectsLaws. *) +EXTENDS Naturals, Sequences + +CONSTANTS Vals, Mutant + +None == [tag |-> "none", v |-> 0] +Some(x) == [tag |-> "some", v |-> x] +Opts == {None} \cup {Some(x) : x \in Vals} +NestedOpts == {None} \cup {Some(o) : o \in Opts} +Fns == [Vals -> Vals] +KFns == [Vals -> Opts] +Preds == [Vals -> BOOLEAN] +FOpts == {None} \cup {Some(f) : f \in Fns} +Seqs == UNION {[1..n -> Opts] : n \in 0..3} +Id == [x \in Vals |-> x] + +\* OptionalProperties.swift +IsSome(o) == o.tag = "some" +IsNone(o) == o.tag = "none" +IsNotNone(o) == o.tag = "some" +IsNotSome(o) == o.tag = "none" + +\* Optional.map / flatMap (stdlib) used throughout the library. +Map(o, f) == IF IsSome(o) THEN Some(f[o.v]) ELSE None +FlatMap(o, k) == IF IsSome(o) THEN k[o.v] ELSE None + +\* AndThen.swift +AndThen(o, k) == FlatMap(o, k) +AsyncAndThen(o, k) == IF IsSome(o) THEN k[o.v] ELSE None +AsyncMap(o, f) == IF IsSome(o) THEN Some(f[o.v]) ELSE None +AsyncFlatMap(o, k) == IF IsSome(o) THEN k[o.v] ELSE None + +\* Applicative.swift (function payloads: fo = Some(f) | None) +Ap(fo, o) == + IF IsSome(fo) + THEN (IF Mutant = "ap_ignores_none_value" THEN Some(fo.v[o.v]) + ELSE IF IsSome(o) THEN Some(fo.v[o.v]) ELSE None) + ELSE None +AsyncAp(fo, o) == + IF IsSome(fo) THEN (IF IsSome(o) THEN Some(fo.v[o.v]) ELSE None) ELSE None + +\* Filter.swift (switch map(predicate) { case true?: self; default: .none }) +Filter(o, p) == + IF Mutant = "filter_keeps_all" THEN o + ELSE IF Map(o, p) = Some(TRUE) THEN o ELSE None +AsyncFilter(o, p) == IF IsSome(o) THEN (IF p[o.v] THEN o ELSE None) ELSE None + +\* ConditionalConstruction.swift +SomeWhen(p, x) == IF p[x] THEN Some(x) ELSE None +NoneWhen(p, x) == + IF Mutant = "nonewhen_same_as_somewhen" THEN SomeWhen(p, x) + ELSE IF p[x] THEN None ELSE Some(x) + +\* Flatten.swift +Flatten(n) == + IF IsSome(n) + THEN (IF Mutant = "flatten_inner_none_becomes_some" /\ IsNone(n.v) + THEN Some(0) ELSE n.v) + ELSE None + +\* Folds.swift (map(someCase) ?? noneCase) +Fold(o, d, f) == IF IsSome(Map(o, f)) THEN Map(o, f).v ELSE d +AsyncFold(o, d, f) == + IF IsSome(o) THEN f[o.v] + ELSE IF Mutant = "async_fold_wrong_none_case" THEN f[0] ELSE d + +\* Or.swift / Maps.swift. Result paired with the number of producer calls. +Or(o, d) == + IF IsSome(o) + THEN [r |-> o.v, calls |-> IF Mutant = "or_eager" THEN 1 ELSE 0] + ELSE [r |-> d, calls |-> 1] +AsyncOr(o, d) == IF IsSome(o) THEN [r |-> o.v, calls |-> 0] ELSE [r |-> d, calls |-> 1] +MapNone(o, d) == Some(Or(o, d).r) \* also the free mapNone (calls optional.or) +DefaultSome(o, d) == Some(Or(o, d).r) \* also the free defaultSome +AsyncMapNone(o, d) == IF IsSome(o) THEN o ELSE Some(d) +AsyncDefaultSome(o, d) == IF IsSome(o) THEN o ELSE Some(d) + +\* Alternative.swift +OrOptional(o, q) == IF IsSome(o) THEN o ELSE q +RECURSIVE FoldAlt(_) +FoldAlt(s) == IF s = <<>> THEN None ELSE OrOptional(Head(s), FoldAlt(Tail(s))) +Coalesce(s) == + IF \E i \in DOMAIN s : IsSome(s[i]) + THEN s[CHOOSE i \in DOMAIN s : + IsSome(s[i]) /\ + (IF Mutant = "coalesce_last_wins" + THEN \A j \in (i + 1)..Len(s) : IsNone(s[j]) + ELSE \A j \in 1..(i - 1) : IsNone(s[j]))] + ELSE None + +\* Cast.swift: Any = [ty, v] with two dynamic types +Types == {"A", "B"} +Anys == [ty : Types, v : Vals] +OptAnys == {None} \cup {Some(a) : a \in Anys} +CastTo(a, T) == IF a.ty = T \/ Mutant = "cast_ignores_type" THEN Some(a.v) ELSE None +OptCast(oa, T) == IF IsSome(oa) THEN CastTo(oa.v, T) ELSE None + +\* OptionalCodable.swift: Data abstracted to Vals plus an undecodable token +Junk == [k |-> "junk", x |-> 0] +Datas == {[k |-> "ok", x |-> x] : x \in Vals} \cup {Junk} +OptDatas == {None} \cup {Some(d) : d \in Datas} +Encode(o) == IF IsSome(o) THEN Some([k |-> "ok", x |-> o.v]) ELSE None \* JSONEncoder abstracted +Decode(od) == + IF IsSome(od) + THEN (IF od.v.k = "junk" THEN (IF Mutant = "decode_junk_becomes_some" THEN Some(0) ELSE None) + ELSE Some(od.v.x)) + ELSE None + +VARIABLES o, p, s, oa, od +vars == <> +Init == o \in Opts /\ p \in Opts /\ s \in Seqs /\ oa \in OptAnys /\ od \in OptDatas +Next == UNCHANGED vars +Spec == Init /\ [][Next]_vars + +TypeOK == o \in Opts /\ p \in Opts /\ s \in Seqs /\ oa \in OptAnys /\ od \in OptDatas + +\* ---- properties +PropertiesAreComplements == + IsSome(o) # IsNone(o) /\ IsNotNone(o) = IsSome(o) /\ IsNotSome(o) = IsNone(o) + +\* ---- functor / monad (andThen) +MapIdentity == Map(o, Id) = o +MapComposition == + \A f, g \in Fns : Map(Map(o, f), g) = Map(o, [x \in Vals |-> g[f[x]]]) +MonadLeftIdentity == + \A k \in KFns : \A x \in Vals : AndThen(Some(x), k) = k[x] +MonadRightIdentity == AndThen(o, [x \in Vals |-> Some(x)]) = o +MonadAssociativity == + \A k1, k2 \in KFns : + AndThen(AndThen(o, k1), k2) = AndThen(o, [x \in Vals |-> AndThen(k1[x], k2)]) +AndThenNoneAbsorbs == \A k \in KFns : AndThen(None, k) = None +AsyncAgreesWithSync == + \A f \in Fns, k \in KFns, pr \in Preds, d \in Vals : + AsyncMap(o, f) = Map(o, f) /\ AsyncFlatMap(o, k) = FlatMap(o, k) + /\ AsyncAndThen(o, k) = AndThen(o, k) /\ AsyncFilter(o, pr) = Filter(o, pr) + /\ AsyncFold(o, d, f) = Fold(o, d, f) /\ AsyncOr(o, d) = Or(o, d) + /\ AsyncMapNone(o, d) = MapNone(o, d) + /\ AsyncDefaultSome(o, d) = DefaultSome(o, d) + /\ AsyncAp(Some(f), o) = Ap(Some(f), o) /\ AsyncAp(None, o) = Ap(None, o) + /\ AsyncAp(Some(f), None) = Ap(Some(f), None) + +\* ---- applicative +ApSomeSome == \A f \in Fns, x \in Vals : Ap(Some(f), Some(x)) = Some(f[x]) +ApNoneValue == \A f \in Fns : Ap(Some(f), None) = None +ApNoneFunction == Ap(None, o) = None +ApIsMap == \A f \in Fns : Ap(Some(f), o) = Map(o, f) +ApIdentity == Ap(Some(Id), o) = o + +\* ---- filter / someWhen / noneWhen +FilterIsSubset == \A pr \in Preds : Filter(o, pr) = o \/ Filter(o, pr) = None +FilterKeepsIffPredicate == + \A pr \in Preds, x \in Vals : Filter(Some(x), pr) = (IF pr[x] THEN Some(x) ELSE None) +FilterNoneIsNone == \A pr \in Preds : Filter(None, pr) = None +FilterIdempotent == \A pr \in Preds : Filter(Filter(o, pr), pr) = Filter(o, pr) +FilterFusion == + \A pr, q \in Preds : + Filter(Filter(o, pr), q) = Filter(o, [x \in Vals |-> pr[x] /\ q[x]]) +FilterViaFlatMap == + \A pr \in Preds : Filter(o, pr) = FlatMap(o, [x \in Vals |-> SomeWhen(pr, x)]) +SomeWhenIsFilterOfSome == \A pr \in Preds, x \in Vals : SomeWhen(pr, x) = Filter(Some(x), pr) +NoneWhenComplementsSomeWhen == + \A pr \in Preds, x \in Vals : + NoneWhen(pr, x) = SomeWhen([y \in Vals |-> ~pr[y]], x) + /\ (IsSome(NoneWhen(pr, x)) # IsSome(SomeWhen(pr, x))) + +\* ---- flatten +FlattenCases == + Flatten(None) = None + /\ Flatten(Some(None)) = None + /\ \A x \in Vals : Flatten(Some(Some(x))) = Some(x) +FlattenIsFlatMapId == + \A n \in NestedOpts : Flatten(n) = FlatMap(n, [x \in Opts |-> x]) +FlattenIsJoin == + \A k \in KFns : FlatMap(o, k) = Flatten(Map(o, k)) +FlattenUnit == Flatten(Map(o, [x \in Vals |-> Some(x)])) = o +FlattenOfNestedNone == \A n \in NestedOpts : IsNone(n) => Flatten(n) = None + +\* ---- fold +FoldCases == + \A d \in Vals, f \in Fns : + Fold(None, d, f) = d /\ \A x \in Vals : Fold(Some(x), d, f) = f[x] +FoldWithIdIsOr == \A d \in Vals : Fold(o, d, Id) = Or(o, d).r + +\* ---- or / mapNone / defaultSome / orOptional / coalesce +OrValue == \A d \in Vals : Or(o, d).r = (IF IsSome(o) THEN o.v ELSE d) +OrIsLazy == \A d \in Vals : IsSome(o) => Or(o, d).calls = 0 +OrProducerRunsOnceWhenNone == \A d \in Vals : IsNone(o) => Or(o, d).calls = 1 +MapNoneAlwaysSome == + \A d \in Vals : IsSome(MapNone(o, d)) /\ MapNone(MapNone(o, d), d) = MapNone(o, d) +MapNoneEqualsDefaultSome == \A d \in Vals : MapNone(o, d) = DefaultSome(o, d) +OrOptionalOfSomeIsMapNone == \A d \in Vals : OrOptional(o, Some(d)) = MapNone(o, d) +OrOptionalLaws == + OrOptional(None, p) = p /\ OrOptional(o, None) = o + /\ \A q \in Opts : OrOptional(OrOptional(o, p), q) = OrOptional(o, OrOptional(p, q)) + /\ IsSome(o) => OrOptional(o, p) = o +CoalesceMatchesFold == Coalesce(s) = FoldAlt(s) +CoalesceEmptyIsNone == Coalesce(<<>>) = None +CoalesceIsFirstSome == + \A i \in DOMAIN s : IsSome(s[i]) /\ (\A j \in 1..(i - 1) : IsNone(s[j])) => Coalesce(s) = s[i] +CoalesceAllNone == (\A i \in DOMAIN s : IsNone(s[i])) => Coalesce(s) = None +CoalesceAgreesWithOrOptional == Coalesce(<>) = OrOptional(o, p) + +\* ---- cast / codable round trips +CastSameTypeKeeps == + \A a \in Anys : OptCast(Some(a), a.ty) = Some(a.v) +CastOtherTypeIsNone == + \A a \in Anys, T \in Types : T # a.ty => OptCast(Some(a), T) = None +CastNoneIsNone == \A T \in Types : OptCast(None, T) = None +CastResultIsSomeOnlyIfSome == \A T \in Types : IsSome(OptCast(oa, T)) => IsSome(oa) +EncodeDecodeRoundTrip == Decode(Encode(o)) = o +DecodeFailureIsNone == Decode(Some(Junk)) = None /\ Decode(None) = None +============================================================================= diff --git a/formal/OptionalEffectsLaws.cfg b/formal/OptionalEffectsLaws.cfg new file mode 100644 index 0000000..3974146 --- /dev/null +++ b/formal/OptionalEffectsLaws.cfg @@ -0,0 +1,3 @@ +CONSTANTS Vals = {0, 1} Mutant = "none" +SPECIFICATION Spec +INVARIANTS TypeOK HasElementsIsNotNoneOrEmpty NoneIsNoneOrEmpty RecoverNoneStaysNone RecoverKeepsNonEmpty RecoverFillsEmpty RecoverIsLazy RecoverWithNonEmptyDefaultHasElements AsyncRecoverAgrees SequenceAllOrNothing SequencePreservesOrderAndLength SequenceEmptyIsSomeEmpty SequenceNoneIfAnyNone TraverseIsSequenceOfMap TraverseShortCircuits TraverseCallsAllWhenTotal TraverseWithSomeIsMap WhenReturnsSelf WhenSomeRunsIffSome WhenNoneRunsIffNone WhenSomeXorWhenNone TryWhenSomeThrowsOnlyForSomeThatThrows ThrowOrGetValueOnSome ThrowOrGetValueThrowsOnNone ErrorBuiltLazily TryNeverErrs TryEqualsOrThrowWhenNoThrow TryIsNoneWhenOrThrowThrows TryOnNoneIsNone AsyncTryAgrees diff --git a/formal/OptionalEffectsLaws.recover_always_calls.cfg b/formal/OptionalEffectsLaws.recover_always_calls.cfg new file mode 100644 index 0000000..52d9d70 --- /dev/null +++ b/formal/OptionalEffectsLaws.recover_always_calls.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: RecoverIsLazy +CONSTANTS Vals = {0, 1} Mutant = "recover_always_calls" +SPECIFICATION Spec +INVARIANTS TypeOK RecoverIsLazy diff --git a/formal/OptionalEffectsLaws.recover_replaces_nonempty.cfg b/formal/OptionalEffectsLaws.recover_replaces_nonempty.cfg new file mode 100644 index 0000000..a7addd4 --- /dev/null +++ b/formal/OptionalEffectsLaws.recover_replaces_nonempty.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: RecoverKeepsNonEmpty +CONSTANTS Vals = {0, 1} Mutant = "recover_replaces_nonempty" +SPECIFICATION Spec +INVARIANTS TypeOK RecoverKeepsNonEmpty diff --git a/formal/OptionalEffectsLaws.sequence_skips_none.cfg b/formal/OptionalEffectsLaws.sequence_skips_none.cfg new file mode 100644 index 0000000..31d9c77 --- /dev/null +++ b/formal/OptionalEffectsLaws.sequence_skips_none.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: SequenceAllOrNothing +CONSTANTS Vals = {0, 1} Mutant = "sequence_skips_none" +SPECIFICATION Spec +INVARIANTS TypeOK SequenceAllOrNothing diff --git a/formal/OptionalEffectsLaws.throw_error_built_eagerly.cfg b/formal/OptionalEffectsLaws.throw_error_built_eagerly.cfg new file mode 100644 index 0000000..0dab0ec --- /dev/null +++ b/formal/OptionalEffectsLaws.throw_error_built_eagerly.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: ErrorBuiltLazily +CONSTANTS Vals = {0, 1} Mutant = "throw_error_built_eagerly" +SPECIFICATION Spec +INVARIANTS TypeOK ErrorBuiltLazily diff --git a/formal/OptionalEffectsLaws.tla b/formal/OptionalEffectsLaws.tla new file mode 100644 index 0000000..69ef48e --- /dev/null +++ b/formal/OptionalEffectsLaws.tla @@ -0,0 +1,155 @@ +-------------------------- MODULE OptionalEffectsLaws -------------------------- +(* Finite model of Sources/OptionalAPI, part 2: the parts that count effects *) +(* or work on collections: recoverFromEmpty / hasElements / isNoneOrEmpty, *) +(* sequence / traverse (short-circuit), whenSome / whenNone / tryWhenSome, *) +(* throwOrGetValue, andThenTry / andThenTryOrThrow (+ async twins). *) +(* Closures that run user code are modelled by a call counter. A Collection is *) +(* a sequence over Vals of length 0..2. A throwing transform returns the token *) +(* Err instead of a value. *) +EXTENDS Naturals, Sequences, FiniteSets + +CONSTANTS Vals, Mutant + +None == [tag |-> "none", v |-> 0] +Some(x) == [tag |-> "some", v |-> x] +Opts == {None} \cup {Some(x) : x \in Vals} +IsSome(o) == o.tag = "some" +IsNone(o) == o.tag = "none" + +Colls == UNION {[1..n -> Vals] : n \in 0..2} +OptColls == {None} \cup {Some(c) : c \in Colls} +OptLists == UNION {[1..n -> Opts] : n \in 0..3} +ValLists == UNION {[1..n -> Vals] : n \in 0..2} +KFns == [Vals -> Opts] +Fns == [Vals -> Vals] +Preds == [Vals -> BOOLEAN] +Err == [tag |-> "err", v |-> 0] +TVals == Vals \cup {Err} \* result of a throwing transform +TFns == [Vals -> {Some(x) : x \in Vals} \cup {Err}] + +\* OptionalCollection.swift +HasElements(oc) == IF IsSome(oc) THEN oc.v # <<>> ELSE FALSE +IsNoneOrEmpty(oc) == IF IsSome(oc) THEN oc.v = <<>> ELSE TRUE +Recover(oc, d) == + IF IsSome(oc) + THEN (IF oc.v = <<>> \/ Mutant = "recover_replaces_nonempty" + THEN [r |-> Some(d), calls |-> 1] ELSE [r |-> oc, calls |-> 0]) + ELSE [r |-> None, calls |-> IF Mutant = "recover_always_calls" THEN 1 ELSE 0] +AsyncRecover(oc, d) == + IF IsSome(oc) + THEN (IF oc.v = <<>> THEN [r |-> Some(d), calls |-> 1] ELSE [r |-> oc, calls |-> 0]) + ELSE [r |-> None, calls |-> 0] + +\* Traversable.swift +Sequence(l) == + IF \A i \in DOMAIN l : IsSome(l[i]) + THEN Some([i \in DOMAIN l |-> l[i].v]) + ELSE IF Mutant = "sequence_skips_none" + THEN LET idx == {i \in DOMAIN l : IsSome(l[i])} + IN Some([j \in 1..Cardinality(idx) |-> + l[CHOOSE i \in idx : Cardinality({k \in idx : k < i}) = j - 1].v]) + ELSE None +FirstNone(xs, f) == + CHOOSE i \in DOMAIN xs : IsNone(f[xs[i]]) /\ \A j \in 1..(i - 1) : IsSome(f[xs[j]]) +Traverse(xs, f) == + [r |-> Sequence([i \in DOMAIN xs |-> f[xs[i]]]), + calls |-> IF \E i \in DOMAIN xs : IsNone(f[xs[i]]) + THEN (IF Mutant = "traverse_no_short_circuit" THEN Len(xs) ELSE FirstNone(xs, f)) + ELSE Len(xs)] + +\* RunWhen.swift: result paired with how many times the block ran +WhenSome(o) == [r |-> o, runs |-> IF IsSome(o) \/ Mutant = "when_some_runs_on_none" THEN 1 ELSE 0] +WhenNone(o) == [r |-> o, runs |-> IF IsNone(o) THEN 1 ELSE 0] +\* tryWhenSome: block throws for values in `th`; Err result models the rethrow +TryWhenSome(o, th) == + IF IsSome(o) /\ th[o.v] THEN Err ELSE o + +\* OptionalError.swift +ThrowOrGet(o) == + IF IsSome(o) + THEN [r |-> o.v, threw |-> FALSE, + calls |-> IF Mutant = "throw_error_built_eagerly" THEN 1 ELSE 0] + ELSE [r |-> 0, threw |-> TRUE, calls |-> 1] + +\* AndThen.swift: transform t either yields Some(x)/None-like result or throws (Err) +AndThenTry(o, t) == + IF IsSome(o) /\ t[o.v] # Err THEN t[o.v] + ELSE IF Mutant = "try_error_becomes_some" /\ IsSome(o) THEN Some(0) ELSE None +AndThenTryOrThrow(o, t) == + IF IsSome(o) THEN t[o.v] ELSE None \* may return Err (== rethrow) +TryAsyncAndThenTry(o, t) == + IF IsSome(o) THEN (IF t[o.v] = Err THEN None ELSE t[o.v]) ELSE None +TryAsyncAndThenTryOrThrow(o, t) == IF IsSome(o) THEN t[o.v] ELSE None + +VARIABLES o, oc, l, xs +vars == <> +Init == o \in Opts /\ oc \in OptColls /\ l \in OptLists /\ xs \in ValLists +Next == UNCHANGED vars +Spec == Init /\ [][Next]_vars + +TypeOK == o \in Opts /\ oc \in OptColls /\ l \in OptLists /\ xs \in ValLists + +\* ---- collections +HasElementsIsNotNoneOrEmpty == HasElements(oc) = ~IsNoneOrEmpty(oc) +NoneIsNoneOrEmpty == IsNoneOrEmpty(None) /\ ~HasElements(None) +RecoverNoneStaysNone == \A d \in Colls : Recover(None, d) = [r |-> None, calls |-> 0] +RecoverKeepsNonEmpty == + \A d \in Colls : (IsSome(oc) /\ oc.v # <<>>) => Recover(oc, d).r = oc +RecoverFillsEmpty == + \A d \in Colls : (IsSome(oc) /\ oc.v = <<>>) => Recover(oc, d).r = Some(d) +RecoverIsLazy == + \A d \in Colls : + Recover(oc, d).calls = (IF IsSome(oc) /\ oc.v = <<>> THEN 1 ELSE 0) +RecoverWithNonEmptyDefaultHasElements == + \A d \in Colls : (IsSome(oc) /\ d # <<>>) => HasElements(Recover(oc, d).r) +AsyncRecoverAgrees == \A d \in Colls : AsyncRecover(oc, d) = Recover(oc, d) + +\* ---- sequence / traverse +SequenceAllOrNothing == + IsSome(Sequence(l)) = (\A i \in DOMAIN l : IsSome(l[i])) +SequencePreservesOrderAndLength == + IsSome(Sequence(l)) => + Len(Sequence(l).v) = Len(l) /\ \A i \in DOMAIN l : Sequence(l).v[i] = l[i].v +SequenceEmptyIsSomeEmpty == Sequence(<<>>) = Some(<<>>) +SequenceNoneIfAnyNone == + (\E i \in DOMAIN l : IsNone(l[i])) => Sequence(l) = None +TraverseIsSequenceOfMap == + \A f \in KFns : Traverse(xs, f).r = Sequence([i \in DOMAIN xs |-> f[xs[i]]]) +TraverseShortCircuits == + \A f \in KFns : + (\E i \in DOMAIN xs : IsNone(f[xs[i]])) + => Traverse(xs, f).calls = FirstNone(xs, f) +TraverseCallsAllWhenTotal == + \A f \in KFns : + (\A i \in DOMAIN xs : IsSome(f[xs[i]])) => Traverse(xs, f).calls = Len(xs) +TraverseWithSomeIsMap == + \A g \in Fns : + Traverse(xs, [x \in Vals |-> Some(g[x])]).r = Some([i \in DOMAIN xs |-> g[xs[i]]]) + +\* ---- whenSome / whenNone +WhenReturnsSelf == WhenSome(o).r = o /\ WhenNone(o).r = o +WhenSomeRunsIffSome == WhenSome(o).runs = (IF IsSome(o) THEN 1 ELSE 0) +WhenNoneRunsIffNone == WhenNone(o).runs = (IF IsNone(o) THEN 1 ELSE 0) +WhenSomeXorWhenNone == WhenSome(o).runs + WhenNone(o).runs = 1 +TryWhenSomeThrowsOnlyForSomeThatThrows == + \A th \in Preds : + (TryWhenSome(o, th) = Err) = (IsSome(o) /\ th[o.v]) + /\ (TryWhenSome(o, th) # Err => TryWhenSome(o, th) = o) + +\* ---- throwOrGetValue +ThrowOrGetValueOnSome == IsSome(o) => ThrowOrGet(o).r = o.v /\ ~ThrowOrGet(o).threw +ThrowOrGetValueThrowsOnNone == IsNone(o) => ThrowOrGet(o).threw +ErrorBuiltLazily == ThrowOrGet(o).calls = (IF IsNone(o) THEN 1 ELSE 0) + +\* ---- andThenTry family +TryNeverErrs == \A t \in TFns : AndThenTry(o, t) # Err +TryEqualsOrThrowWhenNoThrow == + \A t \in TFns : (AndThenTryOrThrow(o, t) # Err) => AndThenTry(o, t) = AndThenTryOrThrow(o, t) +TryIsNoneWhenOrThrowThrows == + \A t \in TFns : (AndThenTryOrThrow(o, t) = Err) => AndThenTry(o, t) = None +TryOnNoneIsNone == \A t \in TFns : AndThenTry(None, t) = None /\ AndThenTryOrThrow(None, t) = None +AsyncTryAgrees == + \A t \in TFns : + TryAsyncAndThenTry(o, t) = AndThenTry(o, t) + /\ TryAsyncAndThenTryOrThrow(o, t) = AndThenTryOrThrow(o, t) +============================================================================= diff --git a/formal/OptionalEffectsLaws.traverse_no_short_circuit.cfg b/formal/OptionalEffectsLaws.traverse_no_short_circuit.cfg new file mode 100644 index 0000000..afaddce --- /dev/null +++ b/formal/OptionalEffectsLaws.traverse_no_short_circuit.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: TraverseShortCircuits +CONSTANTS Vals = {0, 1} Mutant = "traverse_no_short_circuit" +SPECIFICATION Spec +INVARIANTS TypeOK TraverseShortCircuits diff --git a/formal/OptionalEffectsLaws.try_error_becomes_some.cfg b/formal/OptionalEffectsLaws.try_error_becomes_some.cfg new file mode 100644 index 0000000..f23155f --- /dev/null +++ b/formal/OptionalEffectsLaws.try_error_becomes_some.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: TryIsNoneWhenOrThrowThrows +CONSTANTS Vals = {0, 1} Mutant = "try_error_becomes_some" +SPECIFICATION Spec +INVARIANTS TypeOK TryIsNoneWhenOrThrowThrows diff --git a/formal/OptionalEffectsLaws.when_some_runs_on_none.cfg b/formal/OptionalEffectsLaws.when_some_runs_on_none.cfg new file mode 100644 index 0000000..4a615e6 --- /dev/null +++ b/formal/OptionalEffectsLaws.when_some_runs_on_none.cfg @@ -0,0 +1,4 @@ +\* EXPECT_VIOLATION: WhenSomeRunsIffSome +CONSTANTS Vals = {0, 1} Mutant = "when_some_runs_on_none" +SPECIFICATION Spec +INVARIANTS TypeOK WhenSomeRunsIffSome diff --git a/formal/README.md b/formal/README.md new file mode 100644 index 0000000..9d89797 --- /dev/null +++ b/formal/README.md @@ -0,0 +1,84 @@ +# Formal model (TLA+) + +Two finite TLA+ modules model the public semantics of `Sources/OptionalAPI`. `Optional` is +`[tag, v]` over `Vals = {0, 1}`; transforms (`Fns`, `KFns`, `Preds`) range over their **full** finite +function spaces, so each law holds for every closure. "Producer" and "block" closures are modelled by a +call counter, which makes autoclosure laziness and short-circuiting checkable. + +## `OptionalCoreLaws.tla` + +| Invariant(s) | Swift API it abstracts | +|---|---| +| `PropertiesAreComplements` | `isNone` / `isSome` / `isNotNone` / `isNotSome` (+ free functions) | +| `MapIdentity`, `MapComposition` | `Optional.map` as used by the library | +| `MonadLeftIdentity`, `MonadRightIdentity`, `MonadAssociativity`, `AndThenNoneAbsorbs` | `andThen` (== `flatMap`), free `andThen` | +| `AsyncAgreesWithSync` | `asyncMap`, `asyncFlatMap`, `asyncAndThen`, `asyncFilter`, `asyncFold`, `asyncOr`, `asyncMapNone`, `asyncDefaultSome`, `asyncAp` equal their sync twins (the async ones are separate hand-written switches) | +| `ApSomeSome`, `ApNoneValue`, `ApNoneFunction`, `ApIsMap`, `ApIdentity` | `ap`, `asyncAp`, free `ap` | +| `FilterIsSubset`, `FilterKeepsIffPredicate`, `FilterNoneIsNone`, `FilterIdempotent`, `FilterFusion`, `FilterViaFlatMap` | `filter` | +| `SomeWhenIsFilterOfSome`, `NoneWhenComplementsSomeWhen` | `someWhen`, `noneWhen` | +| `FlattenCases`, `FlattenIsFlatMapId`, `FlattenIsJoin`, `FlattenUnit`, `FlattenOfNestedNone` | `flatten` | +| `FoldCases`, `FoldWithIdIsOr` | `fold`, `asyncFold` | +| `OrValue`, `OrIsLazy`, `OrProducerRunsOnceWhenNone` | `or` (producer evaluated only for `.none`) | +| `MapNoneAlwaysSome`, `MapNoneEqualsDefaultSome`, `OrOptionalOfSomeIsMapNone` | `mapNone`, `defaultSome` (+ free functions) | +| `OrOptionalLaws` | `orOptional` (identity, associativity, left bias) | +| `CoalesceMatchesFold`, `CoalesceEmptyIsNone`, `CoalesceIsFirstSome`, `CoalesceAllNone`, `CoalesceAgreesWithOrOptional` | `coalesce` (variadic and array) | +| `CastSameTypeKeeps`, `CastOtherTypeIsNone`, `CastNoneIsNone`, `CastResultIsSomeOnlyIfSome` | `cast` | +| `EncodeDecodeRoundTrip`, `DecodeFailureIsNone` | `encode` / `decode` (+ async) | + +## `OptionalEffectsLaws.tla` + +| Invariant(s) | Swift API it abstracts | +|---|---| +| `HasElementsIsNotNoneOrEmpty`, `NoneIsNoneOrEmpty` | `hasElements`, `isNoneOrEmpty` | +| `RecoverNoneStaysNone`, `RecoverKeepsNonEmpty`, `RecoverFillsEmpty`, `RecoverIsLazy`, `RecoverWithNonEmptyDefaultHasElements`, `AsyncRecoverAgrees` | `recoverFromEmpty`, `asyncRecoverFromEmpty` | +| `SequenceAllOrNothing`, `SequencePreservesOrderAndLength`, `SequenceEmptyIsSomeEmpty`, `SequenceNoneIfAnyNone` | `sequence` | +| `TraverseIsSequenceOfMap`, `TraverseShortCircuits`, `TraverseCallsAllWhenTotal`, `TraverseWithSomeIsMap` | `traverse` (stops at the first `nil`) | +| `WhenReturnsSelf`, `WhenSomeRunsIffSome`, `WhenNoneRunsIffNone`, `WhenSomeXorWhenNone`, `TryWhenSomeThrowsOnlyForSomeThatThrows` | `whenSome`, `whenNone`, `tryWhenSome` (+ async) | +| `ThrowOrGetValueOnSome`, `ThrowOrGetValueThrowsOnNone`, `ErrorBuiltLazily` | `throwOrGetValue` | +| `TryNeverErrs`, `TryEqualsOrThrowWhenNoThrow`, `TryIsNoneWhenOrThrowThrows`, `TryOnNoneIsNone`, `AsyncTryAgrees` | `andThenTry`, `andThenTryOrThrow`, `tryAsyncAndThenTry`, `tryAsyncAndThenTryOrThrow` | + +## Abstractions + +- `T` is `{0, 1}`; collections are sequences over it of length 0..2; `[T?]` lists have length 0..3. +- `Data` / `JSONEncoder` / `JSONDecoder`: `encode` is an injective tagging, an undecodable payload + is one token `junk`. Real JSON edge cases (fragments, number formatting, Linux Foundation + differences) are not modelled. +- `cast`: dynamic type is a tag in `{A, B}`; Swift `as?` bridging (`Int`/`Double`/`NSNumber`, + class hierarchies, existential boxing) is not modelled. +- A throwing transform returns an `Err` token; `try?` maps it to `.none`, `try` propagates it. +- `Optional.or(@autoclosure)` forwards to the closure overload `or(_: Producer)`; the model assumes + that overload resolution (no infinite recursion), as the XCTest suite exercises it. +- Async twins are modelled as separate definitions mirroring the Swift `switch`es and compared to + their sync versions; scheduling, cancellation and `@Sendable` are out of scope. + +## Non-vacuity + +Every `..cfg` seeds one bug via `Mutant` and names the catching invariant. Core: `filter_keeps_all` +(`FilterKeepsIffPredicate`), `or_eager` (`OrIsLazy`), `coalesce_last_wins` (`CoalesceIsFirstSome`), +`flatten_inner_none_becomes_some` (`FlattenCases`), `ap_ignores_none_value` (`ApNoneValue`), +`nonewhen_same_as_somewhen` (`NoneWhenComplementsSomeWhen`), `async_fold_wrong_none_case` +(`AsyncAgreesWithSync`), `decode_junk_becomes_some` (`DecodeFailureIsNone`), `cast_ignores_type` +(`CastOtherTypeIsNone`). Effects: `sequence_skips_none` (`SequenceAllOrNothing`), `traverse_no_short_circuit` +(`TraverseShortCircuits`), `recover_always_calls` (`RecoverIsLazy`), `recover_replaces_nonempty` +(`RecoverKeepsNonEmpty`), `when_some_runs_on_none` (`WhenSomeRunsIffSome`), `throw_error_built_eagerly` +(`ErrorBuiltLazily`), `try_error_becomes_some` (`TryIsNoneWhenOrThrowThrows`). `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 `master` or by manual dispatch (`.github/workflows/oracle-tla.yml`). + +## Findings + +None: every modelled law holds for the code as read. + +## Limits + +The model describes the semantics read by hand from the Swift sources; it does not prove the Swift +code conforms (XCTest does that). If the Swift behaviour changes, update the model in the same PR. +Not modelled: `Optional.isNotNone`/`isNotSome` being literal duplicates of `isSome`/`isNone` is +captured only as equalities; generics beyond one small carrier; `Producer`/`AliasWonderland` types. 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 ]]