quack_rs/abi.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//! `DuckDB` C Extension API ABI compatibility checking.
7//!
8//! # Why this module exists
9//!
10//! A loadable extension does not link against `DuckDB`'s symbols. Instead,
11//! `DuckDB` hands the extension a pointer to a `duckdb_ext_api_v1` struct — an
12//! array of function pointers — and the extension calls through it. The
13//! extension's *compiled-in* idea of that struct's layout comes from the
14//! `duckdb_extension.h` shipped with the `libduckdb-sys` version Cargo resolved
15//! at build time. `DuckDB`'s idea of the layout comes from whatever `DuckDB`
16//! binary is doing the loading. **If those two layouts disagree, every call
17//! lands on the wrong function pointer.**
18//!
19//! `duckdb_ext_api_v1` is split into two regions:
20//!
21//! | Region | Slots | Guarantee |
22//! |--------|-------|-----------|
23//! | Stable | <code>0 .. [STABLE_API_SLOT_COUNT]</code> | Frozen since `DuckDB` v1.2.0: ABI-identical in every release from v1.2.0 through v2.0.0 (two slots were renamed `varint` → `bignum` in v1.4.0; the struct layout is unchanged). |
24//! | Unstable | <code>[STABLE_API_SLOT_COUNT] ..</code> | Before v1.5.6, `DuckDB` twice **inserted new entries in the middle**, shifting every later slot. |
25//!
26//! The unstable region is where `duckdb-1-5` lives: scalar bind/init, copy
27//! functions, catalog access, `ErrorData`, `FileSystem`, `Expression`,
28//! `SelectionVector`, config options, table descriptions, `TIME_NS` values, and
29//! the client context all sit past the stable boundary.
30//!
31//! The unstable region grew at every minor version in the table below, and
32//! twice `DuckDB` **inserted** entries into its middle, shifting every later
33//! slot. The releases from v1.4.4 on were checked by hashing
34//! `extension_api.hpp` at each tag (v1.4.4 and v1.4.5 are identical, as are
35//! v1.5.0 and v1.5.1, and v1.5.2 to v1.5.5); the rest of the table comes from
36//! the original survey. `scripts/check-abi-table.py` re-derives the whole table
37//! from every release's `duckdb_extension.h`, fingerprinting each layout by its
38//! full declarations, and found v1.5.6 identical to v1.5.2 – v1.5.5, and
39//! v2.0.0's layout to be v1.5.6's with two slots appended.
40//!
41//! | `DuckDB` | Total slots | What changed |
42//! |----------|-------------|--------------|
43//! | v1.2.0 – v1.2.2 | 408 | baseline |
44//! | v1.3.0 – v1.3.2 | 428 | appended |
45//! | v1.4.0 – v1.4.5 | 459 | `duckdb_create_varint` → `duckdb_create_bignum`, appended |
46//! | v1.5.0 – v1.5.1 | 545 | `duckdb_appender_clear` **inserted** at slot 410 |
47//! | v1.5.2 – v1.5.6 | 546 | `duckdb_geometry_type_get_crs` **inserted** at slot 493 |
48//! | v2.0.0 | 548 | `duckdb_create_timestamp_tz_ns`, `duckdb_get_timestamp_tz_ns` appended |
49//!
50//! `DuckDB` v1.5.6 **stabilised** the whole struct: its header declares all 546
51//! slots stable for an extension that targets C API v1.5.6, where earlier
52//! releases declared only the first 357 stable. The layout is unchanged, and
53//! so is what this module checks: quack-rs targets C API v1.2.0, and every
54//! release before v1.5.6 still hands out the 546-slot struct with nothing past
55//! slot 357 guaranteed. v2.0.0 keeps the V1 C API at version v1.5.6 and only
56//! appends to it, so a build against the v1.5.2 – v1.5.6 layout runs on
57//! v2.0.0 unchanged; [`check`] accepts it there (`PREFIX_LAYOUTS`).
58//!
59//! # Why `DuckDB` does not catch this for you
60//!
61//! `DuckDB`'s loader validates the extension footer's ABI metadata:
62//!
63//! - `C_STRUCT` + a C API version (`v1.2.0`) — accepted by *any* `DuckDB` whose
64//! C API version is greater than or equal to it, then handed the **whole**
65//! struct including the unstable region. No engine-version check at all.
66//! `DuckDB` v1.2.0 – v1.5.5 declare C API v1.2.0; v1.5.6 and v2.0.0 declare
67//! v1.5.6.
68//! - `C_STRUCT_UNSTABLE` + a `DuckDB` release version — accepted only by that
69//! exact `DuckDB` 1.x release. `DuckDB` 2.0 sends every such binary to the
70//! C API v2 entry point instead (see below).
71//!
72//! An extension that touches the unstable region but is stamped `C_STRUCT`
73//! therefore loads happily into a `DuckDB` with a different layout and then
74//! mis-dispatches. For example, an extension built against `DuckDB` v1.5.0 and
75//! loaded into v1.5.2+ would call `duckdb_scalar_function_set_bind_data(info,
76//! data, destroy)` and actually invoke
77//! `duckdb_scalar_function_get_client_context(info)`.
78//!
79//! # What this module does
80//!
81//! [`check`] compares the slot count of the layout this extension was *compiled*
82//! against with the slot count of the layout the *running* `DuckDB` uses (looked
83//! up from `duckdb_library_version()`, which lives at stable slot 7 and is
84//! therefore always safe to call). A mismatch is reported as
85//! [`AbiCheck::LayoutMismatch`] instead of being allowed to corrupt memory.
86//!
87//! [`init_extension`][crate::entry_point::init_extension] and
88//! [`init_extension_v2`][crate::entry_point::init_extension_v2] run this check
89//! automatically under [`AbiPolicy::Strict`], which is the default whenever the
90//! `duckdb-1-5` feature is enabled. Extensions that only use the stable region
91//! are unaffected and stay portable across every `DuckDB` release.
92//!
93//! # The bindings read the whole struct before this check runs
94//!
95//! `libduckdb-sys` generates its `duckdb_ext_api_v1` with
96//! `DUCKDB_EXTENSION_API_VERSION_UNSTABLE` defined, so the Rust struct always
97//! has every slot of the release it was generated from (546 for the v1.5.x
98//! bindings, 548 for v2.0), whatever quack-rs features are on. Its
99//! `duckdb_rs_extension_api_init` asks `DuckDB` for the struct (`get_api`) and
100//! then reads **every one of those slots** through the returned pointer,
101//! storing each non-null one in a process-wide table. The entry point must call
102//! it before [`check`], because [`check`] reaches `duckdb_library_version`
103//! through that table.
104//!
105//! `DuckDB`'s `get_api` returns the address of the `duckdb_ext_api_v1` member
106//! of the loader's per-load state (`DuckDBExtensionLoadState::api_struct` in
107//! `src/main/extension/extension_load.cpp`, a local of the loading call), sized
108//! by the engine's own header. So loading a build against the 546-slot
109//! bindings into `DuckDB` v1.4.x (459 slots) reads 87 pointers, 696 bytes on a
110//! 64-bit target, past the end of that member, and into v1.5.0 – v1.5.1 (545
111//! slots) one pointer: the fields after it in the load state, then the
112//! loader's stack. This happens on **every** such `LOAD`, before any check,
113//! including for a build without `duckdb-1-5` that [`check`] then lets load as
114//! [`AbiCheck::StableOnly`]. The memory is mapped (no crash has been observed or
115//! is expected), and the values it yields are stored but never called by code
116//! that stays in the stable prefix, or when the check refuses the load. They
117//! *are* what an unstable-region wrapper would call after
118//! [`AbiPolicy::Warn`] or [`AbiPolicy::Trust`] let a mismatched layout load —
119//! one more reason those policies are undefined behaviour on a mismatch. The
120//! over-read is in `libduckdb-sys`'s generated code; quack-rs could avoid it
121//! only by calling `get_api` and reading slot 7 itself before handing the
122//! struct to the bindings.
123//!
124//! # A `DuckDB` release the table has not seen
125//!
126//! [`check`] does not extrapolate: a `duckdb-1-5` build under
127//! [`AbiPolicy::Strict`] refuses `DuckDB` v2.0.1 (or any release missing from the
128//! table) as [`AbiCheck::UnknownEngineVersion`] until quack-rs lists it, or until
129//! the build declares the engine with `QUACK_RS_TARGET_DUCKDB_VERSION`. A
130//! default-feature build is [`AbiCheck::StableOnly`] and loads there. The layout
131//! is not assumed to carry over to a 2.0.x patch release: `DuckDB` v2.0.0's
132//! `duckdb_extension.h` opens with
133//! `// WARNING: this API is not yet stable, meaning it is only guaranteed to work for this specific DuckDB version.`,
134//! v2.0.0 itself added two slots to the band v1.5.6 had declared stable, and a
135//! 1.5.x patch release (v1.5.2) once inserted a slot mid-struct.
136//!
137//! # Shipping an extension that uses the unstable API
138//!
139//! Build against `DuckDB` v1.5.2 or newer bindings and stamp the binary
140//! `--abi-type C_STRUCT --duckdb-version v1.5.6` with
141//! [`append_metadata`][crate::validate] (with `extension-ci-tools`:
142//! `TARGET_DUCKDB_VERSION=v1.5.6` and no `USE_UNSTABLE_C_API`). `DuckDB`
143//! v1.5.0 – v1.5.5 then refuse it at `LOAD` (their C API is v1.2.0), and
144//! v1.5.6 and v2.0.0 load it: v1.5.6 declared that whole layout stable, and
145//! v2.0.0 only appended to it. The runtime guard in this module is the
146//! belt-and-braces for builds where that metadata is missing or wrong — which
147//! includes every `LOAD '/path/to/ext.duckdb_extension'` during development.
148//!
149//! Do **not** stamp such a build `C_STRUCT_UNSTABLE` any more.
150//! `DuckDB` 2.0 sends every `C_STRUCT_UNSTABLE` binary to a
151//! `<name>_init_c_api_v2` entry point (the C API v2 in `duckdb_extension_v2.h`),
152//! which quack-rs does not generate, so it fails to `LOAD` there with "did not
153//! contain function `<name>_init_c_api_v2`". On `DuckDB` 1.x it still pins the
154//! binary to one release.
155
156use core::ffi::c_void;
157use core::mem::size_of;
158
159use libduckdb_sys::duckdb_ext_api_v1;
160
161/// Number of function-pointer slots in the **stable** prefix of
162/// `duckdb_ext_api_v1`.
163///
164/// These slots have been ABI-identical — same slots, same order, same
165/// signatures — in every `DuckDB` release from v1.2.0 through v1.5.6. (Slots
166/// 114 and 138 were renamed from `duckdb_*_varint` to `duckdb_*_bignum` in
167/// v1.4.0; `duckdb_varint` and `duckdb_bignum` have the same layout.) An extension that only
168/// calls into this prefix is portable across all of them.
169pub const STABLE_API_SLOT_COUNT: usize = 357;
170
171/// A `DuckDB` release family and the `duckdb_ext_api_v1` slot count it uses.
172///
173/// `(major, minor, patch_min, patch_max, slots)` — `patch_min..=patch_max` is
174/// the inclusive range of patch releases verified to share `slots`.
175type LayoutEntry = (u64, u64, u64, u64, usize);
176
177/// Verified `DuckDB` release → `duckdb_ext_api_v1` slot-count table.
178///
179/// Derived directly from `src/include/duckdb_extension.h` at each release tag,
180/// with `DUCKDB_EXTENSION_API_VERSION_UNSTABLE` defined (which is what
181/// `libduckdb-sys` does when generating the `loadable-extension` bindings, and
182/// what `DuckDB` itself does when building the struct it hands out).
183///
184/// Regenerate with `scripts/check-abi-table.py`, which re-downloads every
185/// release header and fails if this table drifts.
186///
187/// Within this range the slot count uniquely identifies the layout: no two
188/// releases share a slot count while ordering their entries differently.
189const KNOWN_LAYOUTS: &[LayoutEntry] = &[
190 (1, 2, 0, 2, 408),
191 (1, 3, 0, 2, 428),
192 (1, 4, 0, 5, 459),
193 (1, 5, 0, 1, 545),
194 (1, 5, 2, 6, 546),
195 (2, 0, 0, 0, 548),
196];
197
198/// Pairs of layouts, by slot count, where the first is an exact prefix of the
199/// second: the same declarations, in the same order, then more slots appended.
200///
201/// An extension compiled against the smaller layout reads only that prefix of
202/// the struct `DuckDB` hands it, so it dispatches correctly on an engine using
203/// the larger one. The converse does not hold: a build against the larger
204/// layout would read past the end of the smaller struct.
205///
206/// Derived by `scripts/check-abi-table.py`, which compares full declarations
207/// (not just names) and fails if this table drifts. `(546, 548)` is the one
208/// that matters to the `duckdb-1-5` features: `DuckDB` v2.0.0 appended
209/// `duckdb_create_timestamp_tz_ns` and `duckdb_get_timestamp_tz_ns` to the
210/// v1.5.2 – v1.5.6 layout and changed nothing else.
211const PREFIX_LAYOUTS: &[(usize, usize)] = &[(408, 428), (546, 548)];
212
213/// Returns `true` if a build against `compiled` slots dispatches correctly on
214/// an engine using `engine` slots: the layouts are the same, or `compiled` is a
215/// verified prefix of `engine`.
216fn layout_runs_on(compiled: usize, engine: usize) -> bool {
217 compiled == engine || PREFIX_LAYOUTS.contains(&(compiled, engine))
218}
219
220/// The result of an ABI layout check.
221///
222/// `#[non_exhaustive]`: a future release may report a new outcome, so a
223/// `match` outside quack-rs needs a wildcard arm. [`AbiCheck::is_compatible`]
224/// and [`AbiCheck::error_message`] cover every outcome.
225///
226/// ```rust,compile_fail,E0004
227/// use quack_rs::abi::AbiCheck;
228///
229/// fn passed(check: &AbiCheck) -> bool {
230/// match check {
231/// AbiCheck::Compatible { .. } | AbiCheck::StableOnly => true,
232/// AbiCheck::LayoutMismatch { .. }
233/// | AbiCheck::UnknownEngineVersion { .. }
234/// | AbiCheck::EngineVersionUnavailable { .. }
235/// | AbiCheck::DeclaredVersionMismatch { .. } => false,
236/// // error[E0004]: a wildcard arm is required
237/// }
238/// }
239/// ```
240#[derive(Debug, Clone, PartialEq, Eq)]
241#[non_exhaustive]
242pub enum AbiCheck {
243 /// The running `DuckDB` uses the `duckdb_ext_api_v1` layout this extension
244 /// was compiled against, or one that only appends to it. All calls
245 /// dispatch correctly.
246 Compatible {
247 /// The `duckdb_library_version()` string reported by the engine.
248 engine_version: String,
249 /// The slot count this extension was compiled against, all of which
250 /// the engine lays out identically.
251 slots: usize,
252 },
253 /// The extension only reaches into the stable prefix, so the layout of the
254 /// unstable region is irrelevant. Always portable.
255 StableOnly,
256 /// The running `DuckDB` uses a **different** layout. Calling into the
257 /// unstable region would invoke the wrong function pointers.
258 LayoutMismatch {
259 /// The `duckdb_library_version()` string reported by the engine.
260 engine_version: String,
261 /// Slot count the running engine uses.
262 engine_slots: usize,
263 /// Slot count this extension was compiled against.
264 compiled_slots: usize,
265 },
266 /// The running `DuckDB` reports a version this build of `quack-rs` has no
267 /// verified layout for — a newer release, or a `-dev` build.
268 ///
269 /// This is *not* evidence that the layout matches. `DuckDB` has changed the
270 /// unstable region in every minor and in some patch releases, so an unknown
271 /// version must be treated as potentially incompatible.
272 UnknownEngineVersion {
273 /// The `duckdb_library_version()` string reported by the engine.
274 engine_version: String,
275 /// Slot count this extension was compiled against.
276 compiled_slots: usize,
277 },
278 /// `duckdb_library_version()` returned a null or non-UTF-8 pointer.
279 EngineVersionUnavailable {
280 /// Slot count this extension was compiled against.
281 compiled_slots: usize,
282 },
283 /// `QUACK_RS_TARGET_DUCKDB_VERSION` names a `DuckDB` release whose verified
284 /// slot count does not match the bindings actually compiled in.
285 ///
286 /// The declaration is wrong, so nothing derived from it can be trusted —
287 /// most likely Cargo resolved a different `libduckdb-sys` than the build
288 /// intended.
289 DeclaredVersionMismatch {
290 /// The declared `QUACK_RS_TARGET_DUCKDB_VERSION`.
291 declared_version: String,
292 /// Slot count that release is known to use.
293 declared_slots: usize,
294 /// Slot count this extension was actually compiled against.
295 compiled_slots: usize,
296 },
297}
298
299impl AbiCheck {
300 /// Returns `true` if it is safe to call into the unstable API region.
301 #[must_use]
302 pub const fn is_compatible(&self) -> bool {
303 matches!(self, Self::Compatible { .. } | Self::StableOnly)
304 }
305
306 /// Returns a diagnostic message suitable for `access.set_error`, or `None`
307 /// when the check passed.
308 #[must_use]
309 pub fn error_message(&self) -> Option<String> {
310 match self {
311 Self::Compatible { .. } | Self::StableOnly => None,
312 Self::LayoutMismatch {
313 engine_version,
314 engine_slots,
315 compiled_slots,
316 } => {
317 // The `duckdb-1-5` wrappers do not exist in a 1.4-or-older
318 // header, so "rebuild against it" is only half the answer there.
319 let pre_1_5 = parse_version(engine_version).is_some_and(|v| v < (1, 5, 0));
320 let rebuild = if pre_1_5 {
321 format!(
322 "DuckDB {engine_version} is older than v1.5.0, so it cannot run an \
323 extension that needs the `duckdb-1-5` features at all: build a variant \
324 without them against DuckDB {engine_version}, or have users upgrade \
325 DuckDB."
326 )
327 } else {
328 format!("Rebuild the extension against DuckDB {engine_version}.")
329 };
330 Some(format!(
331 "DuckDB C extension API layout mismatch: this extension was built against a \
332 duckdb_ext_api_v1 with {compiled_slots} slots, but DuckDB {engine_version} \
333 provides {engine_slots}. The extension uses the unstable region of the C \
334 API (quack-rs feature `duckdb-1-5`), whose slot indices differ between \
335 these releases, so loading it would dispatch to the wrong functions. \
336 {rebuild} Stamp a build that uses the unstable region with `--abi-type \
337 C_STRUCT --duckdb-version v1.5.6` (with extension-ci-tools: \
338 `TARGET_DUCKDB_VERSION=v1.5.6` and no `USE_UNSTABLE_C_API`) so DuckDB \
339 itself refuses it before v1.5.6, from which that layout is stable. Not \
340 `C_STRUCT_UNSTABLE`: DuckDB 2.0 loads such a binary only through the C API \
341 v2 entry point, which quack-rs does not generate."
342 ))
343 }
344 Self::UnknownEngineVersion {
345 engine_version,
346 compiled_slots,
347 } if parse_version(engine_version).is_none() => Some(format!(
348 "DuckDB C extension API layout cannot be verified: DuckDB reports version \
349 '{engine_version}', which is not a release version (vX.Y.Z) — a development \
350 build, most likely. quack-rs verifies only released layouts, and \
351 QUACK_RS_TARGET_DUCKDB_VERSION accepts only a release version, so neither \
352 can vouch for this engine (this extension was built against a \
353 {compiled_slots}-slot layout). The extension uses the unstable region of the \
354 C API (quack-rs feature `duckdb-1-5`), so loading is refused rather than \
355 risking mis-dispatch. To load it anyway, build the extension from the same \
356 DuckDB commit and register it with `AbiPolicy::AllowUnknownEngine`, at your \
357 own risk; or, if it does not need the unstable region, build it without the \
358 `duckdb-1-5` features."
359 )),
360 Self::UnknownEngineVersion {
361 engine_version,
362 compiled_slots,
363 } => Some(format!(
364 "DuckDB C extension API layout cannot be verified: DuckDB reports version \
365 '{engine_version}', which this build of quack-rs has no verified \
366 duckdb_ext_api_v1 layout for (this extension was built against a \
367 {compiled_slots}-slot layout). The extension uses the unstable region of the \
368 C API (quack-rs feature `duckdb-1-5`), and DuckDB has changed that region's \
369 layout between releases, so loading is refused rather than risking \
370 mis-dispatch. Fix it in one of these ways, best first: rebuild against DuckDB \
371 {engine_version} and set QUACK_RS_TARGET_DUCKDB_VERSION={engine_version} so \
372 this check passes without waiting for a quack-rs release; upgrade quack-rs to \
373 a version whose layout table lists {engine_version} (which either verifies \
374 the layout or names the mismatch); or, if the extension does not need the \
375 unstable region, build it without the `duckdb-1-5` features so it only uses \
376 the stable prefix, which every DuckDB since v1.2.0 lays out identically."
377 )),
378 Self::DeclaredVersionMismatch {
379 declared_version,
380 declared_slots,
381 compiled_slots,
382 } => Some(format!(
383 "QUACK_RS_TARGET_DUCKDB_VERSION says this extension was built against DuckDB \
384 {declared_version}, whose duckdb_ext_api_v1 has {declared_slots} slots, but the \
385 libduckdb-sys bindings compiled in have {compiled_slots}. The declaration and \
386 the resolved dependency disagree, so neither can be trusted. Check which \
387 libduckdb-sys version Cargo resolved (`cargo tree -p libduckdb-sys`) and make \
388 QUACK_RS_TARGET_DUCKDB_VERSION match it."
389 )),
390 Self::EngineVersionUnavailable { compiled_slots } => Some(format!(
391 "DuckDB C extension API layout cannot be verified: duckdb_library_version() \
392 returned no usable version string (this extension was built against a \
393 {compiled_slots}-slot layout). Refusing to call into the unstable region of \
394 the C API."
395 )),
396 }
397 }
398}
399
400/// Number of `duckdb_ext_api_v1` slots this extension was **compiled** against.
401///
402/// Determined from the size of the `duckdb_ext_api_v1` struct in the resolved
403/// `libduckdb-sys` bindings. Every field is a nullable function pointer, so the
404/// struct is exactly `slots * size_of::<*const c_void>()` bytes.
405#[must_use]
406#[inline]
407pub const fn compiled_slot_count() -> usize {
408 size_of::<duckdb_ext_api_v1>() / size_of::<*const c_void>()
409}
410
411/// Returns `true` if this build of `quack-rs` can reach past the stable prefix.
412///
413/// Only the `duckdb-1-5` / `duckdb-1-5-3` feature set wraps functions in the
414/// unstable region. Without those features the extension is portable across
415/// every `DuckDB` release that accepts C API `v1.2.0`.
416#[must_use]
417#[inline]
418pub const fn uses_unstable_api() -> bool {
419 cfg!(feature = "duckdb-1-5")
420}
421
422/// Parses a `DuckDB` version string into `(major, minor, patch)`.
423///
424/// Accepts `"v1.5.4"` and `"1.5.4"`. Returns `None` for anything carrying a
425/// pre-release or build suffix (`"v1.6.0-dev1234"`), because the layout of a
426/// development build is not knowable from the version string alone.
427#[must_use]
428pub fn parse_version(version: &str) -> Option<(u64, u64, u64)> {
429 /// A part of plain decimal digits: `u64::from_str` alone would also take
430 /// a leading `+` (`"1.5.+4"`), which no `DuckDB` version string has.
431 fn decimal(part: &str) -> Option<u64> {
432 if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {
433 return None;
434 }
435 part.parse().ok()
436 }
437 let trimmed = version.strip_prefix('v').unwrap_or(version);
438 let mut parts = trimmed.split('.');
439 let major = decimal(parts.next()?)?;
440 let minor = decimal(parts.next()?)?;
441 let patch = decimal(parts.next()?)?;
442 if parts.next().is_some() {
443 return None;
444 }
445 Some((major, minor, patch))
446}
447
448/// Returns the verified `duckdb_ext_api_v1` slot count for a `DuckDB` release,
449/// or `None` if this build has no verified entry for it.
450///
451/// # Example
452///
453/// ```rust
454/// use quack_rs::abi::expected_slot_count;
455///
456/// assert_eq!(expected_slot_count("v1.5.4"), Some(546));
457/// assert_eq!(expected_slot_count("v1.5.0"), Some(545));
458/// assert_eq!(expected_slot_count("v1.4.4"), Some(459));
459/// // Unreleased / unknown versions are explicitly not guessed at.
460/// assert_eq!(expected_slot_count("v9.9.9"), None);
461/// assert_eq!(expected_slot_count("v1.6.0-dev42"), None);
462/// ```
463#[must_use]
464pub fn expected_slot_count(version: &str) -> Option<usize> {
465 let (major, minor, patch) = parse_version(version)?;
466 KNOWN_LAYOUTS
467 .iter()
468 .find(|&&(ma, mi, lo, hi, _)| ma == major && mi == minor && patch >= lo && patch <= hi)
469 .map(|&(_, _, _, _, slots)| slots)
470}
471
472/// Returns the version string reported by the running `DuckDB`.
473///
474/// Calls `duckdb_library_version()`, which occupies stable slot 7 and is
475/// therefore dispatched correctly no matter how the unstable region is laid
476/// out.
477///
478/// # Safety
479///
480/// The `DuckDB` C API dispatch table must already have been initialised — that
481/// is, `duckdb_rs_extension_api_init` must have returned successfully. Calling
482/// this before initialisation panics inside `libduckdb-sys`.
483#[must_use]
484pub unsafe fn engine_version() -> Option<String> {
485 // SAFETY: the caller guarantees the dispatch table is initialised.
486 let ptr = unsafe { libduckdb_sys::duckdb_library_version() };
487 if ptr.is_null() {
488 return None;
489 }
490 // SAFETY: DuckDB returns a static NUL-terminated string owned by the engine.
491 let cstr = unsafe { core::ffi::CStr::from_ptr(ptr) };
492 cstr.to_str().ok().map(str::to_owned)
493}
494
495/// The `DuckDB` release this extension declares it was built against, if any.
496///
497/// Set `QUACK_RS_TARGET_DUCKDB_VERSION` when building — to the exact release
498/// whose headers `libduckdb-sys` resolved to, e.g. `v1.5.5`. [`check`] then
499/// short-circuits to [`AbiCheck::Compatible`] whenever it equals the running
500/// engine's version, without needing that release in [`expected_slot_count`]'s
501/// table.
502///
503/// **This is what keeps an extension working across a `DuckDB` release.** When
504/// `DuckDB` ships a new version, the community-extensions repository rebuilds
505/// every extension from its current source and publishes a per-release artifact,
506/// so users get a binary compiled against the new headers. That binary is
507/// correct — but without a declaration, [`check`] can only see an engine version
508/// this build of quack-rs has no verified layout for, and refuses it. The
509/// declaration closes that gap without waiting for a quack-rs release.
510///
511/// The value is an assertion by the build, not a proof. [`check`] cross-checks it
512/// against [`expected_slot_count`] when the declared release is a known one and
513/// reports [`AbiCheck::DeclaredVersionMismatch`] if they disagree.
514#[must_use]
515pub fn built_against_version() -> Option<&'static str> {
516 parse_declared_version(option_env!("QUACK_RS_BUILT_AGAINST_DUCKDB"))
517}
518
519/// The declared build target, kept only if it is a well-formed `vX.Y.Z`: a
520/// malformed declaration must not short-circuit [`check`].
521fn parse_declared_version(declared: Option<&'static str>) -> Option<&'static str> {
522 let declared = declared?;
523 parse_version(declared).map(|_| declared)
524}
525
526/// Checks whether the running `DuckDB` uses the same `duckdb_ext_api_v1` layout
527/// this extension was compiled against.
528///
529/// Returns [`AbiCheck::StableOnly`] immediately when the crate was built without
530/// the `duckdb-1-5` feature, since the stable prefix is frozen and no check is
531/// needed.
532///
533/// Otherwise, in order:
534///
535/// 1. If [`built_against_version`] is set and names a release whose verified slot
536/// count contradicts the compiled bindings, that is
537/// [`AbiCheck::DeclaredVersionMismatch`] — the build is misconfigured.
538/// 2. If it is set and equals the engine's version, the layouts match by
539/// construction: [`AbiCheck::Compatible`].
540/// 3. Otherwise the engine's version is looked up in the verified table and its
541/// slot count compared with the compiled one.
542///
543/// # Safety
544///
545/// The `DuckDB` C API dispatch table must already have been initialised — see
546/// [`engine_version`].
547#[must_use]
548pub unsafe fn check() -> AbiCheck {
549 let compiled_slots = compiled_slot_count();
550
551 if !uses_unstable_api() {
552 return AbiCheck::StableOnly;
553 }
554
555 // SAFETY: forwarded from this function's own contract.
556 let engine = unsafe { engine_version() };
557 decide(compiled_slots, built_against_version(), engine.as_deref())
558}
559
560/// The decision the ABI check makes, separated from the two things it reads
561/// from the environment: the compiled slot count and the engine's version.
562///
563/// Pure, so every branch — including engine versions that do not exist yet — is
564/// unit-testable without a live `DuckDB`.
565fn decide(compiled_slots: usize, declared: Option<&str>, engine: Option<&str>) -> AbiCheck {
566 // A declaration that contradicts the compiled bindings is a build bug, and
567 // must be reported before anything is derived from it.
568 if let Some(declared_version) = declared {
569 if let Some(declared_slots) = expected_slot_count(declared_version) {
570 if declared_slots != compiled_slots {
571 return AbiCheck::DeclaredVersionMismatch {
572 declared_version: declared_version.to_owned(),
573 declared_slots,
574 compiled_slots,
575 };
576 }
577 }
578 }
579
580 let Some(engine_version) = engine else {
581 return AbiCheck::EngineVersionUnavailable { compiled_slots };
582 };
583
584 // Built against exactly this engine: the extension's struct and the engine's
585 // struct were generated from the same release's header, so they agree even
586 // if this build of quack-rs has never heard of the release.
587 if declared.is_some_and(|d| parse_version(d) == parse_version(engine_version)) {
588 return AbiCheck::Compatible {
589 engine_version: engine_version.to_owned(),
590 slots: compiled_slots,
591 };
592 }
593
594 match expected_slot_count(engine_version) {
595 Some(engine_slots) if layout_runs_on(compiled_slots, engine_slots) => {
596 AbiCheck::Compatible {
597 engine_version: engine_version.to_owned(),
598 slots: compiled_slots,
599 }
600 }
601 Some(engine_slots) => AbiCheck::LayoutMismatch {
602 engine_version: engine_version.to_owned(),
603 engine_slots,
604 compiled_slots,
605 },
606 None => AbiCheck::UnknownEngineVersion {
607 engine_version: engine_version.to_owned(),
608 compiled_slots,
609 },
610 }
611}
612
613/// How [`init_extension`][crate::entry_point::init_extension] should react to
614/// the ABI layout check.
615///
616/// `#[non_exhaustive]`: a future release may add a policy, so a `match`
617/// outside quack-rs needs a wildcard arm.
618///
619/// ```rust,compile_fail,E0004
620/// use quack_rs::abi::AbiPolicy;
621///
622/// fn checks(policy: AbiPolicy) -> bool {
623/// match policy {
624/// AbiPolicy::Strict | AbiPolicy::Warn | AbiPolicy::AllowUnknownEngine => true,
625/// AbiPolicy::Trust => false,
626/// // error[E0004]: a wildcard arm is required
627/// }
628/// }
629/// ```
630#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
631#[non_exhaustive]
632pub enum AbiPolicy {
633 /// Refuse to load unless the layout is verified compatible.
634 ///
635 /// This is the default. It converts what would otherwise be silent
636 /// mis-dispatch into a clear `LOAD` error naming the exact remedy.
637 #[default]
638 Strict,
639 /// Perform the check and, on failure, print the diagnostic to stderr but
640 /// continue loading.
641 ///
642 /// Note the channel: this cannot use `access.set_error`, because `DuckDB`'s
643 /// loader throws whenever an extension called `set_error` — regardless of
644 /// what the entry point returned — which would make `Warn` behave exactly
645 /// like [`Strict`][Self::Strict]. The C extension API has no non-fatal
646 /// diagnostic channel, so the message goes to stderr.
647 ///
648 /// Use this when the crate is built with `duckdb-1-5` but the extension
649 /// provably calls only stable-region wrappers, and you want the mismatch
650 /// visible without failing the load. **Calling into the unstable region
651 /// after a failed check is undefined behaviour** — `Warn` does not make it
652 /// safe, it only makes it loud.
653 Warn,
654 /// Refuse a layout the table says is *different*, but allow a `DuckDB`
655 /// release the table has no entry for.
656 ///
657 /// This is the forward-compatibility knob. It still catches the dangerous,
658 /// verifiable case — an extension built against v1.5.0 meeting v1.5.5 — while
659 /// letting the extension load on a release newer than this build of quack-rs
660 /// knows about.
661 ///
662 /// **Prefer setting `QUACK_RS_TARGET_DUCKDB_VERSION` instead**, which turns
663 /// the same situation into a positive match rather than a suspended
664 /// judgement. Reach for this only when the build cannot set that variable.
665 ///
666 /// The risk is real and asymmetric: `DuckDB` changed the unstable region in
667 /// every minor release from v1.3.0 on, and in the v1.5.2 patch release, so
668 /// an unknown version is *more* likely to differ than to match. Under this policy, an extension that calls into the
669 /// unstable region on a release it was not built for is undefined behaviour.
670 /// This is not hypothetical: before `DuckDB` v1.4.5 was added to the table, a
671 /// v1.5.5 build loaded into v1.4.5 under this policy and segfaulted on its
672 /// first unstable-region call. The refusal message for an unknown engine
673 /// therefore never suggests this policy.
674 AllowUnknownEngine,
675 /// Skip the check entirely.
676 ///
677 /// Appropriate when the binary is stamped `C_STRUCT_UNSTABLE`, because
678 /// `DuckDB` then refuses to load it into any release other than the one it
679 /// was built for — making the runtime check redundant. Also appropriate when
680 /// the `duckdb-1-5` feature is enabled but the extension provably calls only
681 /// stable-region wrappers.
682 Trust,
683}
684
685#[cfg(test)]
686mod tests {
687 use super::*;
688
689 /// `u64::from_str` takes a leading `+`; a `DuckDB` version string never has
690 /// one, in any of the three parts.
691 #[test]
692 fn parse_version_refuses_a_plus_sign_in_any_part() {
693 assert_eq!(parse_version("v1.5.4"), Some((1, 5, 4)));
694 for bad in ["v+1.5.4", "1.+5.4", "v1.5.+4", "v1..4", "v1.5.", "v-1.5.4"] {
695 assert_eq!(parse_version(bad), None, "{bad}");
696 }
697 }
698
699 /// A development engine version cannot be declared or looked up, so the
700 /// refusal must not offer either as the fix: before, it told the user to
701 /// set `QUACK_RS_TARGET_DUCKDB_VERSION=v1.5.6-dev123`, which the build
702 /// silently drops.
703 #[test]
704 fn an_unknown_dev_engine_is_not_offered_remedies_that_cannot_apply() {
705 for engine in ["v1.5.6-dev123", "0d3cd0e22e", ""] {
706 let msg = AbiCheck::UnknownEngineVersion {
707 engine_version: engine.to_owned(),
708 compiled_slots: 546,
709 }
710 .error_message()
711 .expect("a refusal has a message");
712 assert!(msg.contains("not a release version"), "{engine}: {msg}");
713 assert!(
714 !msg.contains("set QUACK_RS_TARGET_DUCKDB_VERSION="),
715 "{engine}: {msg}"
716 );
717 assert!(
718 msg.contains("AbiPolicy::AllowUnknownEngine"),
719 "{engine}: {msg}"
720 );
721 }
722 // A release-shaped version keeps the declaration remedy, which works.
723 let msg = AbiCheck::UnknownEngineVersion {
724 engine_version: "v1.5.7".to_owned(),
725 compiled_slots: 546,
726 }
727 .error_message()
728 .expect("a refusal has a message");
729 assert!(
730 msg.contains("set QUACK_RS_TARGET_DUCKDB_VERSION=v1.5.7"),
731 "{msg}"
732 );
733 }
734
735 #[test]
736 fn struct_size_is_a_whole_number_of_pointers() {
737 assert_eq!(
738 size_of::<duckdb_ext_api_v1>() % size_of::<*const c_void>(),
739 0
740 );
741 }
742
743 #[test]
744 fn compiled_layout_is_one_we_have_verified() {
745 let slots = compiled_slot_count();
746 assert!(
747 KNOWN_LAYOUTS.iter().any(|&(_, _, _, _, s)| s == slots),
748 "libduckdb-sys resolved to a duckdb_ext_api_v1 with {slots} slots, which is not in \
749 KNOWN_LAYOUTS. Re-run scripts/check-abi-table.py and add the new DuckDB release."
750 );
751 }
752
753 #[test]
754 fn stable_prefix_fits_inside_every_known_layout() {
755 for &(_, _, _, _, slots) in KNOWN_LAYOUTS {
756 assert!(slots > STABLE_API_SLOT_COUNT);
757 }
758 }
759
760 #[test]
761 fn known_layouts_are_sorted_and_non_overlapping() {
762 let mut prev: Option<(u64, u64, u64)> = None;
763 for &(ma, mi, lo, hi, _) in KNOWN_LAYOUTS {
764 assert!(lo <= hi, "patch range {lo}..={hi} is inverted");
765 let key = (ma, mi, lo);
766 if let Some(p) = prev {
767 assert!(p < key, "KNOWN_LAYOUTS must be sorted: {p:?} !< {key:?}");
768 }
769 prev = Some(key);
770 }
771 }
772
773 #[test]
774 fn slot_count_uniquely_identifies_a_layout() {
775 // Two release families may not claim the same slot count, otherwise the
776 // check in `check()` could pass for a layout it has not verified.
777 let mut seen: Vec<usize> = KNOWN_LAYOUTS.iter().map(|&(.., s)| s).collect();
778 seen.sort_unstable();
779 let len_before = seen.len();
780 seen.dedup();
781 assert_eq!(
782 len_before,
783 seen.len(),
784 "duplicate slot counts in KNOWN_LAYOUTS"
785 );
786 }
787
788 #[test]
789 fn parses_version_strings() {
790 assert_eq!(parse_version("v1.5.4"), Some((1, 5, 4)));
791 assert_eq!(parse_version("1.5.4"), Some((1, 5, 4)));
792 assert_eq!(parse_version("v1.5"), None);
793 assert_eq!(parse_version("v1.5.4.1"), None);
794 assert_eq!(parse_version("v1.6.0-dev1234"), None);
795 assert_eq!(parse_version(""), None);
796 assert_eq!(parse_version("nonsense"), None);
797 }
798
799 #[test]
800 fn maps_every_documented_release_family() {
801 for (version, slots) in [
802 ("v1.2.0", 408),
803 ("v1.2.2", 408),
804 ("v1.3.0", 428),
805 ("v1.3.2", 428),
806 ("v1.4.0", 459),
807 ("v1.4.4", 459),
808 ("v1.4.5", 459),
809 ("v1.5.0", 545),
810 ("v1.5.1", 545),
811 ("v1.5.2", 546),
812 ("v1.5.5", 546),
813 ("v1.5.6", 546),
814 ("v2.0.0", 548),
815 ] {
816 assert_eq!(expected_slot_count(version), Some(slots), "for {version}");
817 }
818 }
819
820 /// The scenario the `abi-guard` CI job builds: `QUACK_RS_TARGET_DUCKDB_VERSION`
821 /// declares v1.2.0 (408 slots) while `libduckdb-sys` is pinned to
822 /// =1.10500.0, i.e. `DuckDB` 1.5.0's 545-slot layout.
823 ///
824 /// The job asserts on this exact message, and it must fire whatever the
825 /// engine reports — the runner pulls `releases/latest`, so anything that
826 /// depends on the engine version differing from the pin is a coin flip.
827 /// Every engine argument below must reach the same verdict.
828 #[test]
829 fn declared_version_mismatch_matches_the_ci_regression_test() {
830 for engine in [None, Some("v1.5.0"), Some("v1.5.5"), Some("v9.9.9")] {
831 let check = decide(545, Some("v1.2.0"), engine);
832 assert!(
833 matches!(check, AbiCheck::DeclaredVersionMismatch { .. }),
834 "engine {engine:?} gave {check:?}"
835 );
836 assert!(!check.is_compatible());
837 let msg = check.error_message().expect("a refusal carries a message");
838 assert!(
839 msg.contains(
840 "QUACK_RS_TARGET_DUCKDB_VERSION says this extension was built against DuckDB"
841 ),
842 "the CI job greps for this exact prefix: {msg}"
843 );
844 }
845 }
846
847 #[test]
848 fn does_not_extrapolate_beyond_verified_patches() {
849 // Releases absent from the table (unreleased at the time it was last
850 // regenerated) are unknown; guessing would defeat the purpose of the
851 // guard.
852 assert_eq!(expected_slot_count("v1.4.6"), None);
853 assert_eq!(expected_slot_count("v1.5.7"), None);
854 assert_eq!(expected_slot_count("v1.6.0"), None);
855 assert_eq!(expected_slot_count("v2.0.1"), None);
856 assert_eq!(expected_slot_count("v2.1.0"), None);
857 }
858
859 #[test]
860 fn compatible_and_stable_only_are_the_only_passing_states() {
861 assert!(AbiCheck::StableOnly.is_compatible());
862 assert!(AbiCheck::Compatible {
863 engine_version: "v1.5.4".into(),
864 slots: 546
865 }
866 .is_compatible());
867 assert!(!AbiCheck::LayoutMismatch {
868 engine_version: "v1.5.0".into(),
869 engine_slots: 545,
870 compiled_slots: 546
871 }
872 .is_compatible());
873 assert!(!AbiCheck::UnknownEngineVersion {
874 engine_version: "v9.9.9".into(),
875 compiled_slots: 546
876 }
877 .is_compatible());
878 assert!(!AbiCheck::EngineVersionUnavailable {
879 compiled_slots: 546
880 }
881 .is_compatible());
882 }
883
884 #[test]
885 fn passing_states_have_no_error_message() {
886 assert!(AbiCheck::StableOnly.error_message().is_none());
887 assert!(AbiCheck::Compatible {
888 engine_version: "v1.5.4".into(),
889 slots: 546
890 }
891 .error_message()
892 .is_none());
893 }
894
895 #[test]
896 fn mismatch_message_names_both_layouts_and_the_remedy() {
897 let msg = AbiCheck::LayoutMismatch {
898 engine_version: "v1.5.0".into(),
899 engine_slots: 545,
900 compiled_slots: 546,
901 }
902 .error_message()
903 .expect("mismatch must produce a message");
904 assert!(msg.contains("546"));
905 assert!(msg.contains("545"));
906 assert!(msg.contains("v1.5.0"));
907 // The remedy must be the stamping DuckDB 2.0 still loads: `C_STRUCT`
908 // pinned to C API v1.5.6. `C_STRUCT_UNSTABLE` is named only as the
909 // thing not to do.
910 assert!(msg.contains("--abi-type C_STRUCT --duckdb-version v1.5.6"));
911 assert!(msg.contains("Not `C_STRUCT_UNSTABLE`"));
912 }
913
914 #[test]
915 fn unavailable_version_message_mentions_the_missing_probe() {
916 let msg = AbiCheck::EngineVersionUnavailable {
917 compiled_slots: 546,
918 }
919 .error_message()
920 .expect("unavailable version must produce a message");
921 assert!(msg.contains("duckdb_library_version"));
922 }
923
924 // ── The decision matrix ─────────────────────────────────────────────
925 //
926 // `decide` is the whole guard. These pin every branch, including engine
927 // versions that do not exist yet — which is the case that decides whether an
928 // extension survives a DuckDB release.
929
930 #[test]
931 fn a_known_engine_with_a_matching_layout_is_compatible() {
932 assert!(matches!(
933 decide(546, None, Some("v1.5.4")),
934 AbiCheck::Compatible { slots: 546, .. }
935 ));
936 }
937
938 #[test]
939 fn a_known_engine_with_a_different_layout_is_a_mismatch() {
940 assert!(matches!(
941 decide(546, None, Some("v1.5.0")),
942 AbiCheck::LayoutMismatch {
943 engine_slots: 545,
944 compiled_slots: 546,
945 ..
946 }
947 ));
948 }
949
950 /// Regression: `DuckDB` v1.4.5 (459 slots) was missing from the table, so a
951 /// 546-slot extension loaded into it was `UnknownEngineVersion` rather than
952 /// a mismatch — and `AllowUnknownEngine` then let it load and segfault on
953 /// its first unstable-region call. Every policy that refuses a verified
954 /// mismatch must now refuse it.
955 #[test]
956 fn duckdb_1_4_5_is_a_verified_mismatch_for_a_1_5_build() {
957 for compiled in [545, 546] {
958 assert!(
959 matches!(
960 decide(compiled, None, Some("v1.4.5")),
961 AbiCheck::LayoutMismatch {
962 engine_slots: 459,
963 ..
964 }
965 ),
966 "compiled {compiled}"
967 );
968 }
969 }
970
971 /// Regression: `DuckDB` v1.5.6 shipped after the table was last
972 /// regenerated, so a `duckdb-1-5` extension built against it (or against
973 /// v1.5.5) was refused as `UnknownEngineVersion` by the current `DuckDB`
974 /// release. Its layout is the 546-slot one of v1.5.2 – v1.5.5.
975 #[test]
976 fn duckdb_1_5_6_has_the_1_5_2_layout() {
977 assert!(matches!(
978 decide(546, None, Some("v1.5.6")),
979 AbiCheck::Compatible { slots: 546, .. }
980 ));
981 assert!(matches!(
982 decide(545, None, Some("v1.5.6")),
983 AbiCheck::LayoutMismatch {
984 engine_slots: 546,
985 compiled_slots: 545,
986 ..
987 }
988 ));
989 }
990
991 /// `DuckDB` v2.0.0 appended two slots to the v1.5.2 – v1.5.6 layout, so a
992 /// build against those bindings runs on it; a 1.5.0 build (545 slots, which
993 /// v1.5.2 inserted into) does not, and neither does a 2.0 build on 1.5.6,
994 /// which would read past the end of the engine's struct.
995 #[test]
996 fn duckdb_2_0_0_appends_to_the_1_5_2_layout() {
997 assert!(matches!(
998 decide(546, None, Some("v2.0.0")),
999 AbiCheck::Compatible { slots: 546, .. }
1000 ));
1001 assert!(matches!(
1002 decide(548, None, Some("v2.0.0")),
1003 AbiCheck::Compatible { slots: 548, .. }
1004 ));
1005 assert!(matches!(
1006 decide(545, None, Some("v2.0.0")),
1007 AbiCheck::LayoutMismatch {
1008 engine_slots: 548,
1009 compiled_slots: 545,
1010 ..
1011 }
1012 ));
1013 assert!(matches!(
1014 decide(548, None, Some("v1.5.6")),
1015 AbiCheck::LayoutMismatch {
1016 engine_slots: 546,
1017 compiled_slots: 548,
1018 ..
1019 }
1020 ));
1021 // Not extrapolated to an unverified patch release.
1022 assert!(matches!(
1023 decide(546, None, Some("v2.0.1")),
1024 AbiCheck::UnknownEngineVersion { .. }
1025 ));
1026 }
1027
1028 /// `DuckDB` v2.0.1 (due 2026-11-18) is not in the table, and nothing in
1029 /// `DuckDB`'s own header promises a 2.0.x patch release keeps v2.0.0's
1030 /// layout (see "A `DuckDB` release the table has not seen" in the module
1031 /// docs). So until it is verified and listed, a `duckdb-1-5` build — on the
1032 /// 1.5.6 or the 2.0.0 bindings — reports it as unknown, which
1033 /// `AbiPolicy::Strict` refuses with a message naming the remedies, and a
1034 /// build that declares v2.0.1 itself is accepted.
1035 #[test]
1036 fn duckdb_2_0_1_is_unknown_until_the_table_lists_it() {
1037 assert_eq!(expected_slot_count("v2.0.1"), None);
1038 for compiled in [546, 548] {
1039 let check = decide(compiled, None, Some("v2.0.1"));
1040 assert_eq!(
1041 check,
1042 AbiCheck::UnknownEngineVersion {
1043 engine_version: "v2.0.1".into(),
1044 compiled_slots: compiled,
1045 },
1046 "{compiled}-slot build"
1047 );
1048 let msg = check.error_message().expect("a refusal has a message");
1049 assert!(
1050 msg.contains("set QUACK_RS_TARGET_DUCKDB_VERSION=v2.0.1"),
1051 "{msg}"
1052 );
1053 assert!(msg.contains("upgrade quack-rs"), "{msg}");
1054 assert!(
1055 matches!(
1056 decide(compiled, Some("v2.0.1"), Some("v2.0.1")),
1057 AbiCheck::Compatible { .. }
1058 ),
1059 "{compiled}-slot build declaring v2.0.1"
1060 );
1061 }
1062 // Declaring v2.0.0 does not vouch for v2.0.1 either.
1063 assert!(matches!(
1064 decide(548, Some("v2.0.0"), Some("v2.0.1")),
1065 AbiCheck::UnknownEngineVersion { .. }
1066 ));
1067 }
1068
1069 #[test]
1070 fn prefix_pairs_name_known_layouts_smaller_first() {
1071 for &(small, large) in PREFIX_LAYOUTS {
1072 assert!(small < large, "({small}, {large}) is not smaller-first");
1073 for slots in [small, large] {
1074 assert!(
1075 KNOWN_LAYOUTS.iter().any(|&(.., s)| s == slots),
1076 "{slots} is not a KNOWN_LAYOUTS slot count"
1077 );
1078 }
1079 }
1080 }
1081
1082 #[test]
1083 fn an_unknown_engine_is_unknown_without_a_declaration() {
1084 assert!(matches!(
1085 decide(546, None, Some("v1.6.0")),
1086 AbiCheck::UnknownEngineVersion { .. }
1087 ));
1088 }
1089
1090 #[test]
1091 fn declaring_the_engine_version_makes_an_unknown_release_compatible() {
1092 // The scenario that matters: DuckDB 1.6.0 ships, the community
1093 // repository rebuilds the extension against 1.6.0's headers, and the
1094 // build declares it. quack-rs has never heard of 1.6.0 and must still
1095 // accept it — the two structs came from the same header.
1096 assert!(matches!(
1097 decide(560, Some("v1.6.0"), Some("v1.6.0")),
1098 AbiCheck::Compatible { slots: 560, .. }
1099 ));
1100 }
1101
1102 #[test]
1103 fn a_declaration_for_a_different_release_does_not_excuse_a_known_mismatch() {
1104 // Declared v1.5.4 (546) matches the compiled 546, so the declaration is
1105 // self-consistent — but the engine is v1.5.0, which is verifiably 545.
1106 assert!(matches!(
1107 decide(546, Some("v1.5.4"), Some("v1.5.0")),
1108 AbiCheck::LayoutMismatch {
1109 engine_slots: 545,
1110 compiled_slots: 546,
1111 ..
1112 }
1113 ));
1114 }
1115
1116 #[test]
1117 fn a_declaration_contradicting_the_bindings_is_reported_first() {
1118 // Declared v1.5.5 (546 slots) but only 545 compiled in: Cargo resolved a
1119 // different libduckdb-sys than the build intended. Reported even though
1120 // the engine would otherwise look fine.
1121 assert!(matches!(
1122 decide(545, Some("v1.5.5"), Some("v1.5.0")),
1123 AbiCheck::DeclaredVersionMismatch {
1124 declared_slots: 546,
1125 compiled_slots: 545,
1126 ..
1127 }
1128 ));
1129 }
1130
1131 #[test]
1132 fn an_unparseable_engine_version_is_unknown_not_a_match() {
1133 // A `-dev` build reports something like "v1.6.0-dev1234", which
1134 // `parse_version` rejects. It must not silently equal a declaration.
1135 assert!(matches!(
1136 decide(546, Some("v1.6.0"), Some("v1.6.0-dev1234")),
1137 AbiCheck::UnknownEngineVersion { .. }
1138 ));
1139 }
1140
1141 #[test]
1142 fn a_missing_engine_version_is_never_compatible() {
1143 assert!(matches!(
1144 decide(546, Some("v1.5.4"), None),
1145 AbiCheck::EngineVersionUnavailable { .. }
1146 ));
1147 }
1148
1149 #[test]
1150 fn declared_version_is_none_unless_it_parses() {
1151 // Nothing is set in this crate's own build, so it must be absent rather
1152 // than a bogus value that would short-circuit the check.
1153 assert_eq!(built_against_version(), None);
1154 }
1155
1156 #[test]
1157 fn built_against_version_is_the_build_scripts_declaration() {
1158 // Holds however the crate was built: the value is exactly what build.rs
1159 // forwarded from QUACK_RS_TARGET_DUCKDB_VERSION, filtered for validity.
1160 assert_eq!(
1161 built_against_version(),
1162 option_env!("QUACK_RS_BUILT_AGAINST_DUCKDB").filter(|v| parse_version(v).is_some())
1163 );
1164 }
1165
1166 #[test]
1167 fn a_declared_version_is_kept_only_if_it_parses() {
1168 assert_eq!(parse_declared_version(None), None);
1169 assert_eq!(parse_declared_version(Some("v1.5.5")), Some("v1.5.5"));
1170 assert_eq!(parse_declared_version(Some("1.4.4")), Some("1.4.4"));
1171 assert_eq!(parse_declared_version(Some("v1.6.0-dev42")), None);
1172 assert_eq!(parse_declared_version(Some("latest")), None);
1173 assert_eq!(parse_declared_version(Some("")), None);
1174 }
1175
1176 #[test]
1177 fn declared_version_mismatch_is_a_failure_with_a_diagnostic() {
1178 let check = AbiCheck::DeclaredVersionMismatch {
1179 declared_version: "v1.5.0".into(),
1180 declared_slots: 545,
1181 compiled_slots: 546,
1182 };
1183 assert!(!check.is_compatible());
1184 let msg = check.error_message().expect("must produce a message");
1185 assert!(msg.contains("QUACK_RS_TARGET_DUCKDB_VERSION"), "{msg}");
1186 assert!(msg.contains("545") && msg.contains("546"), "{msg}");
1187 assert!(msg.contains("libduckdb-sys"), "{msg}");
1188 }
1189
1190 #[test]
1191 fn unknown_version_message_lists_every_remedy_in_order() {
1192 let msg = AbiCheck::UnknownEngineVersion {
1193 engine_version: "v1.6.0".into(),
1194 compiled_slots: 546,
1195 }
1196 .error_message()
1197 .expect("unknown version must produce a message");
1198 // The message is what a user sees when a new DuckDB ships, so it has to
1199 // name the fix that does not require a quack-rs release first.
1200 let declare = msg
1201 .find("QUACK_RS_TARGET_DUCKDB_VERSION")
1202 .expect("declare remedy");
1203 let upgrade = msg.find("upgrade quack-rs").expect("upgrade remedy");
1204 let stable = msg
1205 .find("without the `duckdb-1-5`")
1206 .expect("stable-only remedy");
1207 assert!(declare < upgrade && upgrade < stable, "{msg}");
1208 // Never advise the opt-out: an unknown engine is exactly the case where
1209 // it can load a mis-dispatching binary (DuckDB v1.4.5 segfaulted this
1210 // way before it was added to the table).
1211 assert!(!msg.contains("AllowUnknownEngine"), "{msg}");
1212 }
1213
1214 #[test]
1215 fn mismatch_message_for_a_pre_1_5_engine_does_not_advise_an_impossible_rebuild() {
1216 // A `duckdb-1-5` build cannot be compiled against DuckDB 1.4 headers, so
1217 // "rebuild against v1.4.4" alone is not actionable.
1218 let msg = AbiCheck::LayoutMismatch {
1219 engine_version: "v1.4.4".into(),
1220 engine_slots: 459,
1221 compiled_slots: 546,
1222 }
1223 .error_message()
1224 .expect("mismatch must produce a message");
1225 assert!(msg.contains("older than v1.5.0"), "{msg}");
1226 assert!(!msg.contains("AllowUnknownEngine"), "{msg}");
1227 let msg = AbiCheck::LayoutMismatch {
1228 engine_version: "v1.5.0".into(),
1229 engine_slots: 545,
1230 compiled_slots: 546,
1231 }
1232 .error_message()
1233 .expect("mismatch must produce a message");
1234 assert!(!msg.contains("older than v1.5.0"), "{msg}");
1235 }
1236
1237 #[test]
1238 fn policies_are_ordered_from_safest_to_loosest() {
1239 // Strict and AllowUnknownEngine both reject a known-different layout;
1240 // only Trust skips the check outright. Pinned so a future variant does
1241 // not quietly widen the default.
1242 assert_eq!(AbiPolicy::default(), AbiPolicy::Strict);
1243 assert_ne!(AbiPolicy::AllowUnknownEngine, AbiPolicy::Trust);
1244 assert_ne!(AbiPolicy::AllowUnknownEngine, AbiPolicy::Strict);
1245 }
1246
1247 #[test]
1248 fn default_policy_is_strict() {
1249 assert_eq!(AbiPolicy::default(), AbiPolicy::Strict);
1250 }
1251
1252 #[test]
1253 fn unstable_api_flag_tracks_the_feature() {
1254 assert_eq!(uses_unstable_api(), cfg!(feature = "duckdb-1-5"));
1255 }
1256}
1257
1258/// End-to-end checks that need a live `DuckDB` dispatch table.
1259///
1260/// `InMemoryDb::open()` initialises the `loadable-extension` dispatch table from
1261/// the linked `DuckDB`, which is exactly the state an extension is in after
1262/// `duckdb_rs_extension_api_init` succeeds — so these exercise the real probe
1263/// rather than a stub.
1264#[cfg(all(test, feature = "_duckdb-testing"))]
1265mod live_tests {
1266 use super::*;
1267
1268 #[test]
1269 fn engine_version_is_readable_and_parses() {
1270 let _db = crate::testing::InMemoryDb::open().expect("open in-memory DuckDB");
1271 // SAFETY: InMemoryDb::open() initialised the dispatch table.
1272 let version = unsafe { engine_version() }.expect("duckdb_library_version()");
1273 assert!(
1274 parse_version(&version).is_some(),
1275 "engine reported an unparseable version: {version:?}"
1276 );
1277 }
1278
1279 #[test]
1280 fn linked_engine_layout_matches_the_compiled_bindings() {
1281 let _db = crate::testing::InMemoryDb::open().expect("open in-memory DuckDB");
1282 // SAFETY: InMemoryDb::open() initialised the dispatch table.
1283 let version = unsafe { engine_version() }.expect("duckdb_library_version()");
1284 assert_eq!(
1285 expected_slot_count(&version),
1286 Some(compiled_slot_count()),
1287 "KNOWN_LAYOUTS says DuckDB {version} has a different duckdb_ext_api_v1 slot count \
1288 than the libduckdb-sys bindings this crate compiled against ({} slots). Re-run \
1289 scripts/check-abi-table.py.",
1290 compiled_slot_count()
1291 );
1292 }
1293
1294 #[test]
1295 fn check_reports_compatibility_against_the_linked_engine() {
1296 let _db = crate::testing::InMemoryDb::open().expect("open in-memory DuckDB");
1297 // SAFETY: InMemoryDb::open() initialised the dispatch table.
1298 let result = unsafe { check() };
1299 assert!(
1300 result.is_compatible(),
1301 "ABI check failed against the linked DuckDB: {result:?}"
1302 );
1303 assert!(result.error_message().is_none());
1304 }
1305}