Skip to content

31. A verified REPL over a reusable session, with proved live redefinition

Date: 2026-11-21

Status: Proposed

Context

Dean wants Pia usable interactively, building up an environment the way a Lisp REPL does: each definition joins a persistent environment, and later input can use and redefine it. Claude should be able to drive it too, so it needs a scriptable mode with machine-readable output, then an MCP server with just two tools, execute and poll, in the style of Code Mode. The planned Jupyter kernel (#64) needs the same core.

Dean also wants code sent to the REPL to change the environment the way Lisp code can, including metaprograms that modify live, running code. Two constraints come with that. Every live transformation must be proved safe with all of the language's verification facilities: there are no unchecked hot-swaps. And the live facilities belong to the REPL, which is a self-contained programming environment. Pia.Rt must not carry them, so a normal compiled program has none of that machinery unless it explicitly imports it.

Three existing rules shape the design:

  • Unproved obligations are compile errors unless a flag accepts specific ones (ADR 0004, --allow-unproved).
  • There is no shadowing, even in nested scopes (ADR 0022). A Lisp REPL rebinds a name freely; Pia cannot.
  • Interfaces evolve by proved refinement: a new version is compatible with an old one when it has the same types and layout, a weaker requires and a stronger ensures (ADR 0024). Layout has its own hashes, and a layout change costs a relink, never a re-proof (ADR 0030, proposed).

Prior art: OCaml's toplevel and utop keep a typed environment and allow shadowing. Common Lisp and Clojure redefine through a global indirection (the symbol's function cell, or a var) so running code picks up new definitions at the next call. Erlang hot code loading keeps two versions of a module, and processes move to the new one at their next external call. Julia's world age makes new definitions visible only at the top level, so a running function keeps seeing the methods it started with. Dafny and F* have IDE modes that re-verify on each edit but no live environment.

Decision

The session is the core

  • pia::repl::Session holds the environment and runs cells. A cell is Pia code or a :command. The environment is the list of top-level items that earlier cells committed, kept as source. Each cell is parsed together with the environment (so operators and metaprograms declared earlier apply), expanded to a fixed point, lowered and verified as one program.
  • Cells are transactions. A cell is committed only if the whole environment plus the cell verifies: every obligation is proved, or accepted by :allow (the REPL's --allow-unproved). Otherwise nothing changes and the cell's failures, counterexamples and unproved goals come back as events. So the environment is always a program that verifies.
  • Expressions are evaluated only after they are proved. An expression in a cell becomes a hidden constant, is verified like any definition (a call outside a precondition fails before anything runs), then compiled through the normal codegen pipeline and run with the ORC JIT through MLIR's ExecutionEngine. Its value and type are shown. Constants that a cell defines are evaluated the same way. Evaluation always terminates, because termination is one of the obligations (decreases); only :allow can admit code that might not.
  • Front ends only render events. Session::execute returns a list of typed events (defined, redefined, removed, value, type, proof, error, info). pia repl renders them as text; pia repl --json speaks one JSON object per line in each direction; the MCP server and the Jupyter kernel serialise the same events.
  • pia::repl::Kernel makes it asynchronous. It runs a session on a worker thread, takes cells as numbered jobs and lets callers poll them with a timeout. That is exactly the shape of the MCP tools: execute submits a cell and waits briefly, returning the result or a job handle, and poll waits for a handle. Jupyter's execute_request maps onto the same calls.

Redefinition under the no-shadowing rule

  • Defining a name that exists is an error, with the ADR 0022 message: rename it x', or replace it.
  • :redef replaces a definition explicitly. The old item is removed and the new one is checked in its place, together with everything else, so every dependent is re-verified against the new definition. If any dependent's proof breaks, the redefinition is refused and the error lists the dependents that use it. :forget removes a definition the same way, and is refused while anything uses it.
  • A name generated by a metaprogram call belongs to that call: redefining it means redefining the call.

Live redefinition

The first version re-verifies and recompiles the whole environment for each cell, and each evaluation runs to completion before the next cell, so nothing runs while the environment changes. Live redefinition, where a cell or a metaprogram replaces a function while tasks are still running it, keeps the same soundness argument by classifying each change:

  1. A refinement swaps in place. If the new definition has the same type and layout, its requires is implied by the old one's, and its ensures implies the old one's under the old requires, it refines the old interface (the ADR 0024 check, run by the verifier). Every dependent's proof assumed only the old contract, so all of them still hold without re-verification. The new code is installed behind the function's indirection slot with one atomic store; calls that start after the store run the new code, and frames already running finish on the old code, which stays mapped until no frame uses it (an epoch counter per code version, reclaimed when its count drops to zero).
  2. Any other contract change re-verifies its dependents, transactionally. The new definition and every transitive dependent are verified together against the new contract. If all of them hold, the whole set is swapped at once, at a point where none of them has a frame on any task's stack (the runtime waits for, or asks for, that quiescent point). If any fails, nothing changes.
  3. A change of type or layout is a relink. The layout and shape hashes of ADR 0030 change, so every dependent is recompiled from its verified IR, and its proofs are reused when the interface hash did not change. A live value of the old layout can only cross over through a migration function from the old type to the new one, which is itself verified (total, and preserving any invariant the new type states). Without one, the change is refused while values of the old type are alive.
  4. Module state invariants must hold across the swap. When a function belongs to a module with state invariants (ADR 0006), the swap happens only between calls into the module, where the invariant is known to hold, and the new definitions must preserve the same invariant.

In each case the REPL session holds a certificate for its environment, as a library does under ADR 0024: one interface hash per definition, recorded with the hashes its proofs assumed. A swap updates the certificate in the same transaction, so :proof always shows what the running code is proved against.

What is built

The first live phase is built (docs/repl.md, "Live redefinition"):

  • Tasks. :spawn e runs an evaluation on its own thread; :tasks lists them and :wait n waits for one. A task's reach is every definition its expression can call, through the environment's references.
  • Slots. In the REPL, every call from one definition to another loads the callee's address from a slot with an acquire load and calls it indirectly. Each cell's code is compiled into its own engine, and its addresses are stored into the slots with release stores. An engine stays alive while any task that might run its code is alive, which is a coarser form of the per-version epoch above.
  • The refinement rule, as built. When :redef (or a metaprogram) replaces a definition in a running task's reach, the new definition must have the same shape (parameter count, kinds and types, and result type), and its body must be proved against the old contract: a hidden function with the new body and the old requires and ensures (renamed to the new parameter names) goes through the verifier with everything else. This is case 1, checked directly instead of by comparing contracts, so a new body that meets the old contract is accepted even when its own contract changed. If it holds, the new code is swapped in; otherwise nothing is committed and the error names the task and the failing claim.
  • Cases 2 and 3, for code. A change that does not refine, or that changes a function's type (including through a record type it uses, since shapes compare types in full), is verified with everything else as usual. Then the changed definitions and every definition that calls one of them, in its old or new version, are swapped together at a quiescent point. Code a task may run counts its calls in progress in a per-definition gate: before it loads the callee's slot, a call adds one to the callee's counter with a sequentially consistent atomic add and checks the gate's flag, and it subtracts one when it returns. To swap, the session sets the flag on every gate in the set, waits until all of their counters are zero, stores the new code into the slots, and clears the flags. While a flag is set, a call into the set from a definition outside it backs out and waits, while a call from inside the set goes ahead so that the set drains. If the set does not drain within quiesceMs (two seconds), nothing is committed, and the error names the definitions the task never left. Callers outside the set relied only on contracts that did not change, so their running frames stay valid. This is sound because every frame of the set either finished before the swap or starts after it: no frame runs old code proved against a contract that no longer holds.
  • State, migration and invariants (cases 3 and 4). The REPL has state: a top-level let count : mutable u8 invariant count <= 100 = 0 keeps its value between cells (docs/repl.md, "State"). It stands in for module state until M8, with the same proof obligations:
  • Every definition that uses a state, directly or through a call, takes it as a borrowed inout mutable one-element buffer, requires its invariant and ensures it, has it as an invariant of each of its loops, and ensures the state unchanged if it never writes it. The rewrite needs no new verifier support, and the no-shadowing rule makes it exact: a state's name means the state wherever it appears.
  • Live values migrate through a verified function. A redefinition whose initial value names old count becomes a hidden function of the old value that requires the old invariant and ensures the new one. Proving it shows that every value the old invariant allows maps to one the new type and invariant allow. The session runs it on the stored value, and commits only if it was proved. Without old, a redefinition starts again from its initial value.
  • Invariants hold across swaps. A state belongs to the running task that uses it until the task finishes: the session cannot read, write, redefine, migrate or forget it in the meantime, so a migration never races with code running on the old value. The functions that use the state can be swapped while the task runs. Their contracts include the invariant, so a refinement keeps it, and a contract change waits for a quiescent point as above. Either way, a swap happens between calls, where the invariant is known to hold, and the new code is proved to preserve it.
  • Not yet. A state of a record or array type, and module state in compiled programs (M8). :forget or :reset of anything a task can reach waits for the task.
  • Pia.Live. The metaprogram builtin redefine marks the items it returns as redefinitions, so a metaprogram can replace live code through the same checked path as :redef. Only the REPL enables it; piac reports it as an error.

The environment as data

Metaprograms in the REPL can read and change the environment, as Lisp code can: list its definitions as syntax, fetch one, and define, redefine or forget items. These builtins belong to a REPL-only module, Pia.Live. A metaprogram's changes go through exactly the same path as a typed cell: the result is a transaction that is verified before it is committed, under the rules above. Nothing a metaprogram does can install unverified code.

Kept out of ordinary programs

The session, the JIT, the indirection slots and Pia.Live are part of the REPL tool, not of the language runtime. Pia.Rt does not contain them, ordinary compiled programs call functions directly with no indirection, and code that wants live redefinition must import Pia.Live explicitly, which only the REPL (or a program that deliberately embeds it) provides.

Teaching the language (amendment, 2026-11-23)

Dean asked that the MCP server also teach Pia's syntax and semantics, so that an agent connected to it, with or without the skills loaded, wastes fewer cells and less context. The server still has exactly two tools; the teaching goes through the surfaces MCP already has and through execute:

  • instructions are a primer of under 2 KB (skills/pia-mcp/instructions.md), with the list of guide topics. Clients put them in the agent's context at connection, so they cost every session, and they hold only what prevents the most failed cells.
  • :help <topic> is a REPL command, so it works in every client and in pia repl. Each topic is one section of the pia-language, pia-contracts or pia-mcp skill. The same text is served as MCP resources, pia://guide/<topic>, for clients that attach resources. A new tool for it was rejected: it would add a schema to every session for something one command already does.
  • Hints. A failed cell's result ends with one line per kind of failure, recognised by the diagnostic's wording, saying the fix and the topic. They are added by the MCP server only, so pia repl's text, which the docs' console blocks check, is unchanged.

The guide is not a second copy. src/repl/embed_guide.py cuts it from the skills when the server is built, and fails the build when a skill gains a section that is neither a topic nor deliberately skipped. The skills' examples are already proved by //tests/docs:skills_test, so what the server teaches is checked against the compiler.

Consequences

  • Every value the REPL prints comes from code that was proved first, so the REPL teaches the language's main rule rather than bending it.
  • Each cell re-verifies the whole environment. That is simple and obviously sound, and fast enough for interactive sizes; caching proofs per definition by interface hash is the planned optimisation.
  • The MCP server and the Jupyter kernel are thin layers over Kernel, with no second implementation of the language.
  • Live redefinition reuses the refinement check that shared libraries need anyway, so the REPL and ADR 0024 share one notion of compatible change.
  • Running code that is swapped out keeps running on its old version until it returns, so a long-running task sees a consistent set of definitions, much like Julia's world age.
  • Mutable top-level state, I/O and the concurrency runtime do not exist yet; when they arrive, quiescent points and migration functions become runtime work, not just compile-time checks.