clippy: no workspace reports an error, and the unsafe FFI states its contract #241

Merged
dcharlot merged 1 commit from fix/clippy-sweep into main 2026-10-14 01:11:18 -04:00
14 changed files with 80 additions and 19 deletions

View file

@ -102,7 +102,7 @@ pub const MAX_ORIGINS: usize = 64;
/// conservative over-approximation a ceiling can never satisfy unless it, too, is
/// `Any`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", try_from = "OriginsWire")]
#[serde(rename_all = "kebab-case", from = "OriginsWire")]
pub enum Origins {
Set(BTreeSet<Origin>),
Any,
@ -118,13 +118,12 @@ enum OriginsWire {
Any,
}
impl TryFrom<OriginsWire> for Origins {
type Error = core::convert::Infallible;
fn try_from(wire: OriginsWire) -> Result<Self, Self::Error> {
Ok(match wire {
impl From<OriginsWire> for Origins {
fn from(wire: OriginsWire) -> Self {
match wire {
OriginsWire::Set(set) => Origins::Set(set).normalized(),
OriginsWire::Any => Origins::Any,
})
}
}
}

View file

@ -834,7 +834,7 @@ mod tests {
);
for value in [
PropValue::Text("hi".into()),
PropValue::Number(3.14),
PropValue::Number(2.5),
PropValue::Bool(true),
PropValue::Null,
] {

View file

@ -6986,7 +6986,7 @@ mod f16_tests {
let (nq, nkv) = (n_qh * hd, n_kvh * hd);
let nw: Vec<f32> = (0..kd).map(|i| 0.8 + ((i % 5) as f32) * 0.1).collect();
let eps = 1e-6f32;
let (q_scale, k_scale) = (1.4142135f32, 1.0f32);
let (q_scale, k_scale) = (std::f32::consts::SQRT_2, 1.0f32);
let mk = |seed: usize, rows: usize, cols: usize| -> (Vec<f32>, Vec<u8>) {
let wf: Vec<f32> = (0..rows * cols)
.map(|i| (((i + seed) % 9) as f32 - 4.0) * 0.07)

View file

@ -310,7 +310,7 @@ mod tests {
Score::new(
input.iter().sum::<f64>().abs(),
OutlierExplanation {
nearest_neighbour_distance: 3.14,
nearest_neighbour_distance: 2.5,
features_deviated: vec!["joules_uj".into()],
},
"dummy-outlier",

View file

@ -939,6 +939,8 @@ mod tests {
}
#[test]
// `0 *` spells the (row, col) cell address; it is not a dropped term.
#[allow(clippy::erasing_op)]
fn verify_coverage_matrix_shape() {
let c = sample_contract();
let mut ev = Evidence::new();

View file

@ -559,7 +559,12 @@ impl Gemma4 {
for j in j0..=i {
let mut acc = 0f32;
for x in 0..hd {
acc += qh[(hh * s + i) * hd + x] * kh[(0 * s + j) * hd + x];
// `0 *` names the shared kv head (MQA) rather than
// dropping the term, mirroring the `hh * s` above.
#[allow(clippy::erasing_op)]
{
acc += qh[(hh * s + i) * hd + x] * kh[(0 * s + j) * hd + x];
}
}
// Gemma-2 attn-logit softcap: logits = sc·tanh(logits/sc).
// Gemma-4 path: attn_softcap=0 → no-op.
@ -579,7 +584,11 @@ impl Gemma4 {
for x in 0..hd {
let mut acc = 0f32;
for j in j0..=i {
acc += sc[j] / den * vh[(0 * s + j) * hd + x];
// `0 *` names the shared kv head (MQA), as above.
#[allow(clippy::erasing_op)]
{
acc += sc[j] / den * vh[(0 * s + j) * hd + x];
}
}
attn_out[(i * c.n_heads + hh) * hd + x] = acc;
}

View file

@ -403,7 +403,7 @@ mod tests {
assert!(silu(-10.0).abs() < 1e-3);
assert!((silu(1.0) - 0.731_058_6).abs() < 1e-5);
// softplus(0)=ln2, monotone, stable at extremes
assert!((softplus(0.0) - 0.693_147_2).abs() < 1e-5);
assert!((softplus(0.0) - std::f32::consts::LN_2).abs() < 1e-5);
assert_eq!(softplus(30.0), 30.0);
assert!(softplus(-30.0) > 0.0 && softplus(-30.0) < 1e-12);
// relu2

View file

@ -493,7 +493,7 @@ mod tests {
fn outlier_explanation_round_trips_through_json() {
let e = OutlierExplanation {
features_deviated: vec!["joules".into()],
deviation_metric: 3.14,
deviation_metric: 2.5,
threshold: 1.5,
summary: "x outside fence".into(),
};

View file

@ -36,7 +36,10 @@ fn main() -> std::io::Result<()> {
fn parse_args() -> Policy {
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
// Every arm below returns or exits, so only the first argument is ever
// examined; `if let` says that, where a loop implied iteration that
// cannot happen.
if let Some(arg) = args.next() {
match arg.as_str() {
"--policy" => {
let path = args.next().unwrap_or_else(|| {

View file

@ -110,6 +110,7 @@ fn scatter_2d_axis_1() {
/// (shape `[n_heads, new_seq, d_head]`) into a preallocated buffer (shape
/// `[n_heads, max_seq, d_head]`) at position `pos`.
#[test]
#[allow(clippy::erasing_op)] // `0 *` spells head 0; not a dropped term.
fn scatter_3d_kv_cache_pattern() {
let n_heads = 2;
let max_seq = 6;

View file

@ -19450,7 +19450,7 @@ mod tests {
#[test]
fn format_math_result_decimal() {
assert_eq!(format_math_result(3.14), "3.14");
assert_eq!(format_math_result(2.75), "2.75");
}
// ── MIDI / Music ──

View file

@ -157,10 +157,9 @@ mod tests {
let dst = InMemoryVault::new(cfg());
src.insert(doc("urn:a")).await.expect("insert src");
dst.insert(doc("urn:a")).await.expect("insert dst");
// Bump source twice.
let mut s = src.get("urn:a").await.expect("get src");
let cur = s.sequence;
s.sequence = cur;
// `update` takes the document at its current sequence and bumps it,
// so one update leaves the source one ahead of the target.
let s = src.get("urn:a").await.expect("get src");
let _ = src.update(s).await.expect("update src");
let r = sync(&src, &dst).await.expect("sync");
assert_eq!(r.updated, vec!["urn:a".to_string()]);

View file

@ -305,6 +305,9 @@ pub unsafe extern "C" fn wai_int_payload_declared(
/// *Candidate capabilities*), and a payload that is not the format SPEC §5 pins its
/// integer capability or fallback to (*Payloads of the WAI-native integer codecs*):
/// it emits through `Wai::to_emit_bytes`.
///
/// # Safety
/// `manifest_json` NUL-terminated; `payload` valid for `payload_len` bytes; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_envelope_pack(
manifest_json: *const c_char,
@ -336,6 +339,9 @@ pub unsafe extern "C" fn wai_envelope_pack(
/// Detect WAI version from a byte stream. Returns 1 (WAI1), 2 (WAI2),
/// or 0 with an error message in `wai_last_error` for unknown magic.
///
/// # Safety
/// `bytes` valid for `len` bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_envelope_detect_version(
bytes: *const u8, len: usize,
@ -422,6 +428,9 @@ pub unsafe extern "C" fn wai_envelope_pack_multi(
/// This avoids exposing a C struct array (and the ownership pain that
/// comes with it). Any JSON parser the consumer already has decodes
/// the rendition table in two lines.
///
/// # Safety
/// `bytes` valid for `len` bytes; `out_manifest` writable; `out_renditions_json` writable; `out_payload_block` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_envelope_unpack_multi(
bytes: *const u8, len: usize,
@ -499,6 +508,9 @@ pub unsafe extern "C" fn wai_envelope_unpack_multi(
/// Parses a WAI envelope. Writes the manifest JSON exactly as the envelope
/// carries it to `out_manifest` (so `security`, and members this library does not
/// model, survive) and the raw payload to `out_payload`.
///
/// # Safety
/// `bytes` valid for `len` bytes; `out_manifest` writable; `out_payload` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_envelope_unpack(
bytes: *const u8, len: usize,

View file

@ -44,6 +44,9 @@ pub unsafe extern "C" fn wai_image_png_encode(
}
/// Decode a PNG byte stream to RGB. Returns `(rgb, h, w)`.
///
/// # Safety
/// `bytes` valid for `len` bytes; `out` writable; `out_h` writable; `out_w` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_image_png_decode(
bytes: *const u8, len: usize, out: *mut WaiBuffer,
@ -88,6 +91,8 @@ where F: FnOnce() -> std::result::Result<(Vec<u8>, u32, u32), (c_int, String)> +
}
// ---- image: AVIF ----------------------------------------------------
/// # Safety
/// `rgb` valid for `len` bytes; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_image_avif_encode(
rgb: *const u8, len: usize, h: u32, w: u32, quality: u8,
@ -108,6 +113,8 @@ pub unsafe extern "C" fn wai_image_avif_encode(
})
}
/// # Safety
/// `bytes` valid for `len` bytes; `out` writable; `out_h` writable; `out_w` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_image_avif_decode(
bytes: *const u8, len: usize, out: *mut WaiBuffer,
@ -127,6 +134,9 @@ pub unsafe extern "C" fn wai_image_avif_decode(
// ---- image: JPEG-XL -------------------------------------------------
/// `quality = 0` ⇒ lossless. Otherwise butteraugli distance proxy
/// (higher quality = smaller distance internally).
///
/// # Safety
/// `rgb` valid for `len` bytes; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_image_jxl_encode(
rgb: *const u8, len: usize, h: u32, w: u32, quality: u8,
@ -148,6 +158,8 @@ pub unsafe extern "C" fn wai_image_jxl_encode(
})
}
/// # Safety
/// `bytes` valid for `len` bytes; `out` writable; `out_h` writable; `out_w` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_image_jxl_decode(
bytes: *const u8, len: usize, out: *mut WaiBuffer,
@ -165,6 +177,8 @@ pub unsafe extern "C" fn wai_image_jxl_decode(
}
// ---- audio: Opus ----------------------------------------------------
/// # Safety
/// `samples` valid for `n` `f32`s; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_audio_opus_encode(
samples: *const f32, n: usize, sr: u32, bitrate_bps: i32,
@ -181,6 +195,8 @@ pub unsafe extern "C" fn wai_audio_opus_encode(
})
}
/// # Safety
/// `bytes` valid for `len` bytes; `out` writable; `out_sr` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_audio_opus_decode(
bytes: *const u8, len: usize, out: *mut WaiBuffer, out_sr: *mut u32,
@ -213,6 +229,8 @@ pub unsafe extern "C" fn wai_audio_opus_decode(
}
// ---- audio: FLAC ----------------------------------------------------
/// # Safety
/// `samples` valid for `n` `f32`s; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_audio_flac_encode(
samples: *const f32, n: usize, sr: u32, out: *mut WaiBuffer,
@ -228,6 +246,8 @@ pub unsafe extern "C" fn wai_audio_flac_encode(
})
}
/// # Safety
/// `bytes` valid for `len` bytes; `out` writable; `out_sr` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_audio_flac_decode(
bytes: *const u8, len: usize, out: *mut WaiBuffer, out_sr: *mut u32,
@ -257,6 +277,8 @@ pub unsafe extern "C" fn wai_audio_flac_decode(
}
// ---- text: zstd / xz ------------------------------------------------
/// # Safety
/// `data` valid for `len` bytes; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_text_zstd_encode(
data: *const u8, len: usize, level: i32, out: *mut WaiBuffer,
@ -274,6 +296,9 @@ pub unsafe extern "C" fn wai_text_zstd_encode(
/// and [`TEXT_WINDOW_MAX_LEN`](crate::codecs::text::TEXT_WINDOW_MAX_LEN) bytes of
/// window. A payload past either is refused with `WAI_ERR_CODEC`; the message begins
/// `text_decoded_too_long` or `text_window_too_large`.
///
/// # Safety
/// `bytes` valid for `len` bytes; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_text_zstd_decode(
bytes: *const u8, len: usize, out: *mut WaiBuffer,
@ -286,6 +311,8 @@ pub unsafe extern "C" fn wai_text_zstd_decode(
})
}
/// # Safety
/// `data` valid for `len` bytes; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_text_xz_encode(
data: *const u8, len: usize, level: u32, out: *mut WaiBuffer,
@ -300,6 +327,9 @@ pub unsafe extern "C" fn wai_text_xz_encode(
/// Decode a `wai.text.xz` payload within the same limits as
/// [`wai_text_zstd_decode`], the window limit applying to the dictionary.
///
/// # Safety
/// `bytes` valid for `len` bytes; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_text_xz_decode(
bytes: *const u8, len: usize, out: *mut WaiBuffer,
@ -314,6 +344,9 @@ pub unsafe extern "C" fn wai_text_xz_decode(
// ---- video: AV1 -----------------------------------------------------
/// Encode a sequence of `n` RGB frames as AV1.
///
/// # Safety
/// `rgb` valid for `len` bytes; `out` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_video_av1_encode(
rgb: *const u8, len: usize,
@ -346,6 +379,9 @@ pub unsafe extern "C" fn wai_video_av1_encode(
}
/// Decode an AV1 WAI payload to a packed RGB buffer `n*h*w*3` bytes.
///
/// # Safety
/// `bytes` valid for `len` bytes; `out` writable; `out_n` writable; `out_h` writable; `out_w` writable; `out_fps_num` writable; `out_fps_den` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wai_video_av1_decode(
bytes: *const u8, len: usize, out: *mut WaiBuffer,