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

@@ -151,6 +151,14 @@ impl PostgresRestore {
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();
writeln!(script, "\\restrict {key}")?;
let skip_timeout = self.omit_transaction_timeout;
@@ -169,6 +177,9 @@ impl PostgresRestore {
skip_extension,
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 {
io::copy(
&mut fs::File::open(path).context("read local post-restore SQL")?,
@@ -182,6 +193,25 @@ impl PostgresRestore {
.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<()> {
let database = match self.mode {
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 {
format!("'{}'", value.replace('\'', "''"))
}
@@ -217,19 +253,29 @@ fn identifier(value: &str) -> String {
async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
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)
.stdin(Stdio::from(input))
.stdout(Stdio::from(file.try_clone()?))
.stderr(Stdio::null())
.stderr(Stdio::piped())
.kill_on_drop(true)
.status()
.spawn()
.context("prepare PostgreSQL restore script")?
.wait_with_output()
.await
.context("prepare PostgreSQL restore script")?;
ensure!(
status.success(),
"{executable} rejected the restore archive"
);
if !output.status.success() {
if executable == "pg_restore" {
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!(
file.metadata()?.len() > 0,
"empty PostgreSQL restore script"
@@ -237,6 +283,146 @@ async fn convert(input: File, executable: &str, args: &[&str]) -> Result<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(
data: File,
script: &mut File,
@@ -327,6 +513,98 @@ mod tests {
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 {
std::process::Command::new("psql")
.arg("--help=commands")
@@ -510,5 +788,110 @@ mod tests {
),
"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"
);
}
}