mit-pdos/perennial
Über uns
Verifikation nebenläufiger Speichersysteme und verteilter Systeme.
Weitere ProjekteGemessener Sternzuwachs
- in 24h
- +2
- in 7 days
- +5
- in 15 days
- +9
- in 1 month
- Verlauf wird gesammelt
Nettoänderungen in überlappenden Zeiträumen, keine Tagessummen. Fehlende Messwerte bleiben leer. Sterne zeigen Interesse, nicht Qualität.
README.md
OriginalPerennial
Perennial's goose framework and program proofs, in Lean 4 on top of
iris-lean. This branch
(lean) is the primary branch. It covers Go programs translated by goose,
with a crash semantics and crash adequacy theorem but no crash program logic.
Guides: docs/PERENNIAL_PROOF_TUTORIAL.md,
docs/PERENNIAL_PROOF_REFERENCE.md,
docs/IRIS_PROOF_MODE.md.
Design decisions
One library,
Perennial. Framework directories are UpperCamelCase (Perennial/Golang/Theory/Slice.lean); generated, spec and proof directories follow Go package paths (Perennial/Proof/github_com/tchajed/marshal.lean).One spec per Go function, in its own file.
Perennial/Spec/<pkg>/<F>.leanholds the one Hoare triple of Go functionF(T__Mfor a method), andPerennial/Proof/<pkg>/<F>.leanits proof, which takes the specs of its callees as hypotheses and imports only theirSpecfiles;Perennial/Proof/<pkg>/Link.lean(generated byetc/gen-link.py) applies each proof to its callees' results, as<pkg>.wp_<F>, andPerennial/Proof/<pkg>.leanis the module clients import. Seedocs/PERENNIAL_PROOF_REFERENCE.md, "Layout of the program proofs".Standard WP, crashes in the semantics and adequacy only. GooseLang is an instance of iris-lean's
Language, and proofs use iris-lean'swp, which has later credits andnumLatersPerStep; there is no crash WP (wpc). The local and global state (state × GlobalState) form the single iris-leanState,CfgState. A crash and restart of the node (Crash,GooseLang/Lang.lean) kills every thread, gives the restarted program an arbitrary heap and a fresh Go runtime (no package initialized), and crashes each extension's local state by the extension's own relation (ExtSemantics.crash); the global state is kept.goose_crash_adequacy(GooseLang/CrashAdequacy.lean) is about executions with crashes (RealCrashNsteps,GooseLang/CrashLang.lean) of a boot program, which runs at the start and after every crash: each generation is proved with the standard WP, under the shared global ghost state and its own local ghost state (GooseLocalGS), from a client-chosen preconditionP Lof the generation's local ghost stateL, which each generation's proof guarantees for the next generation after its crash, from its persistentcrashedtoken (exclusive with thenotCrashedthat its state interpretation owns,GooseLang/CrashToken.lean) and a later credit£ 1(example:ProgramLogic/GenStartTest.lean). There are no crash reasoning principles yet (nocrash_own) beyond the crash-token update (ncfupd,GooseLang/NotCrashed.lean), by which a ghost step may usenotCrashed(to open an invariantinv N (P ∨ crashed ∗ tok)shared with later generations), before a step or in the client's update of a channel operation's atomic update. End-to-end example: the Go packagegoose/testdata/examples/crashfs, a boot program on a toy filesystem (GooseLang/Ext/Fs, Go sidecrashfs/fsext; not a sound model of a Linux filesystem, seeGooseLang/Ext/Fs/Impl.lean) whosepanicassertions never fire however many times the node crashes (crash_safety,Perennial/Proof/github_com/mit_pdos/perennial/goose/testdata/examples/crashfs/Results.lean).Distributed systems. A distributed system (
GooseLang/DistLang.lean) is a list of nodes, each with its own thread pool and local state, sharing the global state; a step is a real thread-pool step of one node.goose_dist_adequacy(GooseLang/DistAdequacy.lean) is about its executions: each node's program is proved with the standard WP, under the shared global ghost state and its own local ghost state (nodeWp), after a global setup that may allocate the invariants the nodes share. There is no distributed program logic. With crashes (DistCrashNsteps), a node crashes at any time and restarts from a crashed local state with its boot program, the one program it has (no separate recovery procedure);goose_dist_crash_adequacycombines this with crash adequacy: each generation of each node is proved with the standard WP from a client-chosen preconditionP i L, which it guarantees for the node's next generation, as ingoose_crash_adequacy.goose_dist_mixed_crash_adequacyis for systems where only some nodes crash: the nodescrashing ++ stable, of which the crashing ones owe that guarantee and the stable ones (which never crash) owe only their WP, as without crashes (example:ProgramLogic/MixedCrashTest.lean). End-to-end example: the Go packagegoose/testdata/examples/netfs, three nodes on a toy network (GooseLang/Ext/Net, Go sidenetfs/netext, whose primitives are stubs: the extension is a specification of a network) and the toy filesystem, where a node's reply after a reboot depends on the durability and order of its earlier writes, and whosepanicassertions never fire however often the nodes crash (netfs_crash_safety,Perennial/Proof/github_com/mit_pdos/perennial/goose/testdata/examples/netfs/Results.lean).Bounded layer, time receipts and thread tokens. The trusted semantics
BaseStep(and its iris-lean languagegooseRealEctxiLang,GooseLang/Lang.lean) is the model of Go, but the language instance used by the program logic is a separate bounded layer (GooseLang/BoundedLang.lean): its state adds a fuel⟨steps, threads⟩. Once the step fuel is exhausted, Go instructions stutter instead of stepping; this supports time receipts (Mével, Jourdan, Pottier, ESOP 2019;GooseLang/Receipts.lean):⧗ n/⧖ n, with⧗ N ⊢ Falsefor the boundN = receiptBound GF. Once the thread fuel is exhausted,Forkstutters; a thread's exit returns thread fuel. This supports thread tokens (GooseLang/Threads.lean):threadToks n, one per live thread, withthreadToks T ⊢ Falsefor the boundT = threadBound GF, so that a counter backed by one token per pending goroutine (async.WaitGroup's) is belowT, and that a stock ofT - 1copies of a resource lent to threads for their thread tokens never runs out (Proof/ThreadPool.lean; e.g. anRWMutex's reader tokens,Proof/sync/RWMutexThreads.lean). A token splits intoTlevels (levelTok l), each with its ownT - 1tokens, so that a thread can lend part of its token and keep the rest (sync.tokJoinL, pools at a level); the levels are ghost state only. For this the trusted semantics counts the live threads (state.threads):Fork espawnse ;; ThreadExitand increments it, and the no-opThreadExitdecrements it. The bounds are unspecified parameters, not constants: they are fields of the ghost stateReceiptGS GF/ThreadGS GF(parts ofGooseGlobalGSand of the per-generationGooseLocalGS, hence ofHeapGS), so downstream files, whose sections already assumeHeapGS, need no new argument, and the language instance and itsPureExec/Atomicinstances do not depend on them. A proof that needs a bound to be small takes a premise (wp_clock_incrinProgramLogic/TimeReceiptsTest.leantakesreceiptBound GF ≤ 2 ^ 64;wp_counter_registerinProgramLogic/ThreadTokensTest.leantakesthreadBound GF ≤ 2 ^ 31). The adequacy theorems (goose_adequacy N T,goose_invariance N T, and the grove/disk ones) hold for everyNandT: they allocate the ghost state withreceiptBound GF = NandthreadBound GF = T(hypotheses of the WP premiseHwp, which also receives the main thread's token, and from which the client discharges the proof's premises about the bounds; the main thread's postcondition must exclude panics, see "Panics" below) and are about real executions of fewer thanNsteps along which fewer thanTthreads are live, explicit hypotheses.goose_adequacystates the thread hypothesis over every execution ofnsteps (RealThreadsBelow T n);goose_adequacy_below/goose_invariance_below(GooseLang/AdequacyAlong.lean) state it of the one execution the theorem concludes about (RealNstepsBelow T n: fewer thanTthreads in each of its configurations), so that a program whose goroutine count is unbounded over all schedules can still use a constantTwithout bounding the step count by it. The crash and distributed theorems have the same forms:goose_crash_adequacy_belowoverRealCrashNstepsBelow(AdequacyAlong.lean), andgoose_dist_adequacy_below,goose_dist_crash_adequacy_belowandgoose_dist_mixed_crash_adequacy_belowoverDistCrashNstepsBelow(DistAdequacy.lean). Seedocs/PERENNIAL_PROOF_REFERENCE.md, "Time receipts" and "Thread tokens".Iris substrate. iris-lean provides the BI, proof mode, invariants, ghost maps, later credits and the WP. General-purpose libraries that iris-lean lacks (finite maps and sets, machine words, list lemmas) live in
Perennial/Std.- Finite maps are
Perennial.gmap K V(Perennial/Std/GMap.lean): finite partial functions, extensional so=is equality of bindings, needing onlyDecidableEq K.gset K = gmap K Unit. It is an iris-leanLawfulFiniteMap, so iris-lean'sghost_map/gen_heapapply. - Machine words are
BitVec n(w64 = BitVec 64, ...).uint.Z xis(x.toNat : Int)andsint.Z xisx.toInt. Arithmetic side conditions are discharged withword,omegaandbv_omega. Do not usebv_decide/native_decide: they trust native code (Lean.ofReduceBool); prove bitwise facts viatoNat. GoStringisList w8.
- Finite maps are
Platform: gc on linux/amd64 (trusted assumption). The model assumes Go programs are built by gc for linux/amd64. Every allocation address lies in
(0, maxAddr],maxAddr = 2^47(GooseLang/Lang.lean,IsFresh/IsFreshBytes), gc's user address space there, and proofs use that bound to rule out address overflow (unsafe.Slice,unsafe.Add). A string is no longer thanmaxAddreither:lenof a longer one is anAngelicExit(internal_string_len_step,Golang/Defn/String.lean; "Model assumptions (overflow)" below). The bound is false elsewhere, where a proof may claim "no panic" for a program gc stops:- aix/ppc64: gc's heap hints lie above
0xa0<<52. - linux/arm64 PIE and android: globals and
zerobaseload near0xaaaa_xxxx_xxxx, above 2^47, and the heap's fallback reservation maps near 2^48. - s390x: the user address space (
TASK_SIZE) is 2^64.
docs/KNOWN_LIMITATIONS.md, "Platform", repeats this. The standard library is translated with the build tagpurego(etc/update-goose-new.py), which selects the pure-Go code of the crypto packages (crypto/sha1'sblockGeneric, where the default build calls assembly) and changes no other package; build tags are those of a whole build, so the results are about programs built with-tags purego. Goose translates the build withoutGOEXPERIMENT=boringcrypto(boring.Enabledis the constantfalse), so the results do not cover a BoringCrypto build. The Go semantics also assumes a 64-bit platform: the word-sized typesint,uintanduintptrare 64-bit (valuesw64).uintptr(go.UintptrSemantics,Perennial/Golang/Defn/Predeclared.lean) is an integer type likeuint64. Pointer/unsafe.Pointerto/fromuintptrconversions are not modelled: they are stuck.- aix/ppc64: gc's heap hints lie above
Integers and floats are bytes. A value of an integer or float type of
wbytes (go.IsPlainScalar,Perennial/Golang/Defn/Predeclared.lean) iswheap cells holding its little-endian bytes, allocated together (AllocBytes) at any address. Loads and stores go byte by byte, and are stuck on a cell that is not a byte. The integer atomics ofsync/atomicand the semaphores are byte atomics of their width (LoadBytes,SwapBytes,AddBytes,CmpXchgBytes,GooseLang/Lang.lean), at any address: a misaligned atomic is assumed not to tear (docs/KNOWN_LIMITATIONS.md).bool,string, pointers and the other non-plain values stay one opaque cell (docs/design/unsafe-memory.md, R1, R2 and R5).Plain types have gc's layout. A plain type (
go.PlainLayout,Perennial/Golang/Defn/Plain.lean: integers and floats, arrays of at least one plain element, non-empty structs of plain non-blank fields with no padding, and named types of these) has gc's size and field offsets, and at a positive address its element and field addresses are concrete (go.PlainSemantics):arrayIndexRef V i l = l + i·sizeandstructFieldRef V f l = l + offset. Other addresses stay abstract. Every allocation, and every heap points-to, is at a positive address.Model assumptions (overflow). Where Go panics on an overflow that a real program cannot reach (it would run out of memory first), the model assumes the overflow does not happen, with
assume(Golang/Defn/Assume.lean: anassumethat fails loops forever, so the proofs cover the executions where it holds):append's new length (sumAssumeNoOverflowSigned,Golang/Defn/Slice.lean). Known to be reachable, not yet fixed: with zero-size elements no memory bounds the length, and Go panics where the model assumes:x := make([]struct{}, 1<<62); x = append(x, x...)panics with "growslice: len out of range". A program with that bug verifies.a string's length (
internal_string_len_step,Golang/Defn/String.lean):lenof a string longer thanmaxAddris anAngelicExit. Every string goose translates has its bytes in memory, which gc keeps belowmaxAddr("Platform").unsafe.Stringcan build a longer view, so goose's refusal of it is what keeps this sound; a future rule for it must check the backing allocation.
Only a length that must exist in memory may be assumed away; a length Go computes and checks before allocating is reachable. Overflows that a program can reach are not assumed away.
strings.Joinis one: Go sums the elements' lengths and panics before allocating anything, so a few gigabytes of aliased elements (make([]string, 1<<30+1)with a long separator) reach the panic. Goose translates the realJoin, overstrings.Builder(the real Go too, but for three Go models ingoose/model/overlay/strings/builder.go:String, which is stuck where Go'sStringaliases the builder's buffer,copyCheckandReset), so the panic is in the model, andstrings.wp_Joinrequires the result to be shorter than2^61bytes.sync.WaitGroup'sint32counter is another (twoAdd(1 << 30)calls panic in Go):WaitGroup.Addis Goose's translation, andWaitGroup.wp_Addasks its caller to bound the new counter by2^31. A caller whose counter is backed by one goroutine per unit discharges the bound with thread tokens (above):ntokens given < threadBound GF, and the client assumesthreadBound GF ≤ 2^31at adequacy time (ProgramLogic/ThreadTokensTest.lean,docs/PERENNIAL_PROOF_REFERENCE.md"Thread tokens").Model assumption (stack depth).
runtime.callers(TrustedCode/runtime.lean, behindruntime.Callers) reports at most2^40 - 1frames, so it returns fewer frames than a buffer of2^40or more holds (zap'sstacktrace.Capturedoubles its buffer until it is not filled, and stops). Go reports fewer than2^39: a stack is at mostmaxstackceiling(2e9 bytes on 64-bit, whichdebug.SetMaxStackdoes not raise), so at most250_000_000physical frames, each expanded into at most2081inlined frames with the compiler's default flags (the inliner's largest budget). Only compiler debug flags (-gcflags=-d=pgoinlinebudget=N,-d=inlbudgetslack=N) orGOEXPERIMENT=newinlinercould raise the inlining depth past that; a build with them is outside what the model covers.Model assumption (SHA-256 collisions), opt-in.
crypto/sha256.Sum256is a trusted model over the SHA-256 extension (GooseLang/Ext/Sha256/Impl.lean): an opaque functionsha256Hashand a global state of every input hashed so far. The extension takes a filterokof the hash steps a run allows; a stepokrefuses is anAngelicExit. Withsha256NoFilter(every step allowed) the model removes no execution, and Go's collisions are executions of the model. A theorem may instead assumeSha256NoCollision ok:okallows the hash step to returnhfor an input only if no other input hashed before has the hashh. Such a theorem covers only the runs with no SHA-256 collision among the inputs hashed during the run (instantiated withsha256NoCollisionFilter, it covers exactly those). This is a cryptographic assumption, reachable in principle and so not of the overflow kind above: it is never made by the semantics, only by a top-level statement that namesSha256NoCollision okas a hypothesis (GooseLang/Ext/Sha256/Adequacy.lean). Onlycrypto.sha256.is_hash_injneeds it.The process environment is not in core GooseLang. The environment a program was launched with belongs to an OS extension, not to the core state:
syscall.Getenvis a Go model over the primitive stubenvGet(goose/model/overlay/syscall/env.go), whose trusted model (TrustedCode/syscall.lean) is the operationExternalOp "os" "Getenv"of an extension namedos, which the program's extensions must provide (etcd-grove's Linux extensionfsExtdoes, with the environment in its per-machine state); without one, the call is stuck.os.Getenvis translated from its real body over it. Evidence for the model's Go:goose/model/runtime/env_test.go.Environment premise (GODEBUG
fips140), opt-in.crypto/fips140'senabled(godebug.New("fips140").Value() == "only") is a trusted initializer (TrustedCode/crypto/fips140.lean) overgodebugFips140, an opaque string standing for the text of the run'sfips140GODEBUG setting, of which nothing is proved. In modeonly,crypto/sha1.Sumpanics. A theorem whose proof needs the mode off namesGodebugFips140Off(the setting is unset oroff) as a hypothesis, and then covers only the runs with that setting; it is the condition under which the initializers ofcrypto/internal/fips140andcrypto/internal/fips140/checkdo not panic (withpurego, FIPS 140-3 mode panics at start). The model makes no such assumption itself. Incrypto/rand's closurecrypto/internal/fips140'sinitis translated (over the trustedcrypto/internal/fips140deps/godebug.Value, which returnsgodebugFips140or""), so the model runs it:crypto/rand'sinitialize'.spec(and those of the packages between) takes the condition on the machines' initial stategodebugFips140 = "" ∨ godebugFips140 = "off"as a hypothesis, written out.check'sinitis not run; with FIPS 140-3 mode on, the model is stuck incrypto/internal/fips140/drbg'sinit(the Go model offips140.CAST) where Go panics incheck's. A package that reaches them only throughcrypto/fips140runs neither (docs/KNOWN_LIMITATIONS.md, "crypto/rand": unsound, open). The trusted initializer stands in for translatinginternal/godebug(by the user's decision, 2026-11-23), which goose translates but for fourgo:linknamehooks (setUpdate, whose model would have to hand it the environment,registerMetric,setNewIncNonDefault,write) and which needssync.Mapandinternal/bisect, not translated.Environment premises (the build's
runtime.buildVersion), opt-in. The stringVersionreturns is the trusted initializer'sruntime.buildVersionValue(TrustedCode/runtime.lean), an opaque string standing for what the linker wrote into the binary, of which nothing is proved. A theorem whose proof needs a property of it (for example that it is valid UTF-8, which a standardgo buildgives and only-ldflags -X runtime.buildVersion=<s>can break) names the property as a hypothesis, and then covers only the builds with it.Model assumptions (initial states). An extension's
ExtSemantics.initLocal/initGlobal(GooseLang/Lang.lean, defaultTrue) are what a top-level theorem assumes of the states its execution starts from. A value other than the default is either an assumption that every real start of a machine satisfies, or a constraint on state only the model has (sha256'sinitGlobal: nothing hashed yet); its docstring says which. The two must be jointly satisfiable, or every_initadequacy theorem is vacuous: each extension that sets one has a checkedexampleof∃ g s, initGlobal g ∧ initLocal s gnext to its instance (sha256's,Ext/Sha256/Impl.lean:⟨(∅ : Sha256State), (), rfl, trivial⟩).Panics. A panic outcome is a value,
PanicV p, that unwinds every evaluation frame but that ofCatch e h k(GooseLang/Lang.lean);panic(p)steps to it, a function withdefers runs its body under aCatch(Golang/Defn/Defer.lean), andrecover()(Goose translates it only directly in a deferred function literal, or in a function or methodFthatdefer F(...)calls asF'deferred, passing the cell as$recover) reads and clears the panic. A postcondition receives panics too, a spec{{ P }} e {{ RET v; Q }}excludes them, and a goroutine must not panic (wp_fork:forkPost). The adequacy theorems (goose_adequacyand the grove/disk ones) require the main thread's postconditionφto exclude panics (hφ : ∀ p, ¬ φ (PanicV p), a pure fact aboutφ) and conclude that no thread of the execution has an unrecovered panic (UnrecoveredPanic,GooseLang/BoundedLang.lean): no thread isPanicV p, and none is unwinding a panic through frames none of which is aCatch, so a verified program does not die of a panic within the step bound. Run-time panics of builtins (Panic "msg") are stuck. Seedocs/PERENNIAL_PROOF_REFERENCE.md, "Panics".Program exit.
os.Exitis translated oversyscall.Exit, whose trusted model isAngelicExit(TrustedCode/syscall.lean, which shares it with the Go models' exit primitiveinternal/gomodel.Exit): the calling goroutine steps forever, so its deferred functions never run and its code after the call is unreachable (syscall.Exit.spechas postconditionFalse). The other goroutines keep running in the model, where Go stops them, as aftermainreturns: every Go execution is a prefix of the model's, so the adequacy theorems' conclusions (no stuck thread, no unrecovered panic) cover Go up to the exit, and a proof must also show the other goroutines safe after it. An exit is not a failure:os.Exit(1)(and a logger'sFatal) ends a run that the theorems count as safe; a program that reports a violation by exiting is not checked by them.Skipped package variables. A package variable listed in a
[[skip]]entry of its goose config (names, and a requiredreason) is not translated at all: goose emits no Lean name, noX.init, no allocation and no step ininitialize', and lists the skipped variables with their reasons in the package'sskipped' : List go.SkippedVar(Golang/Defn/Pkg.lean). Translated code that names one (in its package or one that imports it) is a goose error, and hand-written Lean cannot name it, so that verified code never touches the variable holds by construction. The trusted claim of each entry is its reason: not running the variable's Go initializer is unobservable (it terminates, cannot panic, and has no effect beyond the variable). A blank variable (var _ = ...) is listed by its position,"[email protected]:L", with its own reason; a package that skips one lists all of its blank variables, so that one a Go upgrade adds or moves fails the translation until its entry is reviewed. Each entry ofskipped'carries the variable's Go declaration, so a changed initializer changes the generated file, andetc/trusted-delta.pyreports every added, removed or changedskipped'entry as a change to the trusted base. (Hand-written Lean can still write a skipped variable's address from a literal name,GlobalVarAddr go!"pkg.X":trusted-deltaflags every such literal,global-var-addr, and a load or store through it is stuck, as the variable is never allocated.)goose/cmd/skiplint, run byetc/update-goose-new.pyafter translating and separate from goose, warns on the side about a skipped initializer that stores to a package variable or takes one's address, directly or through its package's functions; it is best-effort (it does not follow other packages, interfaces or pointers it did not see taken), so every reason is still reviewed.grep -A3 '\[\[skip\]\]' Perennial/Codelists the entries; thereview-trustedrule R11 says how to check one.Trusted package-variable initializers. A package variable listed in a goose config's
trustedgets its initializerX.init(allocation included) fromPerennial/TrustedCode. A few of them do nothing (λ: <>, #()) although translated code is to read the variable once it is modelled (os.Stdout,log.stdandmath.useFMA, until they get real models: perennial#663): the variable is then not allocated, so a load or store of it is stuck (taking its address steps), and each docstring says why skipping Go's initializer is sound. An initializer of several variables (var c, d = pair(), one Go evaluation) that is trusted or axiomatized runsc.initthend.init: goose cannot split the evaluation, so by convention the first variable'sinitcarries all of it (its effects, any panic, and the variables it gives values to), each later one only what is left for its own variable (nothing, if the first did it all), and the first one's docstring says so. Accepted for now, to remove later: three such models are trusted although goose translates the real source, so thereview-trustedrule R2 grades them REWORK; they were accepted (2026-10-19) to finish the standard library's init proofs, and later reviews and soundness work should translate them away:time.asynctimerchan(the fix translatesinternal/godebug, trusting its runtime hookssetUpdateandsetNewIncNonDefault, withinternal/bisectandinternal/godebugs;asynctimerchan's model also allocates the model's runtime clock, runtime state no Go variable holds, so translating it needs another place for that, such as a goose hook for a package's model-only initialization),log.std(no-op; needsos.Stderr, soos's initialization),log'sinit(no-op; it writeslog/internal.DefaultOutput, and no ownership of another package's variable reaches an init proof: a program-logic gap). (Two more were translated away or skipped:crypto/rand.Readeris translated overcrypto/internal/rand, andcrypto/ed25519.cryptocustomrandis a skip entry, which no translated code reads.) A function of the same standing (R2 REWORK, accepted 2026-11-23 to givemath/rand's top-level functions proved specs):math/rand.globalRand, Go's body with itsrandautoseed.Value() == "0"test (aGODEBUGread) replaced by the default outcome, the generator over the runtime's source; its docstring argues that the other outcome's results are among the model's. The fix translatesinternal/godebug(as forasynctimerchan) and the seeded path it then reaches (lockedSource,rngSourceand its seeding overrngCooked).crypto/sha1'sinit(crypto.RegisterHash(crypto.SHA1, New)) is a trusted no-op for the same program-logic gap, ascrypto/sha256's:cryptois not translated, so nothing translated reads its hash table (the user's decision, 2026-11-23). The no-op formath.useFMA(a CPU feature the runtime detects) models irreducible behaviour;errors.errorTypeandmath/big.hasADX, the same kind, are skip entries. Each model's docstring says why it is faithful.sync.Pool.GetandPutare a Go model (goose/model/overlay/sync/pool.go): the real ones rely on runtime pinning to a P, pointer arithmetic andefacelayout reinterpretation. They keep Go'sPut(nil)andNewhandling and replace the per-P pools by a lock-protected multiset (poolModel) installed in the pool's fieldlocal, wherePutmay drop its value andGetmay ignore the pool. That is more nondeterministic than gc's pools, victim cache and GC clearing. The one primitive stub,poolModelAt(TrustedCode/sync.lean), convertslocalback to*poolModel.sync.Mutex. Goose translatessync.Mutex(struct { _ noCopy; mu isync.Mutex }) and its methods, which forward tointernal/sync.Mutex. ThatMutexis Go's type, translated, and itsLock,TryLockandUnlockare a Go model (goose/model/overlay/internal/sync): Go's have data races (the race detector is disabled on the sync packages) and park on the runtime's semaphores. The model is a spin lock onstate(0 is unlocked, 1 locked) oversync/atomic's compare-and-swap, more nondeterministic than Go's (no fairness or starvation mode, andTryLockmay fail on an unlocked mutex, as Go's does in starvation mode or when its CAS loses to a waiter);Unlockof an unlocked mutex is stuck, where Go ends the program (fatal).sync.Mutex{}is a literal of the translated struct, so it steps by the ordinary struct rules to a zero, unlocked mutex.Method sets. Whether a type implements an interface (
go.typeSetContains, used by type assertions and conversions) is decided bymethodSet, an uninterpreted function of the semantics constrained bygo.MethodSetIs t msfacts (Golang/Defn/MethodSet.lean): "the method set oftis exactlyms". goose emits them, for each named typeTof a translated package, forTand*TinT.TypeAssumptions(method_set,ptr_method_set), from the Go type checker (go/types.NewMethodSet: value and pointer receivers, methods promoted through embedded fields with Go's depth and ambiguity rules, methods that are not translated, the same at every instantiation of a generic type); the semantics (InterfaceSemantics.method_set_no_methods) gives the empty method sets of the types that have no methods in Go (go.NoMethods). A method set is a property of a type's declaration that the type checker fixes, like its underlying type, which goose also emits: computing promotion in Lean would duplicate the type checker's rules, with nothing to check it against. A method is named by its Go id: an unexported method's name qualified by its package path ("context.cancel"), in method sets and in interface types (go.MethodElem) alike, since in Go an unexported method of one package never implements an interface of another. goose writes an interface type as all its methods (go/types' method set of the interface, embedded interfaces included), so thattypeSetContainsneeds no recursion through embedded named interfaces; embedded constraint elements (unions,comparable) stay as type terms. A type a signature mentions that the translation cannot name (a named type or alias of a package it does not import) is written as what it denotes (go.Named "<path>.<Name>" args, the aliased type), so that an interface type has the same term, up to unfolding descriptors and aliases, in every package that writes it: Go's type identity, which=ongo.GoTypemust agree with wherever interface types are compared (in signatures, as element types). Nothing is claimed beyond what is known: a method whose signature has a type goose does not support is an entry without a signature ((id, none): it exists), and the method set of any other type (a struct type literal with embedded fields, a type declared in a function, a type of an untranslated package) is unconstrained. Struct tags are part ofgo.StructType: every field declaration (go.field_decl.Field/Embedded name type tag, the tag empty when there is none; the shorthandsgo.FieldDecl/go.EmbeddedField name typefor the usual untagged field) carries its tag, which goose writes for the fields of unnamed struct types, so that=is Go's type identity for them. A defined struct type's underlying type is written without its tags (its identity is its name), so a conversion that Go allows only by ignoring tags, or between a tagged unnamed struct type and a defined type, is stuck (docs/KNOWN_LIMITATIONS.md). One limit of the model's type identity applies here as to type assertions: the unexported field names of struct type literals are not qualified by package. goose loads code with the build taggoose: a method declared only in files excluded by it (or included only by it) would make the emitted method set differ from the real build's.go_type_set(Golang/Theory/TypeSet.lean) decidestypeSetContainsgoals.Go model overlays. A package's trusted parts may be Go model code in the package itself: its goose config's
[model]table names a directory of model files and the real declarations they replace (goose/README.md). Goose splices the model into the real package in place (so initialization order is kept), refuses a model that changes the real package's API, and translates the model like any other code; only the primitive stubs it calls have a hand-written.impl. The trusted claim, for each replaced declaration, is that every behaviour of the real one under every use is a behaviour of the model's translation (review-trusted, R12). The plan and its stages:goose/model-overlays-plan.md.Generated code comes from goose. The translator in
goose/emitsPerennial/Code/**andPerennial/GeneratedProof/**; regenerate withetc/update-goose-new.pyrather than editing them by hand. The translation's Go toolchain is pinned to go1.26.11 (GO_VERSIONthere; the standard library goose translates is that toolchain's), and the script refuses anothergo.
Layering (bottom up)
| Directory | Contents |
|---|---|
Perennial/Std |
general libraries (gmap, words, lists, bytes) |
Perennial/Algebra |
cameras and ghost-state algebra |
Perennial/GooseLang |
GooseLang: semantics, lifting, bounded-step layer, receipts |
Perennial/GooseLang/Ext |
GooseLang extensions (new primitives): grove |
Perennial/Golang/Defn |
the Go model |
Perennial/Golang/Theory |
its program logic and spec lemmas |
Perennial/Ghost |
ghost-state libraries |
Perennial/TrustedCode |
trusted (hand-written) models of Go code |
Perennial/Code |
GooseLang code (generated by goose) |
Perennial/GeneratedProof |
generated proof boilerplate (generated by proofgen) |
Perennial/Spec |
the specs of the proved Go functions, one per file |
Perennial/Proof |
their proofs, one per file, linked in <pkg>/Link.lean |
Status
Run etc/lean-ci.sh + etc/lean-audit.py for the build and soundness audit
(sorry roots, axioms and opaques). etc/trusted-delta.py [commit | A..B]
prints what a change adds to the trusted base (semantics, goose, trusted
models, trust lists, assumes); the review-trusted skill
(.agents/skills/review-trusted/) reviews it.
Conventions
- Follow the naming of the surrounding code (
wp_load,isMutex,ownSlice). Quote names that are not legal Lean identifiers with «» (e.g.«unsafe»,«_»). - Sealing:
def fooDef,@[irreducible] def foo := fooDef,theorem foo_unseal : foo = fooDef. To make an existing definition opaque, useattribute [irreducible] foo. - GooseLang code notation (
Perennial/GooseLang/Notation.lean):λ: "x", e,let: "x" := e1 in e2,e1 ;; e2,if: c then a else b,rec: "f" "x" := e, Go operatorse1 +⟨t⟩ e2etc. Method calls arercvr @!! T @!! m. - Everything lives in
namespace Perennial. - Every file is a module of Lean's module system:
module, then itspublic imports, then@[expose] public section, so that all declarations are public with their bodies exposed. - An unfinished proof is
sorry, with a comment saying what is missing if it is not obvious. Do not add newaxioms without discussing it first. - Notation:
#xisintoVal x;m !! k,<[k := v]> m,{[k := v]}work on bothgmapandList(on lists they arel[i]?andl.set i v); the set-valued domain of a map isdomSet m;go!"abc"is aGoStringliteral;l +ₗ iis location offset. - Equality on GooseLang syntax and
go.GoTypeis decided classically (noncomputable instance). - An extension (
GooseExt) has a name (by convention the path of the Go package it implements). Its operations are named by strings,ExternalOp ext op e(the extension's name and the operation's; an extension's step is defined on the operation's name), and its opaque values by its name and their encoding (ExtCode,extVal E v), so that neither the syntax nor goose depends on the program's list of extensions: the trusted model of a Go function implemented with an extension isExternalOp E.name "Op" ..., with no assumption, andElemExt E/HasExt E(proofs aboutE) are propositions, proved by computation when a program is closed off. Goose knows nothing of extensions. - An extension's initial states are part of its trusted semantics
(
ExtSemantics.initLocal/initGlobal, defaultTrue), not of its ghost state: a top-level theorem assumesextsInitLocal/extsInitGlobal, through the adequacy theorems'_initversions (GooseLang/InitAdequacy.lean), which require each interpretation to accept them (ExtInitCompat). Seedocs/PERENNIAL_PROOF_REFERENCE.md, "Initial states of extensions". - An extension (
GooseExt) requiresPos.Countableof itsVal, andLoc,GoSlice,val,Expr,GoFunc,GoInterface,go.GoType, ... arePos.Countable(Perennial/GooseLang/Countable.lean, via an injection intoGenTree), so ghost state can store values containing code. - Check a file with
lake build Perennial.Path.To.Module(from the repo root). - The proof automation is compiled to native code:
lakefile.tomldeclares a second library,PerennialMeta, withprecompileModules, listing the modules that define tactics, elaborators, notation or simprocs and everything they import (about 150 modules, rooted at the generatedPerennialMeta.lean). After adding such a module, or changing the imports of one, runetc/meta-lib.pyand commit the result;etc/lean-ci.shandetc/land.sh preparefail until the list is up to date. Editing one of these modules relinks the library and rebuilds everything that loads it. The first build also compiles iris, batteries and Qq to native code (once).
Ähnliche Projekte entdecken
Wird geladen…