Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ members = [
"beyond-pg-cdc",
"beyond-pg-core",
"beyond-pg-init",
"beyond-pg-kernels",
"beyond-pg-sink",
"wal-proto",
]
Expand All @@ -21,6 +22,7 @@ path = "src/main.rs"

[dependencies]
beyond-pg-core = { path = "./beyond-pg-core" }
beyond-pg-kernels = { path = "./beyond-pg-kernels" }
clap = { version = "4", features = ["derive"] }
quinn = "0.11"
rcgen = "0.14"
Expand Down
25 changes: 25 additions & 0 deletions beyond-pg-kernels/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[package]
name = "beyond-pg-kernels"
version = "0.1.0"
edition = "2024"
rust-version = "1.92"
license = "UNLICENSED"
description = "beyond-pg's pure decision kernels: no I/O, no clock, proven with Verus"

[lib]
name = "beyond_pg_kernels"

[features]
default = []
# `start::plan`: a start that runs post_start leaves the role's password as it was (a fork or restore keeps the source's hash). `cargo verus verify --features mut_start_keeps_stored_role` must go red.
mut_start_keeps_stored_role = []

[dependencies]
# The `verus!` macro and the spec library. A normal build erases every proof; only a `cargo verus` build checks them.
vstd = "=0.0.0-2026-11-01-0251"

[package.metadata.verus]
verify = true

[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(verus_only)'] }
3 changes: 3 additions & 0 deletions beyond-pg-kernels/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//! beyond-pg's pure decision kernels (no I/O, no clock), proven with Verus. The supervisor calls them; nothing here is restated elsewhere.

pub mod start;
72 changes: 72 additions & 0 deletions beyond-pg-kernels/src/start.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//! What a start of the database does about its role's password. Row: `P.secrets.a-postgres-role-password-is-the-served-value-on-every-start`
//! (Beyond repo): "A Postgres guest that holds a platform-generated password has its database role's password set to that value on every start, so a
//! fork or restore carrying the source's role hash authenticates with its own value and never the source's."
//!
//! A start is a cold start of the supervisor (a boot, a restart, a fork-branch or restore on a cloned volume: the data directory may carry any role
//! hash) or a successor taking over a running postgres (the same process, so the role is whatever this instance last set). A cold primary start runs
//! `post_start`, whose FIRST statement is `ALTER ROLE postgres WITH PASSWORD <served verifier>`; a replica is a read-only standby and runs none.
//! `plan` is called by `supervisor::run` (whether post_start runs) and by `supervisor::build_post_start_script` (whether it opens with the reset).
//! The served verifier is the one the driver hands the guest over the env relay (`beyond-pg-init/src/env_relay.rs`, a verifier or nothing).
//!
//! Liveness partner: `plan`'s ensures is an iff, so a primary cold start is always planned the reset (completeness), and the reset is idempotent
//! (`role_after` of `served` is `served`), so a retry after a failed post_start converges.

use vstd::prelude::*;

verus! {

/// What a start does.
#[derive(Clone, Copy)]
pub struct Plan {
/// `post_start` runs.
pub post_start: bool,
/// Its first statement sets the role's password to the served value.
pub reset_role: bool,
}

/// The role's password hash after a start that planned `p`, given the one the data directory held and the served one.
pub open spec fn role_after(stored: Option<Seq<u8>>, served: Seq<u8>, p: Plan) -> Option<Seq<u8>> {
if p.reset_role { Some(served) } else { stored }
}

/// The plan for a start: `replica` is a hot standby, `successor` a handover of a running postgres.
pub fn plan(replica: bool, successor: bool) -> (p: Plan)
ensures
p.post_start <==> (!replica && !successor),
// Every start that runs post_start resets the role first; none that skips it does.
p.reset_role <==> p.post_start,
{
let runs = !replica && !successor;
if cfg!(feature = "mut_start_keeps_stored_role") {
return Plan { post_start: runs, reset_role: false };
}
Plan { post_start: runs, reset_role: runs }
}

/// A primary's cold start, whatever the data directory carried (a fork's or restore's source hash among it), leaves the role with exactly the served
/// value: the source's hash, when it differs, is gone.
pub proof fn a_start_holds_the_served_value(stored: Option<Seq<u8>>, served: Seq<u8>)
ensures
({
let p = plan_spec(false, false);
role_after(stored, served, p) == Some(served)
&& (stored is Some && stored->Some_0 != served ==> role_after(stored, served, p) != stored)
}),
{
}

/// Retrying after a failed start converges: the reset applied twice is the reset applied once.
pub proof fn the_reset_is_idempotent(stored: Option<Seq<u8>>, served: Seq<u8>)
ensures
role_after(role_after(stored, served, plan_spec(false, false)), served, plan_spec(false, false))
== role_after(stored, served, plan_spec(false, false)),
{
}

/// The spec of `plan`'s answer.
pub open spec fn plan_spec(replica: bool, successor: bool) -> Plan {
let runs = !replica && !successor;
Plan { post_start: runs, reset_role: runs }
}

} // verus!
31 changes: 18 additions & 13 deletions src/supervisor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,8 +588,11 @@ async fn run_inner_inner(role: MaybeRole) -> Result<(), Box<dyn std::error::Erro
cold_start_wal_handle = wfh;

// Replicas are read-only hot standbys — DDL is rejected during recovery.
if cfg.pg_tier != PgTier::Replica {
post_start(&cfg).await?;
// The start's plan is the kernel's (beyond-pg-kernels/src/start.rs): which starts run post_start, and that it opens by setting the
// role's password to the served value, so a data directory carrying another instance's hash (a fork, a restore) takes this one's.
let start = beyond_pg_kernels::start::plan(cfg.pg_tier == PgTier::Replica, false);
if start.post_start {
post_start(&cfg, start).await?;
}

let mut pgb = ChildState::new("pgbouncer");
Expand Down Expand Up @@ -1819,7 +1822,7 @@ async fn wait_for_sync_standby(name: &str, timeout: std::time::Duration) {
// Post-start setup
// ---------------------------------------------------------------------------

async fn post_start(cfg: &MmdsConfig) -> Result<(), Box<dyn std::error::Error>> {
async fn post_start(cfg: &MmdsConfig, start: beyond_pg_kernels::start::Plan) -> Result<(), Box<dyn std::error::Error>> {
// Resolve the extensions to (idempotently) create: required + optional,
// filtered to those whose control file is present. A REQUIRED extension
// missing its control file is downgraded to a warning (the standalone image
Expand Down Expand Up @@ -1852,7 +1855,7 @@ async fn post_start(cfg: &MmdsConfig) -> Result<(), Box<dyn std::error::Error>>
// process spawns + reconnects. Every statement is idempotent and, on a
// well-formed image, a no-op or fast role op — so a failure is a real problem
// and rightly aborts post_start (→ restart).
pg::psql_script(&build_post_start_script(cfg, &extensions))
pg::psql_script(&build_post_start_script(cfg, start, &extensions))
.await
.map_err(|e| format!("post-start setup failed: {e}"))?;

Expand All @@ -1869,15 +1872,17 @@ async fn post_start(cfg: &MmdsConfig) -> Result<(), Box<dyn std::error::Error>>
/// per `extensions` → (when WAL consumers exist) replicator role + password →
/// (when CDC enabled) slot + publication. Every statement is `;`-terminated so
/// the whole thing runs as one `psql -f -` with `ON_ERROR_STOP=1`.
fn build_post_start_script(cfg: &MmdsConfig, extensions: &[&str]) -> String {
fn build_post_start_script(cfg: &MmdsConfig, start: beyond_pg_kernels::start::Plan, extensions: &[&str]) -> String {
let mut s = String::new();

// 1. Reset the superuser password from the per-instance MMDS secret.
s.push_str(&pg::alter_role_password_sql(
"postgres",
&cfg.postgres_password,
));
s.push_str(";\n");
if start.reset_role {
s.push_str(&pg::alter_role_password_sql(
"postgres",
&cfg.postgres_password,
));
s.push_str(";\n");
}

// 2. pgbouncer auth (role + SECURITY DEFINER lookup function + grants).
s.push_str(crate::sql::PGBOUNCER_AUTH_SQL);
Expand Down Expand Up @@ -2286,7 +2291,7 @@ mod tests {

#[test]
fn post_start_script_is_one_terminated_batch() {
let s = build_post_start_script(&pg_cfg(None, None, false), &["vector", "postgis"]);
let s = build_post_start_script(&pg_cfg(None, None, false), beyond_pg_kernels::start::plan(false, false), &["vector", "postgis"]);
// superuser password (dollar-quoted) + pgbouncer auth, each terminated.
assert!(s.contains("ALTER ROLE postgres WITH PASSWORD $_beyond_$s3cr3t$_beyond_$;"));
assert!(s.contains("CREATE SCHEMA IF NOT EXISTS pgbouncer;"));
Expand All @@ -2304,7 +2309,7 @@ mod tests {
#[test]
fn post_start_script_adds_replicator_and_cdc_when_enabled() {
// WAL sink ⇒ replicator role (no password set); CDC ⇒ slot + publication.
let s = build_post_start_script(&pg_cfg(Some("rpw"), Some("http://sink:9000"), true), &[]);
let s = build_post_start_script(&pg_cfg(Some("rpw"), Some("http://sink:9000"), true), beyond_pg_kernels::start::plan(false, false), &[]);
assert!(s.contains("CREATE ROLE replicator LOGIN REPLICATION PASSWORD NULL"));
assert!(s.contains("ALTER ROLE replicator WITH PASSWORD $_beyond_$rpw$_beyond_$;"));
assert!(s.contains("pg_create_logical_replication_slot('cdc'"));
Expand All @@ -2315,7 +2320,7 @@ mod tests {
#[test]
fn post_start_script_replicator_without_password_when_only_sink() {
// wal_sink alone creates the role but sets NO password (PASSWORD NULL).
let s = build_post_start_script(&pg_cfg(None, Some("http://sink:9000"), false), &[]);
let s = build_post_start_script(&pg_cfg(None, Some("http://sink:9000"), false), beyond_pg_kernels::start::plan(false, false), &[]);
assert!(s.contains("CREATE ROLE replicator"));
assert!(!s.contains("ALTER ROLE replicator WITH PASSWORD"));
}
Expand Down