From 4c231486825da4f92eb29a0b4c968e7432152256 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 28 Nov 2026 15:23:53 -0800 Subject: [PATCH] supervisor: a promoted replica resets the role's password before it serves as primary start::plan takes a StartKind (Cold, Replica, Successor, Promotion); the promote RPC answers ok only after the reset, and a retry after a failed reset converges (an already-promoted node skips pg_ctl promote). Verus ensures over every kind; mut_promotion_skips_reset red. Co-Authored-By: Claude Sonnet 5.5 --- beyond-pg-kernels/Cargo.toml | 2 + beyond-pg-kernels/src/start.rs | 92 ++++++++++++++++++++++----------- beyond-pg-kernels/tests/plan.rs | 12 +++++ src/pg.rs | 5 ++ src/rpc.rs | 19 ++++++- src/supervisor.rs | 8 +-- 6 files changed, 102 insertions(+), 36 deletions(-) create mode 100644 beyond-pg-kernels/tests/plan.rs diff --git a/beyond-pg-kernels/Cargo.toml b/beyond-pg-kernels/Cargo.toml index 0f153e1..4c26f3e 100644 --- a/beyond-pg-kernels/Cargo.toml +++ b/beyond-pg-kernels/Cargo.toml @@ -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. diff --git a/beyond-pg-kernels/src/start.rs b/beyond-pg-kernels/src/start.rs index e9b34f2..75e474b 100644 --- a/beyond-pg-kernels/src/start.rs +++ b/beyond-pg-kernels/src/start.rs @@ -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 `; 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 `; 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, } @@ -29,44 +45,58 @@ pub open spec fn role_after(stored: Option>, served: Seq, 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>, served: Seq) +/// 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>, served: Seq, 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>, served: Seq) +/// 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>, served: Seq) + 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>, served: Seq, 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! diff --git a/beyond-pg-kernels/tests/plan.rs b/beyond-pg-kernels/tests/plan.rs new file mode 100644 index 0000000..645064e --- /dev/null +++ b/beyond-pg-kernels/tests/plan.rs @@ -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); + } +} diff --git a/src/pg.rs b/src/pg.rs index 085253c..6c44995 100644 --- a/src/pg.rs +++ b/src/pg.rs @@ -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]) diff --git a/src/rpc.rs b/src/rpc.rs index b07e1fd..0c629dd 100644 --- a/src/rpc.rs +++ b/src/rpc.rs @@ -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 { @@ -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"), diff --git a/src/supervisor.rs b/src/supervisor.rs index 359b0fc..9714fd0 100644 --- a/src/supervisor.rs +++ b/src/supervisor.rs @@ -590,7 +590,7 @@ async fn run_inner_inner(role: MaybeRole) -> Result<(), Box