A general-purpose, offline-first sync engine that knows nothing about your
domain. examples/todo is the worked example it is exercised with — a to-do list,
compiled both natively and to wasm, which is what lets conformance.rs prove
those two builds agree.
A server owns an append-only, totally ordered log of mutations. Mutations are
intents, not facts — AddToList { list, items }, never
ItemInserted { pos: "a5" } — and apply may read the database to decide what
to write. A client's view is always:
replay(confirmed) then replay(pending)
Confirmed state only moves forward, because the log is never reordered. The only thing ever undone is the client's own pending mutations, replayed on top after confirmed entries land. That is the rebase, and it is the whole concurrency story: no CRDTs, no vector clocks, no merge functions.
applymust be a pure function of(transaction state, arguments). No clock, no RNG, no network, no filesystem. ExplicitORDER BYon every query — SQLite's natural order is not a contract. No floats in control flow.- All non-determinism goes through
AutoCtx, infill_auto, exactly once, at the originating client. It is then frozen in the log forever. - The log is permanent. Never rename or remove a mutation variant, never change
a field's type; add fields with
#[serde(default)].tests/wire.rspins this against a checked-in byte fixture — if it fails, the change would have broken every existing installation. An app's mutations are held to the same rule by a machine rather than by memory:petros_schema::compatcompares the built module against a recorded surface, every app's flake runs it ascheck-log, andnix run .#log-snapshotis how that surface moves on purpose. - Petros owns every transaction boundary. Never call Diesel's
Connection::transactionon a client's connection: the optimistic savepoint outlives any single call, so boundaries are raw SQL throughbatch_execute. - Petros owns tables prefixed
petros_. The app owns everything else. - The server decides who a connection is, once, at
Hello, throughAuthenticate; every entry it pushes is held to that.Trustingis the one authenticator that asks nothing, for a simulation or a test. petros::clientandpetros::serverare sans-io: no sockets, no async, no runtime. That is what makes the deterministic simulation tests possible. The transport module is the only place networking lives — and therefore the only place a keepalive can live, since the engine has no clock to hang one on.- The realtime channel is not the log and never becomes it.
petros::livecarries what is true now — who is playing, how far in — on the same socket, in a room per account, held in the server's memory. Nothing replays a live frame, so none of the log's compatibility rules bind one; and nothing about the view is touched by one, which is deliberate and load-bearing (a report a second would otherwise re-hydrate every maintained view on a timer).
crates/petros/ the engine
client.rs the savepoint rebase — the least obvious code here
server.rs assigns sequence numbers, dedupes, fans out
store.rs, schema.rs the four petros_ tables, as Diesel models
live.rs the *other* channel on the same socket: rooms,
and what is true in one right now. Never the log
backend.rs SqliteStore — compiles a query to one statement,
and reports what every write changed
transport/{ws,web}.rs thin, replaceable; ws = native, web = browser
crates/petros-schema/ the app contract: the `Store` a mutation writes
through, the query builder, and the `Change` a
write reports. No deps
crates/petros-sql/ `tables!` — row types, typed columns and
relationships, generated by asking SQLite what is
in `schema.sql`. A proc macro, so none of it ships
crates/petros-ivm/ incremental views: source, filter, join, take, and
a `View` that holds the answer and says what moved
crates/petros-wasm-guest/ `export!` — an app's wasm crate is one line
crates/petros-wasm-host/ wasmi, for a peer that replaces `apply` at runtime.
Knows nothing about any domain
crates/petros-codegen/ reads a module's schema section, writes TypeScript;
`log-compat` holds an app's mutations to what the
log already carries
crates/petros-axum/ one handler; the app keeps its routes
crates/petros-auth/ who a peer is: OpenID Connect on the server, the
sessions it issues, and how each client gets one
crates/petros-testkit/ the seeded in-process network, generic over an app
nix/lib/ what an app builds with: the crate list, the
`[patch]`, the code generator, the wasm module
nix/app/ an app's flake, minus the app: `lib.mkApp`
modules/ the flake, one flake-parts module per file
examples/todo/ the worked example
schema.sql, src/schema.rs the model
src/functions.rs every mutation and query, each written once
examples/ offline and multiplayer (TUI), iced (native + web)
web/ the browser shell, published to GitHub Pages
docs/decisions.md why everything is the way it is — read this first
just # fmt, lint, test
just test # must stay under 30s
just mutators # rebuild the wasm module and its TypeScript types
just web # the browser peer, at localhost:8080
just offline # a client with no server in existence
just serve # one server…
just peer alice # …a TUI peer…
just iced bob # …a desktop GUI peer…
just web # …a browser peer, at localhost:8080
Take any of them offline, mutate on both sides, come back — that is the rebase, visible.
../harken is one. An app is two files: schema.rs is petros_sql::tables!()
over its schema.sql, and functions.rs is every mutation and query written
once as an ordinary Rust function. petros::app! wires dispatch,
petros_wasm_guest::export! gives the wasm build, petros-axum serves it, and
petros-testkit runs it against a simulated fleet, and petros-auth signs
people in — OpenID Connect on the server, one URL and one code on every
client — and is what the hub is opened with.
A mutation takes ctx: &Ctx to know who authored the entry (ctx.user.id)
and under which login (ctx.session.id); both are frozen with the entry and
checked by the server against the login that pushed it. Actor is the short
form, ctx.user.id as a &str.
When an existing table's shape changes, bump App::SCHEMA_VERSION (it defaults
to 0, off). On the next open Petros rebuilds the app's tables from the log — it
drops them, recreates them at the new shape, and replays every entry through
apply — because they are a function of the log, not a separate store to
back-fill. A new table or index needs no bump (CREATE … IF NOT EXISTS). An
older client meeting a newer server is a separate question; see
docs/decisions.md.
There is no SQL in an app. Reads and writes are the same shape over the
generated row types, a write reports what it changed, and a relationship comes
from the DDL's REFERENCES rather than from a join:
db.put(&Song { .. })?; // reports an Add
db.select(Song::all().filter(Song::done.eq(false))) // one statement
db.select_with(Song::all(), Song::favorite, Favorite::all()) // a treeA client that would otherwise re-read a list on every change holds a
petros::ivm::View instead: hydrate it once, hand it Client::take_changes(),
and splice a rendered list from the patches it returns. Changes::Rebuilt is
the case that cannot be a list — a rebase rolls state back, and a rollback
reports nothing — so it asks for a re-hydrate rather than lying.
Depend on these by path while they are unpublished:
petros = { path = "../petros/crates/petros" }An app's flake.nix is four lines: nixpkgs, this repository, and
outputs = inputs: inputs.petros.lib.mkApp inputs ./.;. mkApp is
flake-parts over every *.nix under the app's root — the dendritic pattern,
import-tree over the tree — plus nix/app here, which is what every app
shares: the toolchain, the workspace, the three checks and their nix run
twins, the devshell, the wasm module a domain compiles to when the app
sets petros.mutators, and a README.md assembled from the readme.nix
beside each directory's nix (readme.intro, readme.sections.<name>). Which directories exist is what wires the rest, each
through its own nix/: a server/nix adds a server, a mobile/nix adds a
phone (from petros-js), and a program with neither is a crate and that
flake.nix.
The app's Cargo.toml is the one place the engine is pinned.
nix/app/workspace.nix reads the revision back and fetches this repository
at it — the crates for the [patch], petros-codegen for the module, and
rust-toolchain.toml for the toolchain — so the app's petros input is only
the code that reads Cargo.toml, and bumping the engine is editing that file.
What a directory contributes to the workspace — libraries the checks need,
tools and a hook for the shell, paths a cross-compile reads — goes through
the petros.* options in workspace.nix.
flakeModules.default puts the library alone — engineCrates,
mkCargoPatch, mkCodegen, mkMutators — in scope of a flake-parts flake;
lib.mkPetros pkgs is the same for one that is not, and nix/default.nix for
no flake at all.
Building an app for a phone is not here. petros-js knows about uniffi,
ubrn and Expo, and builds on expo.nix and android.nix; this repository
knows about none of them. What it does know is its own lockfile: mkCodegen
carries the hash of this repository's vendored dependencies, so
nix build .#codegen here is what says the hash is still right — and the
first thing to run after touching Cargo.lock.
CCin the environment hijacks the wasm build.cc-rsfalls back to plainCC, and gcc cannot target wasm; the failure appears as pages of errors inside glibc headers. The web recipe setsCC_wasm32_unknown_unknown.- nix's wrapped clang injects the system's glibc includes and fails the same
way; the devshell passes an unwrapped one plus
-resource-dir, because an unwrapped clang cannot find its ownstddef.h. - The wasm-bindgen CLI must match
Cargo.lockexactly. The recipe fetches the right version intotarget/rather than trustingPATH. - iced embeds no font by default. Without the
fira-sansfeature a browser draws no glyphs at all, while widgets and input work — so it looks like a renderer bug and is not one. default-features = falsehas to be said in the workspace entry too. A member cannot subtract what[workspace.dependencies]asked for, and nothing warns. It put Diesel and SQLite in the wasm graph for weeks.- A build that compiles is not evidence anything works.
SystemTime::now()panics on wasm and only surfaced when a mutation actually ran in a browser. - An id argument must say what it identifies.
Id<Playlist>, notId— see "An id knows what it identifies" indocs/decisions.md. The tag comes from the DDL'sREFERENCES, and the type in a signature has to be the row type astables!generated it: an alias makes the macro guess a table that does not exist, which is a compile error naming both rather than a silent wrong declaration. - A test can pass for the wrong reason, and three here did. Each time the assertion was satisfied by a path other than the one under test. Falsify every new test by breaking the thing it claims to check; it costs a minute and has not once been wasted.