feat: version-specific pg_restore failure reasons, keep pg_stat_statements, explain reconcile conflicts

- pg_restore's stderr is kept; the archive header names the pg_dump that wrote it, and a newer one than
  the local client gives 'install a PostgreSQL client >= N' before any safety backup is taken
- omit_pg_stat_statements recreates the extension the target had, where it lived
- reconcile on a job that needs no recovery answers 409 with a reason
- proven against a real PostgreSQL server (real archive header, extension kept, mutation caught)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 14:46:37 +07:00
parent b104aa8053
commit 76999f06b8
4 changed files with 440 additions and 12 deletions

View File

@@ -1702,3 +1702,40 @@ async fn a_restore_safety_copy_never_pushes_a_production_capture_out_of_retentio
assert!(vault.get_snapshot(capture).unwrap().is_some()); assert!(vault.get_snapshot(capture).unwrap().is_some());
assert!(vault.get_snapshot(safety[0]).unwrap().is_some()); assert!(vault.get_snapshot(safety[0]).unwrap().is_some());
} }
#[tokio::test]
async fn reconciling_a_job_that_needs_no_recovery_says_so() {
let lab = fresh().await;
lab.start(&lab.admin(), "reconcile").await;
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, _token) = lab.restore_until_ready().await.unwrap();
let uri = format!("/api/v1/restore-jobs/{job}/reconcile");
let (status, body) = lab
.send(
&lab.admin(),
"POST",
&uri,
Some(json!({"confirmation": format!("RECONCILE {job}")})),
)
.await;
assert_eq!(status, StatusCode::CONFLICT);
assert!(
body["error"]
.as_str()
.is_some_and(|text| text.contains("recovery_required")),
"{body}"
);
// the wrong confirmation is still a plain 400
let (status, _) = lab
.send(
&lab.admin(),
"POST",
&uri,
Some(json!({"confirmation": "no"})),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
}

View File

@@ -277,17 +277,23 @@ async fn reconcile(
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
Json(body): Json<Reconcile>, Json(body): Json<Reconcile>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, (StatusCode, Json<serde_json::Value>)> {
let actor = admin_write(&state, peer, &headers)?; let plain = |status: StatusCode| (status, Json(serde_json::Value::Null));
let actor = admin_write(&state, peer, &headers).map_err(plain)?;
if body.confirmation != format!("RECONCILE {id}") { if body.confirmation != format!("RECONCILE {id}") {
return Err(StatusCode::BAD_REQUEST); return Err(plain(StatusCode::BAD_REQUEST));
} }
if !state if !state
.db .db
.reconcile_restore(id, &actor.id(), now()) .reconcile_restore(id, &actor.id(), now())
.map_err(internal)? .map_err(|error| plain(internal(error)))?
{ {
return Err(StatusCode::CONFLICT); return Err((
StatusCode::CONFLICT,
Json(serde_json::json!({
"error": "only a restore job in recovery_required can be reconciled"
})),
));
} }
Ok(StatusCode::NO_CONTENT) Ok(StatusCode::NO_CONTENT)
} }

View File

@@ -151,6 +151,14 @@ impl PostgresRestore {
writeln!(script, "BEGIN;")?; writeln!(script, "BEGIN;")?;
} }
} }
// The dump's own CREATE EXTENSION for pg_stat_statements is left out on request, but the reset has
// already dropped the extension the target had. Put it back where it was so its views and functions
// survive; a target that never had it still does not get it.
let preserved = if self.omit_pg_stat_statements {
self.extension_schema("pg_stat_statements").await?
} else {
None
};
let key = uuid::Uuid::new_v4().simple(); let key = uuid::Uuid::new_v4().simple();
writeln!(script, "\\restrict {key}")?; writeln!(script, "\\restrict {key}")?;
let skip_timeout = self.omit_transaction_timeout; let skip_timeout = self.omit_transaction_timeout;
@@ -169,6 +177,9 @@ impl PostgresRestore {
skip_extension, skip_extension,
create_public, create_public,
)?; )?;
if let Some(schema) = preserved {
script.write_all(keep_extension_sql("pg_stat_statements", &schema).as_bytes())?;
}
if let Some(path) = post_sql { if let Some(path) = post_sql {
io::copy( io::copy(
&mut fs::File::open(path).context("read local post-restore SQL")?, &mut fs::File::open(path).context("read local post-restore SQL")?,
@@ -182,6 +193,25 @@ impl PostgresRestore {
.await? .await?
} }
/// The schema an extension is installed in on the target right now, if it is installed.
async fn extension_schema(&self, name: &str) -> Result<Option<String>> {
let query = format!(
"SELECT n.nspname FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = {}",
literal(name)
);
let args = ["-X", "-w", "-q", "-At", "-c"]
.map(String::from)
.into_iter()
.chain([query])
.collect::<Vec<_>>();
let output = self
.connection
.run("psql", &args, None, Stdio::null(), Stdio::piped())
.await?;
let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok((!text.is_empty()).then_some(text))
}
pub async fn apply(&self, script: File) -> Result<()> { pub async fn apply(&self, script: File) -> Result<()> {
let database = match self.mode { let database = match self.mode {
PostgresReset::RecreateDatabase => Some("postgres"), PostgresReset::RecreateDatabase => Some("postgres"),
@@ -207,6 +237,12 @@ impl PostgresRestore {
} }
} }
/// Statements that bring an extension back in the schema it had, for the end of a restore script.
fn keep_extension_sql(extension: &str, schema: &str) -> String {
let schema = identifier(schema);
format!("CREATE SCHEMA IF NOT EXISTS {schema};\nCREATE EXTENSION IF NOT EXISTS {extension} WITH SCHEMA {schema};\n")
}
fn literal(value: &str) -> String { fn literal(value: &str) -> String {
format!("'{}'", value.replace('\'', "''")) format!("'{}'", value.replace('\'', "''"))
} }
@@ -217,19 +253,29 @@ fn identifier(value: &str) -> String {
async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> { async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
let file = tempfile::tempfile()?; let file = tempfile::tempfile()?;
let status = Command::new(executable) // Read the archive header without moving the offset that the child process will start from.
let header = read_header(&input);
let output = Command::new(executable)
.args(args) .args(args)
.stdin(Stdio::from(input)) .stdin(Stdio::from(input))
.stdout(Stdio::from(file.try_clone()?)) .stdout(Stdio::from(file.try_clone()?))
.stderr(Stdio::null()) .stderr(Stdio::piped())
.kill_on_drop(true) .kill_on_drop(true)
.status() .spawn()
.context("prepare PostgreSQL restore script")?
.wait_with_output()
.await .await
.context("prepare PostgreSQL restore script")?; .context("prepare PostgreSQL restore script")?;
ensure!( if !output.status.success() {
status.success(), if executable == "pg_restore" {
"{executable} rejected the restore archive" let local = local_client_version("pg_restore").await;
); anyhow::bail!(
"{}",
explain_restore_failure(header.as_ref(), local.as_deref(), &output.stderr)
);
}
anyhow::bail!("{executable} rejected the restore archive");
}
ensure!( ensure!(
file.metadata()?.len() > 0, file.metadata()?.len() > 0,
"empty PostgreSQL restore script" "empty PostgreSQL restore script"
@@ -237,6 +283,146 @@ async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
Ok(file) Ok(file)
} }
/// What pg_dump wrote at the top of a custom-format archive.
#[derive(Debug)]
pub(crate) struct ArchiveHeader {
/// Archive format version, e.g. (1, 16, 0) for pg_dump 17.
pub format: (u8, u8, u8),
/// Version of the pg_dump that made it, e.g. `17.2`.
pub dumped_by: Option<String>,
}
fn read_header(file: &File) -> Option<ArchiveHeader> {
let mut head = vec![0u8; 512];
#[cfg(unix)]
let read = {
use std::os::unix::fs::FileExt;
file.read_at(&mut head, 0).ok()?
};
#[cfg(not(unix))]
let read = {
let _ = file;
0
};
head.truncate(read);
parse_archive_header(&head)
}
/// Parse the start of a custom-format archive. Anything unexpected gives `None`: the header only enriches an
/// error message, so it must never be a reason to fail by itself.
pub(crate) fn parse_archive_header(bytes: &[u8]) -> Option<ArchiveHeader> {
let rest = bytes.strip_prefix(b"PGDMP")?;
let (&major, rest) = rest.split_first()?;
let (&minor, rest) = rest.split_first()?;
let (&revision, rest) = rest.split_first()?;
if major != 1 || minor < 10 || rest.len() < 3 {
return None; // before 1.10 there is no pg_dump version string
}
let (int_size, rest) = (usize::from(rest[0]), &rest[2..]); // integer size, then offset size
if !(1..=8).contains(&int_size) {
return None;
}
let mut cursor = Cursor {
bytes: rest,
int_size,
};
cursor.byte()?; // archive format
if (major, minor) >= (1, 15) {
cursor.byte()?; // compression algorithm
} else {
cursor.int()?; // compression level
}
for _ in 0..7 {
cursor.int()?; // creation time
}
cursor.text()?; // database name
cursor.text()?; // server version
let dumped_by = cursor.text()?;
let version = dumped_by.split(' ').next()?.to_string();
let valid = !version.is_empty()
&& version
.split('.')
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()));
Some(ArchiveHeader {
format: (major, minor, revision),
dumped_by: valid.then_some(version),
})
}
struct Cursor<'a> {
bytes: &'a [u8],
int_size: usize,
}
impl Cursor<'_> {
fn byte(&mut self) -> Option<u8> {
let (&byte, rest) = self.bytes.split_first()?;
self.bytes = rest;
Some(byte)
}
/// pg_dump's integer: a sign byte, then the magnitude, least significant byte first.
fn int(&mut self) -> Option<i64> {
let sign = self.byte()?;
let mut value = 0i64;
for index in 0..self.int_size {
value |= i64::from(self.byte()?) << (8 * index);
}
Some(if sign == 0 { value } else { -value })
}
fn text(&mut self) -> Option<String> {
let length = usize::try_from(self.int()?)
.ok()
.filter(|length| *length <= 256)?;
let (text, rest) = self.bytes.split_at_checked(length)?;
self.bytes = rest;
Some(String::from_utf8_lossy(text).into_owned())
}
}
async fn local_client_version(program: &str) -> Option<String> {
let output = Command::new(program)
.arg("--version")
.kill_on_drop(true)
.output()
.await
.ok()?;
let text = String::from_utf8_lossy(&output.stdout);
// "pg_restore (PostgreSQL) 16.15 (Ubuntu ...)"
text.split_whitespace()
.find(|word| word.chars().next().is_some_and(|c| c.is_ascii_digit()))
.map(str::to_string)
}
fn major_of(version: &str) -> Option<u32> {
version.split('.').next()?.parse().ok()
}
/// A reason that says what to do when the archive was made by a newer pg_dump than the local pg_restore
/// understands, and otherwise passes on what pg_restore itself said.
pub(crate) fn explain_restore_failure(
header: Option<&ArchiveHeader>,
local: Option<&str>,
stderr: &[u8],
) -> String {
let said = crate::postgres::client_reason(stderr);
let newer = header
.and_then(|header| header.dumped_by.as_deref())
.zip(local)
.filter(|(dumped, local)| major_of(dumped) > major_of(local));
match (newer, header) {
(Some((dumped, local)), Some(header)) => format!(
"pg_restore {local} cannot read this archive (made by pg_dump {dumped}, archive format {}.{}): install a PostgreSQL client >= {} on the restore host{said}",
header.format.0,
header.format.1,
major_of(dumped).unwrap_or_default(),
),
_ if !said.is_empty() => format!("pg_restore rejected the restore archive{said}"),
_ => "pg_restore rejected the restore archive".to_string(),
}
}
fn append_dump( fn append_dump(
data: File, data: File,
script: &mut File, script: &mut File,
@@ -327,6 +513,98 @@ mod tests {
text text
} }
/// A custom-format archive header the way pg_dump writes it: magic, version, sizes, format, compression,
/// the creation time (seven integers), then database name, server version and pg_dump version.
fn archive_header(major: u8, minor: u8, dumped_by: &str) -> Vec<u8> {
fn int(out: &mut Vec<u8>, value: u32) {
out.push(0); // sign
out.extend(value.to_le_bytes());
}
fn text(out: &mut Vec<u8>, value: &str) {
int(out, value.len() as u32);
out.extend(value.as_bytes());
}
let mut out = b"PGDMP".to_vec();
out.extend([major, minor, 0, 4, 8, 1]);
if (major, minor) >= (1, 15) {
out.push(1); // compression algorithm, one byte since 1.15
} else {
int(&mut out, 0); // compression level as an integer before that
}
for _ in 0..7 {
int(&mut out, 1); // creation time
}
text(&mut out, "app");
text(&mut out, "17.2");
text(&mut out, dumped_by);
out
}
#[test]
fn the_archive_header_names_the_pg_dump_that_made_it() {
for (major, minor, by) in [
(1, 14, "14.20"),
(1, 16, "17.2"),
(1, 15, "16.15 (Ubuntu 16.15-1)"),
] {
let header = parse_archive_header(&archive_header(major, minor, by)).expect("a header");
assert_eq!((header.format.0, header.format.1), (major, minor));
assert_eq!(
header.dumped_by.as_deref(),
Some(by.split(' ').next().unwrap())
);
}
assert!(parse_archive_header(b"-- plain sql").is_none());
assert!(parse_archive_header(b"PGDMP").is_none(), "truncated");
assert!(parse_archive_header(&archive_header(1, 16, "17.2")[..20]).is_none());
}
#[test]
fn a_too_old_pg_restore_says_which_client_to_install() {
let header = parse_archive_header(&archive_header(1, 16, "17.2"));
let reason = explain_restore_failure(
header.as_ref(),
Some("16.15"),
b"pg_restore: error: unsupported version (1.16) in file header\n",
);
assert!(
reason.contains("pg_restore 16.15")
&& reason.contains("pg_dump 17.2")
&& reason.contains(">= 17"),
"{reason}"
);
assert!(
reason.contains("unsupported version (1.16)"),
"the client's own words stay: {reason}"
);
// an unreadable header or an equal version falls back to what pg_restore said
let reason = explain_restore_failure(
None,
Some("16.15"),
b"pg_restore: error: could not read from input file: end of file\n",
);
assert!(
reason.contains("could not read from input file") && !reason.contains("install"),
"{reason}"
);
let same = parse_archive_header(&archive_header(1, 15, "16.9"));
assert!(!explain_restore_failure(same.as_ref(), Some("16.15"), b"").contains("install"));
assert_eq!(
explain_restore_failure(None, None, b""),
"pg_restore rejected the restore archive"
);
}
#[test]
fn an_extension_the_target_had_is_recreated_where_it_lived() {
assert_eq!(
keep_extension_sql("pg_stat_statements", "public"),
"CREATE SCHEMA IF NOT EXISTS \"public\";\nCREATE EXTENSION IF NOT EXISTS pg_stat_statements WITH SCHEMA \"public\";\n"
);
// a schema name cannot break out of its quotes
assert!(keep_extension_sql("pg_stat_statements", "a\"b; DROP").contains("\"a\"\"b; DROP\""));
}
fn psql_with_restricted_mode() -> bool { fn psql_with_restricted_mode() -> bool {
std::process::Command::new("psql") std::process::Command::new("psql")
.arg("--help=commands") .arg("--help=commands")
@@ -510,5 +788,110 @@ mod tests {
), ),
"0" "0"
); );
// 3. a real custom-format archive: its header names the pg_dump that wrote it
let custom = std::process::Command::new("pg_dump")
.args([
"-h",
"127.0.0.1",
"-p",
&port,
"-U",
"postgres",
"-d",
"src_db",
"-Fc",
])
.env("PGPASSWORD", "pw")
.output()
.unwrap();
let header = parse_archive_header(&custom.stdout).expect("a real archive header parses");
let dumped_by = header.dumped_by.expect("with the pg_dump version");
let server_major = sh(&port, "src_db", "SHOW server_version_num")
.parse::<u32>()
.unwrap()
/ 10000;
assert!(
dumped_by.starts_with(&format!("{server_major}.")),
"{dumped_by}"
);
// 4. pg_stat_statements: kept where the target had it, never added where it had none
for db in ["ext_src", "ext_dst", "ext_none"] {
sh(&port, "postgres", &format!("DROP DATABASE IF EXISTS {db}"));
sh(&port, "postgres", &format!("CREATE DATABASE {db}"));
}
sh(
&port,
"ext_src",
"CREATE EXTENSION pg_stat_statements; CREATE TABLE public.t (id int)",
);
sh(
&port,
"ext_dst",
"CREATE EXTENSION pg_stat_statements; CREATE TABLE public.old (id int)",
);
let ext_dump = std::process::Command::new("pg_dump")
.args([
"-h",
"127.0.0.1",
"-p",
&port,
"-U",
"postgres",
"-d",
"ext_src",
"--no-owner",
"--no-acl",
"-Fp",
])
.env("PGPASSWORD", "pw")
.output()
.unwrap();
for (db, expected) in [("ext_dst", "1"), ("ext_none", "0")] {
let identity = DatabaseIdentity {
instance: sh(
&port,
db,
"SELECT system_identifier FROM pg_control_system()",
),
database: db.into(),
};
let restore: PostgresRestore = serde_json::from_value(serde_json::json!({
"connection": {"host": "127.0.0.1", "port": port.parse::<u16>().unwrap(), "database": db, "user": "postgres",
"password_file": password, "tls": {"mode": "disable"}},
"mode": {"reset": "user_schemas"},
"omit_pg_stat_statements": true,
}))
.unwrap();
restore
.apply(prepared(&restore, &ext_dump.stdout, &identity).await)
.await
.unwrap();
assert_eq!(
sh(
&port,
db,
"SELECT count(*) FROM pg_extension WHERE extname = 'pg_stat_statements'"
),
expected,
"{db}"
);
assert_eq!(
sh(&port, db, "SELECT count(*) FROM public.t"),
"0",
"{db}: the dump's table arrived"
);
}
// the extension's own view works again after the restore (it was not left half-dropped)
// its objects are back too, not just the catalog entry (the view itself needs the server to preload it)
assert_eq!(
sh(
&port,
"ext_dst",
"SELECT count(*) FROM pg_proc WHERE proname = 'pg_stat_statements_reset'"
),
"1"
);
} }
} }

View File

@@ -166,6 +166,8 @@ On the target agent, add a `targets` map under the application UUID, keyed by th
Use `{"reset":"recreate_database"}` to recreate the registered PostgreSQL database. It requires access to the `postgres` maintenance database and permission to drop and create the target database. Schema mode resets the named schema and applies the dump in a transaction. Use `{"reset":"user_schemas"}` for a database whose tables live in several schemas: it drops every non-system schema (everything except `pg_*` and `information_schema`) and recreates `public`, in the same transaction as the restore, so a dump's `CREATE SCHEMA` for a schema that already exists on the target cannot collide. Schema mode only drops the one named schema, so a dump that also creates another schema that the target already has fails and rolls back; the target is left unchanged. Objects that live outside schemas (roles, publications, subscriptions) are not touched, and the connected role must own, or be allowed to drop, every schema it empties. Supply a local `post_restore_sql` file for target-specific SQL. PostgreSQL can read custom archives and plain or gzip-compressed SQL. The agent requires a psql client with restricted mode for restore. `omit_transaction_timeout` and `omit_pg_stat_statements` enable specific compatibility rules. Use `{"reset":"recreate_database"}` to recreate the registered PostgreSQL database. It requires access to the `postgres` maintenance database and permission to drop and create the target database. Schema mode resets the named schema and applies the dump in a transaction. Use `{"reset":"user_schemas"}` for a database whose tables live in several schemas: it drops every non-system schema (everything except `pg_*` and `information_schema`) and recreates `public`, in the same transaction as the restore, so a dump's `CREATE SCHEMA` for a schema that already exists on the target cannot collide. Schema mode only drops the one named schema, so a dump that also creates another schema that the target already has fails and rolls back; the target is left unchanged. Objects that live outside schemas (roles, publications, subscriptions) are not touched, and the connected role must own, or be allowed to drop, every schema it empties. Supply a local `post_restore_sql` file for target-specific SQL. PostgreSQL can read custom archives and plain or gzip-compressed SQL. The agent requires a psql client with restricted mode for restore. `omit_transaction_timeout` and `omit_pg_stat_statements` enable specific compatibility rules.
A custom-format archive must be readable by the `pg_restore` on the restore host. pg_restore refuses archives made by a newer pg_dump, so install a client at least as new as the one that captured. The check happens while the archive is being prepared, before the safety backup and before anything is touched, and the failure names both versions, for example `pg_restore 16.15 cannot read this archive (made by pg_dump 17.2, archive format 1.16): install a PostgreSQL client >= 17 on the restore host`. With `omit_pg_stat_statements`, the dump's own `pg_stat_statements` statements are skipped, but an extension the target already had is recreated in the schema it lived in (a target without it does not get it).
When a restore step fails, the agent reports why and the hub keeps it as `failure_reason` on the restore job (visible to administrators through `GET /api/v1/restore-jobs/{id}`, written to the hub log and the audit log as `restore.failed`). It is the client's own primary error line (`ERROR:`/`FATAL:`), cleaned to one line of printable ASCII of at most 300 characters. `DETAIL`, `CONTEXT` and statement text are dropped because they quote data, and the psql run uses `VERBOSITY=terse`. People who only hold a refresh grant never see it: their run shows the status, not the database's words. Message text can still name an object or value in a few cases (for example an invalid input value), so treat the field as administrator-only. When a restore step fails, the agent reports why and the hub keeps it as `failure_reason` on the restore job (visible to administrators through `GET /api/v1/restore-jobs/{id}`, written to the hub log and the audit log as `restore.failed`). It is the client's own primary error line (`ERROR:`/`FATAL:`), cleaned to one line of printable ASCII of at most 300 characters. `DETAIL`, `CONTEXT` and statement text are dropped because they quote data, and the psql run uses `VERBOSITY=terse`. People who only hold a refresh grant never see it: their run shows the status, not the database's words. Message text can still name an object or value in a few cases (for example an invalid input value), so treat the field as administrator-only.
A MySQL target uses `"engine":"mysql"` and the same `connection` fields as a direct or SSH MySQL source. `recreate_database` drops and recreates the registered database before applying SQL. `use_target_definer` rewrites supported dump DEFINER clauses to the connected MySQL user. A MySQL target uses `"engine":"mysql"` and the same `connection` fields as a direct or SSH MySQL source. `recreate_database` drops and recreates the registered database before applying SQL. `use_target_definer` rewrites supported dump DEFINER clauses to the connected MySQL user.