Skip to main content

quack_rs/validate/
release_profile.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! Release profile validation for `DuckDB` loadable extensions.
7//!
8//! `DuckDB` loadable extensions are shared libraries (`.so`/`.dylib`/`.dll`)
9//! whose Cargo release profile decides whether a panic in your code becomes a
10//! `DuckDB` error or kills the `DuckDB` process.
11//!
12//! # Required settings
13//!
14//! ```toml
15//! [profile.release]
16//! panic = "unwind"    # Required: quack-rs catches panics, and catching needs unwinding
17//! lto = true          # Recommended: reduces binary size
18//! opt-level = 3       # Recommended: maximum optimization
19//! codegen-units = 1   # Recommended: better optimization
20//! ```
21//!
22//! # Why `unwind`, not `abort`
23//!
24//! quack-rs wraps every `extern "C"` entry point — the extension entry point,
25//! every scalar/table/aggregate/cast/copy callback macro — in
26//! [`std::panic::catch_unwind`], turning a panic into a `DuckDB` error message
27//! instead of a crash. **`catch_unwind` cannot catch anything under
28//! `panic = "abort"`**: the runtime aborts before unwinding starts, so the
29//! process dies with `SIGABRT` and takes the user's `DuckDB` session with it.
30//!
31//! Demonstrated directly:
32//!
33//! ```text
34//! $ rustc -O panic_probe.rs && ./panic_probe
35//! catch_unwind returned: true
36//! process survived the panic          exit=0
37//!
38//! $ rustc -O -C panic=abort panic_probe.rs && ./panic_probe
39//! Aborted                             exit=134
40//! ```
41//!
42//! The older advice to set `panic = "abort"` came from panics escaping an
43//! `extern "C"` boundary once being undefined behaviour. They no longer are —
44//! Rust defines that as an abort — and quack-rs catches them before the
45//! boundary anyway, which is the whole point.
46
47use crate::error::ExtensionError;
48
49/// Results of checking a release profile configuration.
50///
51/// Each field indicates whether the corresponding setting is present and correct.
52#[allow(clippy::struct_excessive_bools)]
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct ReleaseProfileCheck {
55    /// `panic = "unwind"` is set (required for quack-rs's panic safety).
56    pub panic_unwind: bool,
57    /// `lto = true` or `lto = "fat"` is set (recommended for binary size).
58    pub lto_enabled: bool,
59    /// `opt-level = 3` is set (recommended for performance).
60    pub opt_level_3: bool,
61    /// `codegen-units = 1` is set (recommended for optimization quality).
62    pub codegen_units_1: bool,
63}
64
65impl ReleaseProfileCheck {
66    /// Returns `true` if all required settings are satisfied.
67    ///
68    /// Only `panic = "unwind"` is strictly required; the rest are best
69    /// practices.
70    #[must_use]
71    pub const fn is_required_satisfied(&self) -> bool {
72        self.panic_unwind
73    }
74
75    /// Returns `true` if all recommended settings are satisfied.
76    #[must_use]
77    pub const fn is_fully_optimized(&self) -> bool {
78        self.panic_unwind && self.lto_enabled && self.opt_level_3 && self.codegen_units_1
79    }
80}
81
82/// Validates release profile settings from string key-value pairs.
83///
84/// This function checks whether the given settings match the recommended
85/// release profile for `DuckDB` loadable extensions.
86///
87/// # Arguments
88///
89/// - `panic`: The value of `panic` (e.g., `"unwind"`, `"abort"`)
90/// - `lto`: The value of `lto` (e.g., `"true"`, `"false"`, `"fat"`, `"thin"`)
91/// - `opt_level`: The value of `opt-level` (e.g., `"3"`, `"2"`, `"s"`)
92/// - `codegen_units`: The value of `codegen-units` (e.g., `"1"`, `"16"`)
93///
94/// # Errors
95///
96/// Returns `ExtensionError` if the required setting (`panic = "unwind"`) is not
97/// met.
98///
99/// # Example
100///
101/// ```rust
102/// use quack_rs::validate::validate_release_profile;
103///
104/// let check = validate_release_profile("unwind", "true", "3", "1").unwrap();
105/// assert!(check.is_fully_optimized());
106///
107/// // `abort` makes quack-rs's panic handling inert — see the module docs.
108/// assert!(validate_release_profile("abort", "true", "3", "1").is_err());
109/// ```
110pub fn validate_release_profile(
111    panic: &str,
112    lto: &str,
113    opt_level: &str,
114    codegen_units: &str,
115) -> Result<ReleaseProfileCheck, ExtensionError> {
116    let check = ReleaseProfileCheck {
117        // An unset `panic` defaults to unwind, which is what we want; but an
118        // extension's profile should say so explicitly, so only the literal
119        // "unwind" counts here.
120        panic_unwind: panic == "unwind",
121        lto_enabled: matches!(lto, "true" | "fat"),
122        opt_level_3: opt_level == "3",
123        codegen_units_1: codegen_units == "1",
124    };
125
126    if !check.panic_unwind {
127        return Err(ExtensionError::new(format!(
128            "release profile sets panic = \"{panic}\"; it must be \"unwind\". \
129             quack-rs catches panics at every FFI boundary and turns them into \
130             DuckDB errors, and std::panic::catch_unwind cannot catch anything \
131             under panic = \"abort\" — the process aborts instead, taking the \
132             user's DuckDB session with it"
133        )));
134    }
135
136    Ok(check)
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn fully_optimized() {
145        let check = validate_release_profile("unwind", "true", "3", "1").unwrap();
146        assert!(check.is_fully_optimized());
147        assert!(check.is_required_satisfied());
148    }
149
150    #[test]
151    fn fat_lto_accepted() {
152        let check = validate_release_profile("unwind", "fat", "3", "1").unwrap();
153        assert!(check.lto_enabled);
154    }
155
156    #[test]
157    fn thin_lto_not_full() {
158        let check = validate_release_profile("unwind", "thin", "3", "1").unwrap();
159        assert!(!check.lto_enabled);
160        assert!(!check.is_fully_optimized());
161    }
162
163    #[test]
164    fn no_lto_still_passes_required() {
165        let check = validate_release_profile("unwind", "false", "2", "16").unwrap();
166        assert!(check.is_required_satisfied());
167        assert!(!check.is_fully_optimized());
168    }
169
170    /// `validate_release_profile` refuses `panic = "abort"` outright, so a
171    /// check without it only comes from a struct literal; it must not pass.
172    #[test]
173    fn a_check_without_unwind_is_not_satisfied() {
174        let check = ReleaseProfileCheck {
175            panic_unwind: false,
176            lto_enabled: true,
177            opt_level_3: true,
178            codegen_units_1: true,
179        };
180        assert!(!check.is_required_satisfied());
181        assert!(!check.is_fully_optimized());
182    }
183
184    #[test]
185    fn panic_abort_rejected_because_it_disables_catch_unwind() {
186        let err = validate_release_profile("abort", "true", "3", "1").unwrap_err();
187        assert!(err.as_str().contains("catch_unwind"));
188        assert!(err.as_str().contains("must be"));
189    }
190
191    #[test]
192    fn empty_panic_rejected() {
193        // An unset `panic` does default to unwind, but an extension's profile
194        // should say so — the setting is load-bearing enough to be explicit.
195        assert!(validate_release_profile("", "true", "3", "1").is_err());
196    }
197
198    #[test]
199    fn check_fields_independent() {
200        let check = validate_release_profile("unwind", "false", "2", "4").unwrap();
201        assert!(check.panic_unwind);
202        assert!(!check.lto_enabled);
203        assert!(!check.opt_level_3);
204        assert!(!check.codegen_units_1);
205    }
206
207    #[test]
208    fn the_scaffold_and_the_validator_agree() {
209        // These two contradicted each other: the scaffold generated
210        // `panic = "unwind"` (correct) while this validator required "abort".
211        let cargo_toml = crate::scaffold::generate_scaffold(&crate::scaffold::ScaffoldConfig {
212            name: "probe".into(),
213            description: "d".into(),
214            maintainer: "m".into(),
215            github_repo: "o/r".into(),
216            ..Default::default()
217        })
218        .expect("scaffold");
219        let manifest = &cargo_toml
220            .iter()
221            .find(|f| f.path == "Cargo.toml")
222            .expect("Cargo.toml")
223            .content;
224        assert!(
225            manifest.contains(r#"panic = "unwind""#),
226            "the scaffold must generate the profile this validator requires"
227        );
228        assert!(!manifest.contains(r#"panic = "abort""#));
229    }
230}