Skip to content
المشاريع

حول

التحقق من أنظمة التخزين المتزامنة والأنظمة الموزعة

مشاريع أخرى

كيف تُقاس هذه الأرقام

273 نجمة57 التفرعات +2 خلال 24 ساعة

النمو المقاس للنجوم

خلال 24 ساعة
+٢
خلال 7 أيام
+٥
خلال 15 يومًا
+٩
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

Perennial

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>.lean holds the one Hoare triple of Go function F (T__M for a method), and Perennial/Proof/<pkg>/<F>.lean its proof, which takes the specs of its callees as hypotheses and imports only their Spec files; Perennial/Proof/<pkg>/Link.lean (generated by etc/gen-link.py) applies each proof to its callees' results, as <pkg>.wp_<F>, and Perennial/Proof/<pkg>.lean is the module clients import. See docs/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's wp, which has later credits and numLatersPerStep; there is no crash WP (wpc). The local and global state (state × GlobalState) form the single iris-lean State, 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 precondition P L of the generation's local ghost state L, which each generation's proof guarantees for the next generation after its crash, from its persistent crashed token (exclusive with the notCrashed that its state interpretation owns, GooseLang/CrashToken.lean) and a later credit £ 1 (example: ProgramLogic/GenStartTest.lean). There are no crash reasoning principles yet (no crash_own) beyond the crash-token update (ncfupd, GooseLang/NotCrashed.lean), by which a ghost step may use notCrashed (to open an invariant inv 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 package goose/testdata/examples/crashfs, a boot program on a toy filesystem (GooseLang/Ext/Fs, Go side crashfs/fsext; not a sound model of a Linux filesystem, see GooseLang/Ext/Fs/Impl.lean) whose panic assertions 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_adequacy combines this with crash adequacy: each generation of each node is proved with the standard WP from a client-chosen precondition P i L, which it guarantees for the node's next generation, as in goose_crash_adequacy. goose_dist_mixed_crash_adequacy is for systems where only some nodes crash: the nodes crashing ++ 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 package goose/testdata/examples/netfs, three nodes on a toy network (GooseLang/Ext/Net, Go side netfs/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 whose panic assertions 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 language gooseRealEctxiLang, 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 ⊢ False for the bound N = receiptBound GF. Once the thread fuel is exhausted, Fork stutters; a thread's exit returns thread fuel. This supports thread tokens (GooseLang/Threads.lean): threadToks n, one per live thread, with threadToks T ⊢ False for the bound T = threadBound GF, so that a counter backed by one token per pending goroutine (a sync.WaitGroup's) is below T, and that a stock of T - 1 copies of a resource lent to threads for their thread tokens never runs out (Proof/ThreadPool.lean; e.g. an RWMutex's reader tokens, Proof/sync/RWMutexThreads.lean). A token splits into T levels (levelTok l), each with its own T - 1 tokens, 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 e spawns e ;; ThreadExit and increments it, and the no-op ThreadExit decrements it. The bounds are unspecified parameters, not constants: they are fields of the ghost state ReceiptGS GF/ThreadGS GF (parts of GooseGlobalGS and of the per-generation GooseLocalGS, hence of HeapGS), so downstream files, whose sections already assume HeapGS, need no new argument, and the language instance and its PureExec/Atomic instances do not depend on them. A proof that needs a bound to be small takes a premise (wp_clock_incr in ProgramLogic/TimeReceiptsTest.lean takes receiptBound GF ≤ 2 ^ 64; wp_counter_register in ProgramLogic/ThreadTokensTest.lean takes threadBound GF ≤ 2 ^ 31). The adequacy theorems (goose_adequacy N T, goose_invariance N T, and the grove/disk ones) hold for every N and T: they allocate the ghost state with receiptBound GF = N and threadBound GF = T (hypotheses of the WP premise Hwp, 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 than N steps along which fewer than T threads are live, explicit hypotheses. goose_adequacy states the thread hypothesis over every execution of n steps (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 than T threads in each of its configurations), so that a program whose goroutine count is unbounded over all schedules can still use a constant T without bounding the step count by it. The crash and distributed theorems have the same forms: goose_crash_adequacy_below over RealCrashNstepsBelow (AdequacyAlong.lean), and goose_dist_adequacy_below, goose_dist_crash_adequacy_below and goose_dist_mixed_crash_adequacy_below over DistCrashNstepsBelow (DistAdequacy.lean). See docs/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 only DecidableEq K. gset K = gmap K Unit. It is an iris-lean LawfulFiniteMap, so iris-lean's ghost_map/gen_heap apply.
    • Machine words are BitVec n (w64 = BitVec 64, ...). uint.Z x is (x.toNat : Int) and sint.Z x is x.toInt. Arithmetic side conditions are discharged with word, omega and bv_omega. Do not use bv_decide/native_decide: they trust native code (Lean.ofReduceBool); prove bitwise facts via toNat.
    • GoString is List w8.
  • 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 than maxAddr either: len of a longer one is an AngelicExit (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 zerobase load near 0xaaaa_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 tag purego (etc/update-goose-new.py), which selects the pure-Go code of the crypto packages (crypto/sha1's blockGeneric, 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 without GOEXPERIMENT=boringcrypto (boring.Enabled is the constant false), so the results do not cover a BoringCrypto build. The Go semantics also assumes a 64-bit platform: the word-sized types int, uint and uintptr are 64-bit (values w64). uintptr (go.UintptrSemantics, Perennial/Golang/Defn/Predeclared.lean) is an integer type like uint64. Pointer/unsafe.Pointer to/from uintptr conversions are not modelled: they are stuck.

  • Integers and floats are bytes. A value of an integer or float type of w bytes (go.IsPlainScalar, Perennial/Golang/Defn/Predeclared.lean) is w heap 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 of sync/atomic and 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·size and structFieldRef 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: an assume that 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): len of a string longer than maxAddr is an AngelicExit. Every string goose translates has its bytes in memory, which gc keeps below maxAddr ("Platform"). unsafe.String can 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.Join is 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 real Join, over strings.Builder (the real Go too, but for three Go models in goose/model/overlay/strings/builder.go: String, which is stuck where Go's String aliases the builder's buffer, copyCheck and Reset), so the panic is in the model, and strings.wp_Join requires the result to be shorter than 2^61 bytes. sync.WaitGroup's int32 counter is another (two Add(1 << 30) calls panic in Go): WaitGroup.Add is Goose's translation, and WaitGroup.wp_Add asks its caller to bound the new counter by 2^31. A caller whose counter is backed by one goroutine per unit discharges the bound with thread tokens (above): n tokens give n < threadBound GF, and the client assumes threadBound GF ≤ 2^31 at adequacy time (ProgramLogic/ThreadTokensTest.lean, docs/PERENNIAL_PROOF_REFERENCE.md "Thread tokens").

  • Model assumption (stack depth). runtime.callers (TrustedCode/runtime.lean, behind runtime.Callers) reports at most 2^40 - 1 frames, so it returns fewer frames than a buffer of 2^40 or more holds (zap's stacktrace.Capture doubles its buffer until it is not filled, and stops). Go reports fewer than 2^39: a stack is at most maxstackceiling (2e9 bytes on 64-bit, which debug.SetMaxStack does not raise), so at most 250_000_000 physical frames, each expanded into at most 2081 inlined frames with the compiler's default flags (the inliner's largest budget). Only compiler debug flags (-gcflags=-d=pgoinlinebudget=N, -d=inlbudgetslack=N) or GOEXPERIMENT=newinliner could 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.Sum256 is a trusted model over the SHA-256 extension (GooseLang/Ext/Sha256/Impl.lean): an opaque function sha256Hash and a global state of every input hashed so far. The extension takes a filter ok of the hash steps a run allows; a step ok refuses is an AngelicExit. With sha256NoFilter (every step allowed) the model removes no execution, and Go's collisions are executions of the model. A theorem may instead assume Sha256NoCollision ok: ok allows the hash step to return h for an input only if no other input hashed before has the hash h. Such a theorem covers only the runs with no SHA-256 collision among the inputs hashed during the run (instantiated with sha256NoCollisionFilter, 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 names Sha256NoCollision ok as a hypothesis (GooseLang/Ext/Sha256/Adequacy.lean). Only crypto.sha256.is_hash_inj needs 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.Getenv is a Go model over the primitive stub envGet (goose/model/overlay/syscall/env.go), whose trusted model (TrustedCode/syscall.lean) is the operation ExternalOp "os" "Getenv" of an extension named os, which the program's extensions must provide (etcd-grove's Linux extension fsExt does, with the environment in its per-machine state); without one, the call is stuck. os.Getenv is 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's enabled (godebug.New("fips140").Value() == "only") is a trusted initializer (TrustedCode/crypto/fips140.lean) over godebugFips140, an opaque string standing for the text of the run's fips140 GODEBUG setting, of which nothing is proved. In mode only, crypto/sha1.Sum panics. A theorem whose proof needs the mode off names GodebugFips140Off (the setting is unset or off) as a hypothesis, and then covers only the runs with that setting; it is the condition under which the initializers of crypto/internal/fips140 and crypto/internal/fips140/check do not panic (with purego, FIPS 140-3 mode panics at start). The model makes no such assumption itself. In crypto/rand's closure crypto/internal/fips140's init is translated (over the trusted crypto/internal/fips140deps/godebug.Value, which returns godebugFips140 or ""), so the model runs it: crypto/rand's initialize'.spec (and those of the packages between) takes the condition on the machines' initial state godebugFips140 = "" ∨ godebugFips140 = "off" as a hypothesis, written out. check's init is not run; with FIPS 140-3 mode on, the model is stuck in crypto/internal/fips140/drbg's init (the Go model of fips140.CAST) where Go panics in check's. A package that reaches them only through crypto/fips140 runs neither (docs/KNOWN_LIMITATIONS.md, "crypto/rand": unsound, open). The trusted initializer stands in for translating internal/godebug (by the user's decision, 2026-11-23), which goose translates but for four go:linkname hooks (setUpdate, whose model would have to hand it the environment, registerMetric, setNewIncNonDefault, write) and which needs sync.Map and internal/bisect, not translated.

  • Environment premises (the build's runtime.buildVersion), opt-in. The string Version returns is the trusted initializer's runtime.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 standard go build gives 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, default True) 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's initGlobal: nothing hashed yet); its docstring says which. The two must be jointly satisfiable, or every _init adequacy theorem is vacuous: each extension that sets one has a checked example of ∃ g s, initGlobal g ∧ initLocal s g next 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 of Catch e h k (GooseLang/Lang.lean); panic(p) steps to it, a function with defers runs its body under a Catch (Golang/Defn/Defer.lean), and recover() (Goose translates it only directly in a deferred function literal, or in a function or method F that defer F(...) calls as F'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_adequacy and 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 is PanicV p, and none is unwinding a panic through frames none of which is a Catch, so a verified program does not die of a panic within the step bound. Run-time panics of builtins (Panic "msg") are stuck. See docs/PERENNIAL_PROOF_REFERENCE.md, "Panics".

  • Program exit. os.Exit is translated over syscall.Exit, whose trusted model is AngelicExit (TrustedCode/syscall.lean, which shares it with the Go models' exit primitive internal/gomodel.Exit): the calling goroutine steps forever, so its deferred functions never run and its code after the call is unreachable (syscall.Exit.spec has postcondition False). The other goroutines keep running in the model, where Go stops them, as after main returns: 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's Fatal) 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 required reason) is not translated at all: goose emits no Lean name, no X.init, no allocation and no step in initialize', and lists the skipped variables with their reasons in the package's skipped' : 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 of skipped' carries the variable's Go declaration, so a changed initializer changes the generated file, and etc/trusted-delta.py reports every added, removed or changed skipped' 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-delta flags 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 by etc/update-goose-new.py after 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/Code lists the entries; the review-trusted rule R11 says how to check one.

  • Trusted package-variable initializers. A package variable listed in a goose config's trusted gets its initializer X.init (allocation included) from Perennial/TrustedCode. A few of them do nothing (λ: <>, #()) although translated code is to read the variable once it is modelled (os.Stdout, log.std and math.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 runs c.init then d.init: goose cannot split the evaluation, so by convention the first variable's init carries 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 the review-trusted rule 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 translates internal/godebug, trusting its runtime hooks setUpdate and setNewIncNonDefault, with internal/bisect and internal/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; needs os.Stderr, so os's initialization), log's init (no-op; it writes log/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.Reader is translated over crypto/internal/rand, and crypto/ed25519.cryptocustomrand is a skip entry, which no translated code reads.) A function of the same standing (R2 REWORK, accepted 2026-11-23 to give math/rand's top-level functions proved specs): math/rand.globalRand, Go's body with its randautoseed.Value() == "0" test (a GODEBUG read) 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 translates internal/godebug (as for asynctimerchan) and the seeded path it then reaches (lockedSource, rngSource and its seeding over rngCooked). crypto/sha1's init (crypto.RegisterHash(crypto.SHA1, New)) is a trusted no-op for the same program-logic gap, as crypto/sha256's: crypto is not translated, so nothing translated reads its hash table (the user's decision, 2026-11-23). The no-op for math.useFMA (a CPU feature the runtime detects) models irreducible behaviour; errors.errorType and math/big.hasADX, the same kind, are skip entries. Each model's docstring says why it is faithful.

  • sync.Pool. Get and Put are a Go model (goose/model/overlay/sync/pool.go): the real ones rely on runtime pinning to a P, pointer arithmetic and eface layout reinterpretation. They keep Go's Put(nil) and New handling and replace the per-P pools by a lock-protected multiset (poolModel) installed in the pool's field local, where Put may drop its value and Get may ignore the pool. That is more nondeterministic than gc's pools, victim cache and GC clearing. The one primitive stub, poolModelAt (TrustedCode/sync.lean), converts local back to *poolModel.

  • sync.Mutex. Goose translates sync.Mutex (struct { _ noCopy; mu isync.Mutex }) and its methods, which forward to internal/sync.Mutex. That Mutex is Go's type, translated, and its Lock, TryLock and Unlock are 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 on state (0 is unlocked, 1 locked) over sync/atomic's compare-and-swap, more nondeterministic than Go's (no fairness or starvation mode, and TryLock may fail on an unlocked mutex, as Go's does in starvation mode or when its CAS loses to a waiter); Unlock of 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 by methodSet, an uninterpreted function of the semantics constrained by go.MethodSetIs t ms facts (Golang/Defn/MethodSet.lean): "the method set of t is exactly ms". goose emits them, for each named type T of a translated package, for T and *T in T.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 that typeSetContains needs 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 = on go.GoType must 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 of go.StructType: every field declaration (go.field_decl.Field/Embedded name type tag, the tag empty when there is none; the shorthands go.FieldDecl/go.EmbeddedField name type for 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 tag goose: 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) decides typeSetContains goals.

  • 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/ emits Perennial/Code/** and Perennial/GeneratedProof/**; regenerate with etc/update-goose-new.py rather than editing them by hand. The translation's Go toolchain is pinned to go1.26.11 (GO_VERSION there; the standard library goose translates is that toolchain's), and the script refuses another go.

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, use attribute [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 operators e1 +⟨t⟩ e2 etc. Method calls are rcvr @!! T @!! m.
  • Everything lives in namespace Perennial.
  • Every file is a module of Lean's module system: module, then its public 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 new axioms without discussing it first.
  • Notation: #x is intoVal x; m !! k, <[k := v]> m, {[k := v]} work on both gmap and List (on lists they are l[i]? and l.set i v); the set-valued domain of a map is domSet m; go!"abc" is a GoString literal; l +ₗ i is location offset.
  • Equality on GooseLang syntax and go.GoType is 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 is ExternalOp E.name "Op" ..., with no assumption, and ElemExt E/HasExt E (proofs about E) 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, default True), not of its ghost state: a top-level theorem assumes extsInitLocal/extsInitGlobal, through the adequacy theorems' _init versions (GooseLang/InitAdequacy.lean), which require each interpretation to accept them (ExtInitCompat). See docs/PERENNIAL_PROOF_REFERENCE.md, "Initial states of extensions".
  • An extension (GooseExt) requires Pos.Countable of its Val, and Loc, GoSlice, val, Expr, GoFunc, GoInterface, go.GoType, ... are Pos.Countable (Perennial/GooseLang/Countable.lean, via an injection into GenTree), 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.toml declares a second library, PerennialMeta, with precompileModules, listing the modules that define tactics, elaborators, notation or simprocs and everything they import (about 150 modules, rooted at the generated PerennialMeta.lean). After adding such a module, or changing the imports of one, run etc/meta-lib.py and commit the result; etc/lean-ci.sh and etc/land.sh prepare fail 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).

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…