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
2 changes: 2 additions & 0 deletions beyond-pg-kernels/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ name = "beyond_pg_kernels"
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 = []
# `start::plan`: a promotion does not reset the role (the replicated hash is served as the new primary). Red in Verus.
mut_promotion_skips_reset = []

[dependencies]
# The `verus!` macro and the spec library. A normal build erases every proof; only a `cargo verus` build checks them.
Expand Down
92 changes: 61 additions & 31 deletions beyond-pg-kernels/src/start.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,42 @@
//! 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."
//! What a start of the database does about its role's password. Row: "On every start the server's role holds the deployment's current
//! credential: a primary start resets it before serving, a replica serves only the role its primary replicated, and a promoted replica
//! resets it before it serves as primary." (`P.secrets.a-postgres-role-password-is-the-served-value-on-every-start`, Beyond repo.)
//!
//! 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).
//! The kinds of start ([`StartKind`]): a cold start of a primary (a boot, a restart, a fork-branch or restore on a cloned volume: the data
//! directory may carry any role hash) runs `post_start`, whose FIRST statement is `ALTER ROLE postgres WITH PASSWORD <served verifier>`; a replica
//! is a read-only standby that serves the role its primary replicated (the primary reset it) and runs nothing; a successor takes over a running
//! postgres (the same process, so the role is whatever this instance last set); a promotion (`pg_ctl promote`, the `promote` RPC) makes a replica
//! a primary, and the RPC answers ok only after the reset (`ALTER ROLE` alone: the rest of `post_start` was replicated).
//! `plan` is called by `supervisor::run` (cold start and replica: whether post_start runs, whether it opens with the reset), by
//! `supervisor::build_post_start_script`, and by `rpc::dispatch` for `promote`. The served verifier is the one the driver hands the guest
//! over the env relay, read from MMDS at the start (at promotion: at the promotion).
//!
//! 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.
//! Liveness partner: `plan`'s ensures is an iff, so a primary cold start and a promotion are always planned the reset (completeness), and the
//! reset is idempotent (`role_after` of `served` is `served`), so a retry after a failed post_start or a failed reset converges.

use vstd::prelude::*;

verus! {

/// The kinds of start.
#[derive(Clone, Copy)]
pub enum StartKind {
/// A cold start of a primary: a boot, a restart, a fork-branch or a restore.
Cold,
/// A cold start of a hot standby.
Replica,
/// A successor taking over a running postgres.
Successor,
/// A replica promoted to primary.
Promotion,
}

/// 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.
/// The role's password is set to the served value, before the server serves as a primary.
pub reset_role: bool,
}

Expand All @@ -29,44 +45,58 @@ pub open spec fn role_after(stored: Option<Seq<u8>>, served: Seq<u8>, p: Plan) -
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)
/// The plan for a start.
pub fn plan(kind: StartKind) -> (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,
p == plan_spec(kind),
// A cold primary start runs post_start, which resets the role first.
kind is Cold ==> p.post_start && p.reset_role,
// A promoted replica resets the role before it serves as primary (and runs no post_start: its setup was replicated).
kind is Promotion ==> p.reset_role && !p.post_start,
// A replica serves only the role its primary replicated; a successor is the same process.
(kind is Replica || kind is Successor) ==> !p.reset_role && !p.post_start,
// Every start that serves as a primary with a role of unknown origin resets it, and no other does.
p.reset_role <==> (kind is Cold || kind is Promotion),
{
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 }
let reset = match kind {
StartKind::Cold => !cfg!(feature = "mut_start_keeps_stored_role"),
StartKind::Promotion => !cfg!(feature = "mut_promotion_skips_reset"),
StartKind::Replica | StartKind::Successor => false,
};
Plan { post_start: matches!(kind, StartKind::Cold), reset_role: reset }
}

/// 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>)
/// value: the source's hash, when it differs, is gone. The same holds at a promotion, whatever the replicated hash was.
pub proof fn a_start_holds_the_served_value(stored: Option<Seq<u8>>, served: Seq<u8>, kind: StartKind)
requires
kind is Cold || kind is Promotion,
ensures
({
let p = plan_spec(false, false);
let p = plan_spec(kind);
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>)
/// A replica serves exactly the role it was given: the primary's, which the primary's own reset set.
pub proof fn a_replica_serves_the_replicated_role(stored: Option<Seq<u8>>, served: Seq<u8>)
ensures
role_after(stored, served, plan_spec(StartKind::Replica)) == stored,
{
}

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

/// 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 }
pub open spec fn plan_spec(kind: StartKind) -> Plan {
Plan { post_start: kind is Cold, reset_role: kind is Cold || kind is Promotion }
}

} // verus!
12 changes: 12 additions & 0 deletions beyond-pg-kernels/tests/plan.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use beyond_pg_kernels::start::{StartKind, plan};

#[test]
fn a_cold_start_and_a_promotion_reset_the_role_and_nothing_else_does() {
assert!(plan(StartKind::Cold).post_start && plan(StartKind::Cold).reset_role);
let promoted = plan(StartKind::Promotion);
assert!(promoted.reset_role && !promoted.post_start);
for kind in [StartKind::Replica, StartKind::Successor] {
let p = plan(kind);
assert!(!p.reset_role && !p.post_start);
}
}
5 changes: 5 additions & 0 deletions src/pg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,11 @@ pub async fn basebackup(conninfo: &str) -> Result<(), PgError> {
/// under normal conditions completes in under 1 second.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub async fn promote() -> Result<(), PgError> {
// A retry after a promotion that completed (its role reset failed) finds no standby.signal: promoted already, nothing to do.
if !std::path::Path::new(&format!("{PGDATA}/standby.signal")).exists() {
tracing::info!("pg_ctl: already promoted (no standby.signal)");
return Ok(());
}
tracing::info!("pg_ctl: promoting standby to primary");
let out = Command::new("pg_ctl")
.args(["promote", "-w", "-t", "55", "-D", PGDATA])
Expand Down
19 changes: 18 additions & 1 deletion src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,18 @@ mod inner {
Ok(())
}

/// The role reset a promotion owes before the node serves as primary (`beyond_pg_kernels::start::plan(Promotion)` decides it): the
/// role's password becomes the deployment's current credential, read from MMDS now. Idempotent: a retry sets the same value.
async fn reset_role_after_promotion() -> Result<(), String> {
use beyond_pg_kernels::start::{StartKind, plan};
if !plan(StartKind::Promotion).reset_role {
return Ok(());
}
let cfg = crate::mmds::read().await.map_err(|e| e.to_string())?;
let sql = format!("{};\n", crate::pg::alter_role_password_sql("postgres", &cfg.postgres_password));
crate::pg::psql_script(&sql).await.map_err(|e| e.to_string())
}

async fn dispatch(cmd: &str, pooler: &crate::handoff_bridge::PoolerStatsHandle) -> RpcResponse {
match cmd {
"checkpoint" => match crate::pg::psql("CHECKPOINT").await {
Expand All @@ -224,8 +236,13 @@ mod inner {
Ok(()) => RpcResponse::ok(),
Err(e) => RpcResponse::err(e.to_string()),
},
// ok:true means a writable primary whose role holds the deployment's current credential: the reset
// (beyond-pg-kernels start::plan(Promotion)) runs before the answer, so a retry after a failure converges.
"promote" => match crate::pg::promote().await {
Ok(()) => RpcResponse::ok(),
Ok(()) => match reset_role_after_promotion().await {
Ok(()) => RpcResponse::ok(),
Err(e) => RpcResponse::err(format!("promoted, but the role reset failed: {e}")),
},
Err(e) => RpcResponse::err(e.to_string()),
},
"backup" => RpcResponse::err("not implemented"),
Expand Down
8 changes: 4 additions & 4 deletions src/supervisor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ async fn run_inner_inner(role: MaybeRole) -> Result<(), Box<dyn std::error::Erro
// Replicas are read-only hot standbys — DDL is rejected during recovery.
// 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);
let start = beyond_pg_kernels::start::plan(if cfg.pg_tier == PgTier::Replica { beyond_pg_kernels::start::StartKind::Replica } else { beyond_pg_kernels::start::StartKind::Cold });
if start.post_start {
post_start(&cfg, start).await?;
}
Expand Down Expand Up @@ -2291,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), beyond_pg_kernels::start::plan(false, false), &["vector", "postgis"]);
let s = build_post_start_script(&pg_cfg(None, None, false), beyond_pg_kernels::start::plan(beyond_pg_kernels::start::StartKind::Cold), &["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 @@ -2309,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), beyond_pg_kernels::start::plan(false, false), &[]);
let s = build_post_start_script(&pg_cfg(Some("rpw"), Some("http://sink:9000"), true), beyond_pg_kernels::start::plan(beyond_pg_kernels::start::StartKind::Cold), &[]);
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 @@ -2320,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), beyond_pg_kernels::start::plan(false, false), &[]);
let s = build_post_start_script(&pg_cfg(None, Some("http://sink:9000"), false), beyond_pg_kernels::start::plan(beyond_pg_kernels::start::StartKind::Cold), &[]);
assert!(s.contains("CREATE ROLE replicator"));
assert!(!s.contains("ALTER ROLE replicator WITH PASSWORD"));
}
Expand Down