From 3c5599595697f96bf11d1723f90d24b96db7aad5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:37:31 -0800 Subject: [PATCH 01/33] craft-testkit: fonts renames a test face's family and builds TrueType collections Add the fonts module. rename_family(bytes, from, to) replaces a family name of the same UTF-16 length in the family records (name IDs 1, 16 and 21) and in full names (ID 4) that are the name or start with it followed by a space, in UTF-16BE and ASCII Macintosh Roman records, and writes the name table checksum and head.checkSumAdjustment. collection(faces) builds a TTC 1.0 with each face's own tables, four-byte padding, file-relative offsets, zeroed checkSumAdjustment and checksums of the copied tables. Both return a FontError instead of panicking: names of different lengths, no family record holding the name, a face shorter than its table directory, tables or name strings out of range, shared name storage that a rename would change, a collection given as a face, and output past the 4 GiB that 32-bit offsets reach. The code comes from the rename and collection helpers in VectorCraft, DesignCraft and WordCraft font tests. Their tests need each app's font database and bundled fonts, so they stay in the apps; tests/fonts.rs tests the module on faces built in memory. --- crates/testkit/README.md | 19 ++ crates/testkit/src/fonts.rs | 498 ++++++++++++++++++++++++++++++ crates/testkit/src/lib.rs | 7 + crates/testkit/tests/fonts.rs | 558 ++++++++++++++++++++++++++++++++++ 4 files changed, 1082 insertions(+) create mode 100644 crates/testkit/src/fonts.rs create mode 100644 crates/testkit/tests/fonts.rs diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..1e1a254e9f 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -78,11 +78,27 @@ fn no_std_instant_in_code_the_web_build_runs() { } ``` +## Test fonts + +The `fonts` module makes test fonts from font bytes the caller supplies. It reads no file and no environment variable, prints nothing, and builds for `wasm32-unknown-unknown`. + +- **`fonts::rename_family(bytes, from, to)`** returns a copy of one standalone face with the family name `from` replaced by `to`, which must have the same length in UTF-16 code units. It changes the family name records (name IDs 1, 16 and 21) whose value is `from`, and full names (ID 4) that are `from` or start with `from` and a space. At least one family record must hold `from`. It reads UTF-16BE and Macintosh Roman records, writes only ASCII names into Macintosh Roman records, leaves the PostScript name (ID 6), other names and other tables as they are, and writes the `name` table checksum and the `head` table's `checkSumAdjustment`. +- **`fonts::collection(faces)`** returns a TrueType collection (TTC 1.0) holding standalone faces. Each face gets its own copy of every table, tables start on four-byte boundaries, offsets count from the start of the collection, `checkSumAdjustment` is zero, and every table checksum matches the bytes in the collection. + +Both return a `fonts::FontError` instead of panicking: names of different lengths, a name that no family record holds, a face shorter than its table directory, a table or name string out of range, a collection given as a face, or output past the 4 GiB a collection's offsets reach. The layouts come from the OpenType font file and `name` table chapters: and . + +The tests that call the copies in VectorCraft, DesignCraft and WordCraft need each app's font database and its bundled fonts, so they stay in the apps. `tests/fonts.rs` tests the module on faces it assembles from bytes. + ## Origin | Module | Source | Path | Commit | |---|---|---|---| | `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | +| `fonts` | storytold/vectorcraft, `rename` and `collection` | `crates/text/src/tests/sysfonts.rs` | `bada8e1710` | +| `fonts` | storytold/vectorcraft, `renamed` | `crates/testkit/src/fonts.rs` | `bada8e1710` | +| `fonts` | storytold/designcraft, the family renaming and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `8b169f8ee7` | +| `fonts` | storytold/wordcraft, `renamed_to` and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `f8c66d0692` | +| `fonts` | storytold/wordcraft, `renamed` | `crates/fonts/src/fontdb/user/tests.rs` | `f8c66d0692` | ## Migration @@ -90,3 +106,6 @@ fn no_std_instant_in_code_the_web_build_runs() { |---|---|---|---| | PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | | FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | +| VectorCraft | `fonts::rename_family`, `fonts::collection` | `crates/text/src/tests/sysfonts.rs` and `crates/testkit/src/fonts.rs` helpers | Not started | +| DesignCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` helpers | Not started | +| WordCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` and `crates/fonts/src/fontdb/user/tests.rs` helpers | Not started | diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs new file mode 100644 index 0000000000..7231980c7a --- /dev/null +++ b/crates/testkit/src/fonts.rs @@ -0,0 +1,498 @@ +//! Test fonts made from font bytes the caller supplies. +//! +//! [`rename_family`] gives one standalone face a family name of the same length, and [`collection`] +//! builds a TrueType collection (TTC) from standalone faces. Both read the structures they change as +//! the OpenType specification lays them out +//! ( and +//! ), and return a [`FontError`] +//! for input that does not fit them. Other tables are copied as they are and are not checked. +//! +//! The module reads no file and no environment variable, prints nothing, and builds for +//! `wasm32-unknown-unknown`. + +use std::fmt; +use std::ops::Range; + +/// Length of the sfnt header: version, `numTables`, `searchRange`, `entrySelector`, `rangeShift`. +const SFNT_HEADER: usize = 12; +/// Length of one table record: tag, checksum, offset, length. +const TABLE_RECORD: usize = 16; +/// Length of the `name` table header: version, count, `storageOffset`. +const NAME_HEADER: usize = 6; +/// Length of one name record. +const NAME_RECORD: usize = 12; +/// Length of one language-tag record of a version 1 `name` table. +const LANG_TAG_RECORD: usize = 4; +/// Offset of `checkSumAdjustment` in the `head` table. +const HEAD_ADJUSTMENT: usize = 8; +/// The value a standalone font's checksum and its `checkSumAdjustment` add up to. +const CHECKSUM_TARGET: u32 = 0xB1B0_AFBA; +/// Name IDs that hold a family name: legacy (1), typographic (16) and WWS (21). +const FAMILY_IDS: [u16; 3] = [1, 16, 21]; +/// Name ID of the full font name, which starts with the family name. +const FULL_NAME_ID: u16 = 4; + +/// Why a face could not be renamed or collected. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FontError { + /// `from` and `to` have different lengths in UTF-16 code units. + UnequalLength, + /// `from` or `to` is empty. + InvalidName, + /// No family record of the face holds `from`. + NameNotFound, + /// The face has no `name` table. + MissingNameTable, + /// A structure the function reads is truncated, out of range or of an unknown version. + MalformedFont, + /// A matching Macintosh Roman record would need a name that is not ASCII. + UnsupportedEncoding, + /// A string the rename changes shares bytes with a string it keeps, or with a different replacement. + ConflictingNameStorage, + /// [`collection`] was given no faces. + EmptyCollection, + /// The input is a collection, or an sfnt version other than TrueType or CFF outlines. + UnsupportedFace, + /// The output would not fit in memory or in the 32-bit offsets of a collection. + OutputTooLarge, +} + +impl fmt::Display for FontError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::UnequalLength => "the old and new family names have different lengths", + Self::InvalidName => "a family name is empty", + Self::NameNotFound => "no family name record holds the old name", + Self::MissingNameTable => "the font has no name table", + Self::MalformedFont => "the font's table directory or name table is truncated or out of range", + Self::UnsupportedEncoding => "a Macintosh Roman name record can only take an ASCII name", + Self::ConflictingNameStorage => "a renamed string shares its bytes with a string that must not change", + Self::EmptyCollection => "a collection needs at least one face", + Self::UnsupportedFace => "the input is not a standalone TrueType or CFF face", + Self::OutputTooLarge => "the output is too large", + }) + } +} + +impl std::error::Error for FontError {} + +/// Returns a copy of `bytes`, one standalone face, with the family name `from` replaced by `to`. +/// +/// The records changed are the legacy, typographic and WWS family names (name IDs 1, 16 and 21) +/// whose whole value is `from`, and full names (name ID 4) that are `from` or start with `from` and a +/// space; at least one family record must hold `from`. Copyright, style, PostScript (ID 6) and every +/// other name keep their bytes. Records in UTF-16BE (platform 0, and platform 3 encodings 0, 1 and +/// 10) and Macintosh Roman (platform 1 encoding 0) are read, and only ASCII names are written into +/// Macintosh Roman records; records in other encodings are left as they are. The function then writes the +/// `name` table's checksum and the `head` table's `checkSumAdjustment`. +/// +/// # Errors +/// +/// [`FontError::InvalidName`] when a name is empty, [`FontError::UnequalLength`] when the names have +/// different UTF-16 lengths, [`FontError::NameNotFound`] when no family record holds `from`, +/// [`FontError::UnsupportedEncoding`] when a matching Macintosh Roman record would need non-ASCII +/// bytes, [`FontError::ConflictingNameStorage`] when a changed string shares bytes with a kept one, +/// [`FontError::MissingNameTable`], [`FontError::UnsupportedFace`] for a collection, and +/// [`FontError::MalformedFont`] when the directory, the `name` table or the `head` table is out of +/// range or of an unknown version, or when the `name` or `head` table shares bytes with the directory +/// or another table. +pub fn rename_family(bytes: &[u8], from: &str, to: &str) -> Result, FontError> { + if from.is_empty() || to.is_empty() { + return Err(FontError::InvalidName); + } + if from.encode_utf16().count() != to.encode_utf16().count() { + return Err(FontError::UnequalLength); + } + let tables = directory(bytes)?; + let name = tables.iter().find(|t| &t.tag == b"name").ok_or(FontError::MissingNameTable)?; + let head = tables.iter().find(|t| &t.tag == b"head"); + if shares_bytes(&tables, name) || head.is_some_and(|head| shares_bytes(&tables, head)) { + return Err(FontError::MalformedFont); + } + if head.is_some_and(|head| head.length < HEAD_ADJUSTMENT + 4) { + return Err(FontError::MalformedFont); + } + let strings = name_strings(bytes, name)?; + let (edits, kept) = plan_edits(bytes, &strings, from, to)?; + check_kept(&edits, kept)?; + + let mut out = copy_of(bytes)?; + apply_edits(&mut out, name, &edits)?; + let name_sum = checksum(bytes_at(&out, name.offset, name.length)?); + put_u32(&mut out, name.record + 4, name_sum)?; + if let Some(head) = head { + let at = head.offset + HEAD_ADJUSTMENT; + put_u32(&mut out, at, 0)?; + let sum = checksum(&out); + put_u32(&mut out, at, CHECKSUM_TARGET.wrapping_sub(sum))?; + } + Ok(out) +} + +/// Returns a TrueType collection (TTC version 1.0) holding `faces`, each a standalone face, in order. +/// +/// Every face keeps its sfnt header and table order and gets its own copy of each table. Tables +/// start on four-byte boundaries with zero padding between them, offsets count from the start of the +/// collection, and each record keeps the table's unpadded length. Each `head` table's +/// `checkSumAdjustment` is set to zero, as a collection does not use it, and every table checksum is +/// computed from the bytes in the collection. +/// +/// # Errors +/// +/// [`FontError::EmptyCollection`] for no faces, [`FontError::UnsupportedFace`] for a face that is +/// itself a collection, [`FontError::MalformedFont`] for a face shorter than its table directory or +/// with a table out of range, and [`FontError::OutputTooLarge`] when the collection would pass the +/// 4 GiB that its 32-bit offsets reach or cannot be allocated. +pub fn collection(faces: &[&[u8]]) -> Result, FontError> { + if faces.is_empty() { + return Err(FontError::EmptyCollection); + } + let directories = faces.iter().map(|face| directory(face)).collect::, _>>()?; + let count = u32::try_from(faces.len()).map_err(|_| FontError::OutputTooLarge)?; + let size = collection_size(&directories)?; + let mut out = Vec::new(); + out.try_reserve_exact(size).map_err(|_| FontError::OutputTooLarge)?; + out.extend_from_slice(b"ttcf"); + out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + out.extend_from_slice(&count.to_be_bytes()); + out.resize(SFNT_HEADER + faces.len() * 4, 0); + for (index, (face, tables)) in faces.iter().zip(&directories).enumerate() { + let directory = offset32(out.len())?; + put_u32(&mut out, SFNT_HEADER + index * 4, directory)?; + write_face(&mut out, face, tables)?; + } + Ok(out) +} + +/// One table record of a face: where the record is and where its table is. +struct Table { + tag: [u8; 4], + /// Offset of the table record in the face. + record: usize, + offset: usize, + length: usize, +} + +/// Reads a standalone face's table directory, checking that every record and table lies in `face`. +fn directory(face: &[u8]) -> Result, FontError> { + let version = bytes_at(face, 0, 4)?; + if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) { + return Err(FontError::UnsupportedFace); + } + let count = usize::from(u16_at(face, 4)?); + bytes_at(face, 0, SFNT_HEADER + count * TABLE_RECORD)?; + let mut tables = Vec::with_capacity(count); + for index in 0..count { + let record = SFNT_HEADER + index * TABLE_RECORD; + let tag = <[u8; 4]>::try_from(bytes_at(face, record, 4)?).map_err(|_| FontError::MalformedFont)?; + let offset = usize_from(u32_at(face, record + 8)?)?; + let length = usize_from(u32_at(face, record + 12)?)?; + bytes_at(face, offset, length)?; + tables.push(Table { tag, record, offset, length }); + } + Ok(tables) +} + +/// Whether `table` shares bytes with the table directory or with another table of the face. +fn shares_bytes(tables: &[Table], table: &Table) -> bool { + let end = table.offset + table.length; + let overlaps = |start: usize, other_end: usize| start < end && table.offset < other_end; + overlaps(0, SFNT_HEADER + tables.len() * TABLE_RECORD) + || tables.iter().any(|other| other.record != table.record && overlaps(other.offset, other.offset + other.length)) +} + +/// Bytes a collection of these faces takes, refused past what a 32-bit offset reaches. +fn collection_size(directories: &[Vec]) -> Result { + let mut size = u64::try_from(SFNT_HEADER + directories.len() * 4).map_err(|_| FontError::OutputTooLarge)?; + for tables in directories { + let directory = SFNT_HEADER + tables.len() * TABLE_RECORD; + size = size.checked_add(u64::try_from(directory).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?; + for table in tables { + let padded = u64::try_from(table.length).map_err(|_| FontError::OutputTooLarge)?.div_ceil(4) * 4; + size = size.checked_add(padded).ok_or(FontError::OutputTooLarge)?; + } + } + if size > u64::from(u32::MAX) { + return Err(FontError::OutputTooLarge); + } + usize::try_from(size).map_err(|_| FontError::OutputTooLarge) +} + +/// Appends one face's directory and tables to a collection being built. +fn write_face(out: &mut Vec, face: &[u8], tables: &[Table]) -> Result<(), FontError> { + let directory = out.len(); + out.extend_from_slice(bytes_at(face, 0, SFNT_HEADER)?); + out.resize(directory + SFNT_HEADER + tables.len() * TABLE_RECORD, 0); + for (index, table) in tables.iter().enumerate() { + let start = out.len(); + out.extend_from_slice(bytes_at(face, table.offset, table.length)?); + if &table.tag == b"head" { + if table.length < HEAD_ADJUSTMENT + 4 { + return Err(FontError::MalformedFont); + } + put_u32(out, start + HEAD_ADJUSTMENT, 0)?; + } + let sum = checksum(bytes_at(out, start, table.length)?); + out.resize(out.len().div_ceil(4) * 4, 0); + let record = directory + SFNT_HEADER + index * TABLE_RECORD; + put_bytes(out, record, &table.tag)?; + put_u32(out, record + 4, sum)?; + put_u32(out, record + 8, offset32(start)?)?; + put_u32(out, record + 12, offset32(table.length)?)?; + } + Ok(()) +} + +/// How the bytes of a name record are encoded, as far as renaming reads them. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Encoding { + Utf16, + MacRoman, + Other, +} + +impl Encoding { + fn of(platform: u16, encoding: u16) -> Self { + match (platform, encoding) { + (0, _) | (3, 0 | 1 | 10) => Self::Utf16, + (1, 0) => Self::MacRoman, + _ => Self::Other, + } + } +} + +/// One string of the `name` table, with its range in the face. +struct NameString { + encoding: Encoding, + name_id: u16, + range: Range, +} + +/// The strings of a face's `name` table: the name records, then the language tags of version 1. +struct NameStrings { + names: Vec, + lang_tags: Vec>, +} + +/// Reads the name and language-tag records of `table`, checking every string lies in the table. +fn name_strings(face: &[u8], table: &Table) -> Result { + let data = bytes_at(face, table.offset, table.length)?; + let version = u16_at(data, 0)?; + if version > 1 { + return Err(FontError::MalformedFont); + } + let count = usize::from(u16_at(data, 2)?); + let storage = usize::from(u16_at(data, 4)?); + let records_end = NAME_HEADER + count * NAME_RECORD; + bytes_at(data, 0, records_end)?; + let mut header_end = records_end; + let mut lang_tag_records = 0; + if version == 1 { + lang_tag_records = usize::from(u16_at(data, records_end)?); + header_end = records_end + 2 + lang_tag_records * LANG_TAG_RECORD; + } + if storage < header_end || storage > data.len() { + return Err(FontError::MalformedFont); + } + let string = |at: usize| -> Result, FontError> { + let length = usize::from(u16_at(data, at)?); + let start = storage + usize::from(u16_at(data, at + 2)?); + bytes_at(data, start, length)?; + Ok(table.offset + start..table.offset + start + length) + }; + let mut names = Vec::with_capacity(count); + for index in 0..count { + let record = NAME_HEADER + index * NAME_RECORD; + let encoding = Encoding::of(u16_at(data, record)?, u16_at(data, record + 2)?); + let name_id = u16_at(data, record + 6)?; + names.push(NameString { encoding, name_id, range: string(record + 8)? }); + } + let mut lang_tags = Vec::with_capacity(lang_tag_records); + for index in 0..lang_tag_records { + lang_tags.push(string(records_end + 2 + index * LANG_TAG_RECORD)?); + } + Ok(NameStrings { names, lang_tags }) +} + +/// A string the rename writes: its range in the face and its new bytes. +struct Edit { + range: Range, + bytes: Vec, +} + +/// Works out the strings to rewrite and the ranges of the strings that must keep their bytes. +/// Refuses with [`FontError::NameNotFound`] when no family record (IDs 1, 16 and 21) holds `from`. +fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Result<(Vec, Vec>), FontError> { + let mut edits = Vec::new(); + let mut kept = strings.lang_tags.clone(); + let mut family_found = false; + for string in &strings.names { + let family = FAMILY_IDS.contains(&string.name_id); + let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?; + let new = if family || string.name_id == FULL_NAME_ID { renamed(string, bytes, from, to)? } else { None }; + match new { + Some(new) => { + family_found |= family; + edits.push(Edit { range: string.range.clone(), bytes: new }); + } + None => kept.push(string.range.clone()), + } + } + if !family_found { + return Err(FontError::NameNotFound); + } + Ok((edits, kept)) +} + +/// The new bytes of a family or full-name string, or `None` when it does not hold `from`. +fn renamed(string: &NameString, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { + let family = FAMILY_IDS.contains(&string.name_id); + let encoded = match string.encoding { + Encoding::Utf16 => renamed_utf16(family, bytes, from, to)?, + Encoding::MacRoman => renamed_mac_roman(family, bytes, from, to)?, + Encoding::Other => None, + }; + if encoded.as_ref().is_some_and(|encoded| encoded.len() != bytes.len()) { + return Err(FontError::UnequalLength); + } + Ok(encoded) +} + +/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and a space. +fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { + let value = utf16_value(bytes)?; + let new = if family { + (value == from).then(|| to.to_owned()) + } else { + value.strip_prefix(from).filter(|rest| rest.is_empty() || rest.starts_with(' ')).map(|rest| format!("{to}{rest}")) + }; + Ok(new.map(|new| new.encode_utf16().flat_map(u16::to_be_bytes).collect())) +} + +/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, byte by byte; only ASCII names are written. +fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { + if !from.is_ascii() { + return if mac_roman_may_hold(family, bytes, from) { Err(FontError::UnsupportedEncoding) } else { Ok(None) }; + } + let Some(rest) = bytes.strip_prefix(from.as_bytes()) else { + return Ok(None); + }; + if !(rest.is_empty() || (!family && rest.first() == Some(&b' '))) { + return Ok(None); + } + if !to.is_ascii() { + return Err(FontError::UnsupportedEncoding); + } + Ok(Some([to.as_bytes(), rest].concat())) +} + +/// Whether a Macintosh Roman string could hold a non-ASCII `from`. The encoding has one byte per +/// character and shares its ASCII range with Unicode, so a string that differs from `from` in length +/// or in an ASCII position cannot hold it. +fn mac_roman_may_hold(family: bool, bytes: &[u8], from: &str) -> bool { + let count = from.chars().count(); + let fits = bytes.len() == count || (!family && bytes.get(count) == Some(&b' ')); + fits && bytes.iter().zip(from.chars()).all(|(&byte, c)| !(byte.is_ascii() || c.is_ascii()) || char::from(byte) == c) +} + +/// Decodes a UTF-16BE string, refusing an odd length or an unpaired surrogate. +fn utf16_value(bytes: &[u8]) -> Result { + let (pairs, rest) = bytes.as_chunks::<2>(); + if !rest.is_empty() { + return Err(FontError::MalformedFont); + } + let units = pairs.iter().map(|&pair| u16::from_be_bytes(pair)); + char::decode_utf16(units).collect::>().map_err(|_| FontError::MalformedFont) +} + +/// Refuses a rename whose strings overlap a string that keeps its bytes. +fn check_kept(edits: &[Edit], mut kept: Vec>) -> Result<(), FontError> { + kept.retain(|range| !range.is_empty()); + kept.sort_by_key(|range| range.start); + let mut merged: Vec> = Vec::with_capacity(kept.len()); + for range in kept { + match merged.last_mut() { + Some(last) if range.start <= last.end => last.end = last.end.max(range.end), + _ => merged.push(range), + } + } + for edit in edits { + let next = merged.partition_point(|range| range.end <= edit.range.start); + if merged.get(next).is_some_and(|range| range.start < edit.range.end) { + return Err(FontError::ConflictingNameStorage); + } + } + Ok(()) +} + +/// Writes the edits into `out`, refusing two edits that write different bytes to the same place. +fn apply_edits(out: &mut [u8], name: &Table, edits: &[Edit]) -> Result<(), FontError> { + let mut ranges: Vec<&Edit> = edits.iter().collect(); + ranges.sort_by_key(|edit| (edit.range.start, edit.range.end)); + ranges.dedup_by(|a, b| a.range == b.range && a.bytes == b.bytes); + let mut written = vec![false; name.length]; + for edit in ranges { + let target = out.get_mut(edit.range.clone()).ok_or(FontError::MalformedFont)?; + let start = edit.range.start.checked_sub(name.offset).ok_or(FontError::MalformedFont)?; + let marks = written.get_mut(start..start + edit.bytes.len()).ok_or(FontError::MalformedFont)?; + for ((byte, mark), &new) in target.iter_mut().zip(marks.iter_mut()).zip(&edit.bytes) { + if *mark && *byte != new { + return Err(FontError::ConflictingNameStorage); + } + *byte = new; + *mark = true; + } + } + Ok(()) +} + +/// The OpenType table checksum: the sum of big-endian 32-bit words, the last one padded with zeros. +fn checksum(data: &[u8]) -> u32 { + data.chunks(4).fold(0u32, |sum, chunk| { + let mut word = [0u8; 4]; + for (to, &from) in word.iter_mut().zip(chunk) { + *to = from; + } + sum.wrapping_add(u32::from_be_bytes(word)) + }) +} + +fn copy_of(bytes: &[u8]) -> Result, FontError> { + let mut out = Vec::new(); + out.try_reserve_exact(bytes.len()).map_err(|_| FontError::OutputTooLarge)?; + out.extend_from_slice(bytes); + Ok(out) +} + +fn bytes_at(data: &[u8], at: usize, length: usize) -> Result<&[u8], FontError> { + let end = at.checked_add(length).ok_or(FontError::MalformedFont)?; + data.get(at..end).ok_or(FontError::MalformedFont) +} + +fn u16_at(data: &[u8], at: usize) -> Result { + let bytes = <[u8; 2]>::try_from(bytes_at(data, at, 2)?).map_err(|_| FontError::MalformedFont)?; + Ok(u16::from_be_bytes(bytes)) +} + +fn u32_at(data: &[u8], at: usize) -> Result { + let bytes = <[u8; 4]>::try_from(bytes_at(data, at, 4)?).map_err(|_| FontError::MalformedFont)?; + Ok(u32::from_be_bytes(bytes)) +} + +fn put_bytes(data: &mut [u8], at: usize, bytes: &[u8]) -> Result<(), FontError> { + let end = at.checked_add(bytes.len()).ok_or(FontError::MalformedFont)?; + data.get_mut(at..end).ok_or(FontError::MalformedFont)?.copy_from_slice(bytes); + Ok(()) +} + +fn put_u32(data: &mut [u8], at: usize, value: u32) -> Result<(), FontError> { + put_bytes(data, at, &value.to_be_bytes()) +} + +fn usize_from(value: u32) -> Result { + usize::try_from(value).map_err(|_| FontError::MalformedFont) +} + +fn offset32(value: usize) -> Result { + u32::try_from(value).map_err(|_| FontError::OutputTooLarge) +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..fbf29767ce 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -24,7 +24,14 @@ //! They do **not** establish runtime correctness, protocol concurrency safety, or platform behavior //! under foreign host environments. They are lightweight syntactic regression gates designed to complement, //! rather than replace, platform integration tests and CI execution. +//! +//! ### Test fonts +//! +//! The [`fonts`] module makes test fonts from font bytes the caller supplies: +//! [`fonts::rename_family`] gives a face a family name of the same length, and +//! [`fonts::collection`] builds a TrueType collection from standalone faces. +pub mod fonts; pub mod guards; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/fonts.rs new file mode 100644 index 0000000000..f2722f11d3 --- /dev/null +++ b/crates/testkit/tests/fonts.rs @@ -0,0 +1,558 @@ +//! Tests of `craft_testkit::fonts` on faces assembled here from bytes. +//! +//! The helpers below read the output by the offsets the OpenType specification gives, without the +//! crate's own parser, so a test fails when a field is wrong even if the crate could read it back. + +use craft_testkit::fonts::{FontError, collection, rename_family}; + +const FROM: &str = "Source Sans 3"; +const TO: &str = "Sysfont Sans3"; +const CHECKSUM_TARGET: u32 = 0xB1B0_AFBA; + +fn be16(data: &[u8], at: usize) -> u16 { + u16::from_be_bytes([data[at], data[at + 1]]) +} + +fn be32(data: &[u8], at: usize) -> u32 { + u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) +} + +fn set16(data: &mut [u8], at: usize, value: u16) { + data[at..at + 2].copy_from_slice(&value.to_be_bytes()); +} + +fn set32(data: &mut [u8], at: usize, value: u32) { + data[at..at + 4].copy_from_slice(&value.to_be_bytes()); +} + +/// The table checksum: big-endian 32-bit words added with wrapping, the last padded with zeros. +fn sum(data: &[u8]) -> u32 { + let mut total = 0u32; + let mut at = 0; + while at < data.len() { + let mut word = [0u8; 4]; + for (k, byte) in word.iter_mut().enumerate() { + if let Some(&b) = data.get(at + k) { + *byte = b; + } + } + total = total.wrapping_add(u32::from_be_bytes(word)); + at += 4; + } + total +} + +fn utf16(text: &str) -> Vec { + text.encode_utf16().flat_map(u16::to_be_bytes).collect() +} + +/// A name record: platform, encoding, name ID, and where its string is in storage. +struct Rec { + platform: u16, + encoding: u16, + name_id: u16, + offset: u16, + length: u16, +} + +/// A `name` table of `version` with the records as given, language tags as (length, offset), then storage. +fn name_table(version: u16, records: &[Rec], lang_tags: &[(u16, u16)], storage: &[u8]) -> Vec { + let mut header = 6 + 12 * records.len(); + if version == 1 { + header += 2 + 4 * lang_tags.len(); + } + let mut table = Vec::new(); + table.extend_from_slice(&version.to_be_bytes()); + table.extend_from_slice(&(records.len() as u16).to_be_bytes()); + table.extend_from_slice(&(header as u16).to_be_bytes()); + for rec in records { + for value in [rec.platform, rec.encoding, 0, rec.name_id, rec.length, rec.offset] { + table.extend_from_slice(&value.to_be_bytes()); + } + } + if version == 1 { + table.extend_from_slice(&(lang_tags.len() as u16).to_be_bytes()); + for &(length, offset) in lang_tags { + table.extend_from_slice(&length.to_be_bytes()); + table.extend_from_slice(&offset.to_be_bytes()); + } + } + table.extend_from_slice(storage); + table +} + +/// Name records with their strings stored one after another: (platform, encoding, name ID, bytes). +fn names(list: &[(u16, u16, u16, Vec)]) -> Vec { + let mut storage = Vec::new(); + let mut records = Vec::new(); + for (platform, encoding, name_id, bytes) in list { + records.push(Rec { platform: *platform, encoding: *encoding, name_id: *name_id, offset: storage.len() as u16, length: bytes.len() as u16 }); + storage.extend_from_slice(bytes); + } + name_table(0, &records, &[], &storage) +} + +/// A 54-byte `head` table whose `checkSumAdjustment` holds a stale value. +fn head() -> Vec { + let mut table = vec![0u8; 54]; + set32(&mut table, 0, 0x0001_0000); + set32(&mut table, 8, 0x1234_5678); + set32(&mut table, 12, 0x5F0F_3CF5); + set16(&mut table, 18, 1000); + table +} + +/// A standalone TrueType face holding `tables` in the order given, each on a four-byte boundary. +fn face(tables: &[(&[u8; 4], Vec)]) -> Vec { + let mut font = Vec::new(); + font.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + font.extend_from_slice(&(tables.len() as u16).to_be_bytes()); + font.extend_from_slice(&[0; 6]); + font.resize(12 + 16 * tables.len(), 0); + for (index, (tag, data)) in tables.iter().enumerate() { + let offset = font.len(); + font.extend_from_slice(data); + font.resize(font.len().div_ceil(4) * 4, 0); + let record = 12 + 16 * index; + font[record..record + 4].copy_from_slice(&tag[..]); + set32(&mut font, record + 4, sum(data)); + set32(&mut font, record + 8, offset as u32); + set32(&mut font, record + 12, data.len() as u32); + } + font +} + +fn family_face(list: &[(u16, u16, u16, Vec)]) -> Vec { + face(&[(b"head", head()), (b"name", names(list))]) +} + +/// A table of the face whose directory starts at `directory`: (record offset, table offset, length). +fn table_at(font: &[u8], directory: usize, tag: &[u8; 4]) -> (usize, usize, usize) { + let count = usize::from(be16(font, directory + 4)); + (0..count) + .map(|i| directory + 12 + 16 * i) + .find(|&record| &font[record..record + 4] == tag) + .map(|record| (record, be32(font, record + 8) as usize, be32(font, record + 12) as usize)) + .unwrap_or_else(|| panic!("no {} table", String::from_utf8_lossy(tag))) +} + +fn table(font: &[u8], tag: &[u8; 4]) -> (usize, usize, usize) { + table_at(font, 0, tag) +} + +/// Every name record of a standalone face: (platform, encoding, name ID, bytes). +fn strings(font: &[u8]) -> Vec<(u16, u16, u16, Vec)> { + let (_, at, _) = table(font, b"name"); + let count = usize::from(be16(font, at + 2)); + let storage = at + usize::from(be16(font, at + 4)); + (0..count) + .map(|i| { + let rec = at + 6 + 12 * i; + let start = storage + usize::from(be16(font, rec + 10)); + let end = start + usize::from(be16(font, rec + 8)); + (be16(font, rec), be16(font, rec + 2), be16(font, rec + 6), font[start..end].to_vec()) + }) + .collect() +} + +fn win(name_id: u16, text: &str) -> (u16, u16, u16, Vec) { + (3, 1, name_id, utf16(text)) +} + +fn mac(name_id: u16, bytes: &[u8]) -> (u16, u16, u16, Vec) { + (1, 0, name_id, bytes.to_vec()) +} + +#[test] +fn rename_handles_utf16_and_ascii() { + let font = family_face(&[win(1, FROM), (0, 3, 1, utf16(FROM)), mac(1, FROM.as_bytes()), win(16, FROM), win(21, FROM)]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(out.len(), font.len()); + assert_eq!(strings(&out), vec![win(1, TO), (0, 3, 1, utf16(TO)), mac(1, TO.as_bytes()), win(16, TO), win(21, TO)]); +} + +#[test] +fn rename_only_family_records() { + let list = [ + win(0, "Copyright 2026 the Source Sans 3 authors"), + win(1, FROM), + win(2, "Regular"), + win(6, "SourceSans3-Regular"), + win(13, "Source Sans 3 is licensed under the OFL"), + win(16, "Source Sans 3 Extra"), + ]; + let other = utf16(FROM); + let font = face(&[(b"head", head()), (b"name", names(&list)), (b"zzzz", other.clone())]); + let out = rename_family(&font, FROM, TO).unwrap(); + let mut want = list.to_vec(); + want[1] = win(1, TO); + assert_eq!(strings(&out), want); + let (_, at, length) = table(&out, b"zzzz"); + assert_eq!(&out[at..at + length], &other[..], "a table other than name keeps its bytes"); +} + +#[test] +fn rename_full_name_prefix_only() { + let list = + [win(1, FROM), win(4, "Source Sans 3 Bold"), (0, 3, 4, utf16("Source Sans 3Bold")), mac(4, b"My Source Sans 3"), mac(4, FROM.as_bytes())]; + let out = rename_family(&family_face(&list), FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), win(4, "Sysfont Sans3 Bold"), list[2].clone(), list[3].clone(), mac(4, TO.as_bytes())]); +} + +#[test] +fn rename_rejects_non_ascii_mac_roman() { + let font = family_face(&[win(1, FROM), mac(1, FROM.as_bytes())]); + assert_eq!(rename_family(&font, FROM, "Sourcé Sans 3"), Err(FontError::UnsupportedEncoding)); + // "Café Sans 3" in Mac Roman, where é is 0x8E. + let font = family_face(&[win(1, "Café Sans 3"), mac(1, b"Caf\x8E Sans 3")]); + assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding)); +} + +#[test] +fn rename_keeps_unrelated_mac_roman_names() { + // Mac Roman 0x8E is "é". Neither Mac record can hold "Café Sans 3": one is shorter, and the other + // differs from it in an ASCII position. + let list = [win(1, "Café Sans 3"), mac(4, b"Autre \x8E"), mac(16, b"Caf\x8E Sans 4")]; + let out = rename_family(&family_face(&list), "Café Sans 3", "Cafe Sans 3").unwrap(); + assert_eq!(strings(&out), vec![win(1, "Cafe Sans 3"), list[1].clone(), list[2].clone()]); +} + +#[test] +fn rename_keeps_mac_roman_full_name_suffix() { + let list = [win(1, FROM), mac(4, b"Source Sans 3 Cr\x8Ame")]; + let out = rename_family(&family_face(&list), FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), mac(4, b"Sysfont Sans3 Cr\x8Ame")]); +} + +#[test] +fn rename_requires_a_family_record() { + let font = family_face(&[win(1, "Other Family"), win(4, "Source Sans 3 Bold")]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::NameNotFound)); +} + +#[test] +fn rename_preserves_other_encodings() { + let list = [win(1, FROM), (3, 3, 1, utf16(FROM)), (1, 1, 1, FROM.as_bytes().to_vec()), (2, 1, 1, utf16(FROM))]; + let out = rename_family(&family_face(&list), FROM, TO).unwrap(); + let mut want = list.to_vec(); + want[0] = win(1, TO); + assert_eq!(strings(&out), want); +} + +#[test] +fn rename_rejects_odd_utf16() { + let mut odd = utf16(FROM); + odd.push(0); + let font = family_face(&[(3, 1, 1, odd)]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_bad_surrogate() { + let font = family_face(&[(3, 1, 1, vec![0xD8, 0x00, 0x00, b'A']), win(16, FROM)]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_handles_shared_family_storage() { + let storage = utf16("Source Sans 3 Bold"); + let records = [ + Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, + Rec { platform: 3, encoding: 1, name_id: 16, offset: 0, length: 26 }, + Rec { platform: 3, encoding: 1, name_id: 4, offset: 0, length: 36 }, + ]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &storage))]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), win(16, TO), win(4, "Sysfont Sans3 Bold")]); +} + +#[test] +fn rename_rejects_shared_nonfamily_storage() { + let records = + [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, Rec { platform: 3, encoding: 1, name_id: 6, offset: 2, length: 10 }]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &utf16(FROM)))]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage)); +} + +#[test] +fn rename_updates_name_checksum() { + let font = family_face(&[win(1, FROM), win(2, "Regular")]); + let out = rename_family(&font, FROM, TO).unwrap(); + let (record, at, length) = table(&out, b"name"); + assert_eq!(be32(&out, record + 4), sum(&out[at..at + length])); + assert_ne!(be32(&out, record + 4), be32(&font, record + 4), "the renamed table has a new checksum"); +} + +#[test] +fn rename_updates_head_adjustment() { + let font = family_face(&[win(1, FROM)]); + let out = rename_family(&font, FROM, TO).unwrap(); + let (_, at, _) = table(&out, b"head"); + let mut zeroed = out.clone(); + set32(&mut zeroed, at + 8, 0); + assert_eq!(be32(&out, at + 8), CHECKSUM_TARGET.wrapping_sub(sum(&zeroed))); + assert_eq!(sum(&out), CHECKSUM_TARGET); +} + +#[test] +fn rename_format_one_preserves_language_tags() { + let mut storage = utf16(FROM); + storage.extend(utf16("en-US")); + let records = [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }]; + let font = face(&[(b"head", head()), (b"name", name_table(1, &records, &[(10, 26)], &storage))]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO)]); + let (_, at, length) = table(&out, b"name"); + assert_eq!(&out[at + length - 10..at + length], &utf16("en-US")[..]); + assert_eq!(be16(&out, at + 18), 1, "the language-tag count stays"); +} + +#[test] +fn rename_keeps_language_tag_storage() { + let records = [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }]; + let font = face(&[(b"head", head()), (b"name", name_table(1, &records, &[(26, 0)], &utf16(FROM)))]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage)); +} + +#[test] +fn rename_rejects_short_sfnt() { + assert_eq!(rename_family(&[], FROM, TO), Err(FontError::MalformedFont)); + assert_eq!(rename_family(&[0, 1, 0, 0, 0], FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_truncated_directory() { + let font = family_face(&[win(1, FROM)]); + assert_eq!(rename_family(&font[..12 + 16 + 8], FROM, TO), Err(FontError::MalformedFont)); + let mut many = font.clone(); + set16(&mut many, 4, 4000); + assert_eq!(rename_family(&many, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_collection() { + let font = family_face(&[win(1, FROM)]); + let ttc = collection(&[&font]).unwrap(); + assert_eq!(rename_family(&ttc, FROM, TO), Err(FontError::UnsupportedFace)); +} + +#[test] +fn rename_rejects_missing_name_table() { + let font = face(&[(b"head", head())]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MissingNameTable)); +} + +#[test] +fn rename_rejects_short_head() { + let font = face(&[(b"head", head()[..8].to_vec()), (b"name", names(&[win(1, FROM)]))]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_bad_name_storage() { + let font = family_face(&[win(1, FROM)]); + let (_, at, length) = table(&font, b"name"); + let mut beyond = font.clone(); + set16(&mut beyond, at + 4, length as u16 + 1); + assert_eq!(rename_family(&beyond, FROM, TO), Err(FontError::MalformedFont)); + let mut inside_header = font.clone(); + set16(&mut inside_header, at + 4, 6); + assert_eq!(rename_family(&inside_header, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_bad_name_record_range() { + let font = family_face(&[win(1, FROM)]); + let (_, at, _) = table(&font, b"name"); + let mut long = font.clone(); + set16(&mut long, at + 6 + 8, 28); + assert_eq!(rename_family(&long, FROM, TO), Err(FontError::MalformedFont)); + let mut late = font; + set16(&mut late, at + 6 + 10, 2); + assert_eq!(rename_family(&late, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_name_table_sharing_bytes() { + let font = face(&[(b"head", head()), (b"name", names(&[win(1, FROM)])), (b"zzzz", vec![7; 8])]); + let (_, at, _) = table(&font, b"name"); + let (record, _, _) = table(&font, b"zzzz"); + let mut shared = font.clone(); + set32(&mut shared, record + 8, (at + 18) as u32); + assert_eq!(rename_family(&shared, FROM, TO), Err(FontError::MalformedFont)); + let (_, head_at, _) = table(&font, b"head"); + let mut under_head = font; + set32(&mut under_head, record + 8, (head_at + 8) as u32); + assert_eq!(rename_family(&under_head, FROM, TO), Err(FontError::MalformedFont), "checkSumAdjustment would land in zzzz"); +} + +#[test] +fn rename_rejects_unknown_name_format() { + let font = family_face(&[win(1, FROM)]); + let (_, at, _) = table(&font, b"name"); + let mut two = font; + set16(&mut two, at, 2); + assert_eq!(rename_family(&two, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_unequal_lengths() { + let font = family_face(&[win(1, FROM)]); + assert_eq!(rename_family(&font, FROM, "Other"), Err(FontError::UnequalLength)); +} + +#[test] +fn rename_rejects_unequal_utf16_lengths() { + // Both names are four bytes of UTF-8, but "𝐀" is two UTF-16 code units and "abcd" is four. + let font = family_face(&[win(1, "𝐀")]); + assert_eq!(rename_family(&font, "𝐀", "abcd"), Err(FontError::UnequalLength)); +} + +#[test] +fn rename_rejects_missing_family() { + let font = family_face(&[win(1, FROM), win(2, "Regular")]); + assert_eq!(rename_family(&font, "Source Sans 4", TO), Err(FontError::NameNotFound)); +} + +#[test] +fn rename_rejects_empty_names() { + let font = family_face(&[win(1, FROM)]); + assert_eq!(rename_family(&font, "", ""), Err(FontError::InvalidName)); + assert_eq!(rename_family(&font, FROM, ""), Err(FontError::InvalidName)); +} + +/// Two faces that differ in every table, with table lengths that are not multiples of four. +fn two_faces() -> (Vec, Vec) { + let a = face(&[(b"head", head()), (b"name", names(&[mac(1, b"Alpha")])), (b"zzzz", vec![1, 2, 3, 4, 5])]); + let mut other_head = head(); + set32(&mut other_head, 4, 0x0002_0000); + let b = face(&[(b"head", other_head), (b"name", names(&[mac(1, b"Beta")])), (b"zzzz", vec![9; 7])]); + (a, b) +} + +/// Each face's directory offset, read from the TTC header. +fn ttc_faces(ttc: &[u8]) -> Vec { + assert_eq!(&ttc[..4], b"ttcf"); + assert_eq!(be32(ttc, 4), 0x0001_0000); + (0..be32(ttc, 8) as usize).map(|i| be32(ttc, 12 + 4 * i) as usize).collect() +} + +/// Every table of a face in a collection: (tag, checksum, offset, length). +fn ttc_tables(ttc: &[u8], directory: usize) -> Vec<([u8; 4], u32, usize, usize)> { + (0..usize::from(be16(ttc, directory + 4))) + .map(|i| { + let r = directory + 12 + 16 * i; + (ttc[r..r + 4].try_into().unwrap(), be32(ttc, r + 4), be32(ttc, r + 8) as usize, be32(ttc, r + 12) as usize) + }) + .collect() +} + +#[test] +fn collection_offsets_are_file_relative() { + let (a, b) = two_faces(); + let ttc = collection(&[&a, &b]).unwrap(); + let faces = ttc_faces(&ttc); + assert_eq!(faces.len(), 2); + for (directory, input) in faces.into_iter().zip([&a, &b]) { + assert_eq!(&ttc[directory..directory + 12], &input[..12], "the sfnt header is copied"); + for (tag, _, offset, length) in ttc_tables(&ttc, directory) { + let (_, from, from_length) = table(input, &tag); + assert_eq!(length, from_length); + let mut want = input[from..from + from_length].to_vec(); + if &tag == b"head" { + set32(&mut want, 8, 0); + } + assert_eq!(&ttc[offset..offset + length], &want[..], "{} sits at its file offset", String::from_utf8_lossy(&tag)); + } + } +} + +#[test] +fn collection_pads_odd_faces() { + let (a, b) = two_faces(); + let ttc = collection(&[&a, &b]).unwrap(); + assert_eq!(ttc.len() % 4, 0); + for directory in ttc_faces(&ttc) { + assert_eq!(directory % 4, 0); + for (_, _, offset, length) in ttc_tables(&ttc, directory) { + assert_eq!(offset % 4, 0, "tables start on four-byte boundaries"); + let padded = length.div_ceil(4) * 4; + assert!(ttc[offset + length..offset + padded].iter().all(|&b| b == 0), "padding is zero"); + } + } + let lengths: Vec = ttc_faces(&ttc).into_iter().flat_map(|d| ttc_tables(&ttc, d)).map(|t| t.3).collect(); + assert!(lengths.iter().any(|length| length % 4 != 0), "the fixture has unpadded lengths"); +} + +#[test] +fn collection_checksums_match_tables() { + let (a, b) = two_faces(); + let ttc = collection(&[&a, &b]).unwrap(); + for directory in ttc_faces(&ttc) { + for (tag, checksum, offset, length) in ttc_tables(&ttc, directory) { + assert_eq!(checksum, sum(&ttc[offset..offset + length])); + if &tag == b"head" { + assert_eq!(be32(&ttc, offset + 8), 0, "checkSumAdjustment is zero in a collection"); + } + } + } +} + +#[test] +fn collection_copies_tables() { + let (a, _) = two_faces(); + let ttc = collection(&[&a, &a]).unwrap(); + let mut ranges: Vec<(usize, usize)> = ttc_faces(&ttc).into_iter().flat_map(|d| ttc_tables(&ttc, d)).map(|t| (t.2, t.2 + t.3)).collect(); + assert_eq!(ranges.len(), 6); + ranges.sort(); + assert!(ranges.windows(2).all(|pair| pair[0].1 <= pair[1].0), "each face has its own tables"); +} + +#[test] +fn collection_rejects_empty() { + assert_eq!(collection(&[]), Err(FontError::EmptyCollection)); +} + +#[test] +fn collection_rejects_nested_ttc() { + let (a, _) = two_faces(); + let ttc = collection(&[&a]).unwrap(); + assert_eq!(collection(&[&a, &ttc]), Err(FontError::UnsupportedFace)); +} + +#[test] +fn collection_rejects_short_directory() { + let (a, _) = two_faces(); + assert_eq!(collection(&[&a[..3]]), Err(FontError::MalformedFont)); + assert_eq!(collection(&[&a[..12 + 16 * 2]]), Err(FontError::MalformedFont)); + let mut many = a.clone(); + set16(&mut many, 4, 400); + assert_eq!(collection(&[&a, &many]), Err(FontError::MalformedFont)); +} + +#[test] +fn collection_rejects_out_of_range_table() { + let (a, _) = two_faces(); + let (record, _, _) = table(&a, b"zzzz"); + let mut late = a.clone(); + set32(&mut late, record + 8, a.len() as u32); + assert_eq!(collection(&[&late]), Err(FontError::MalformedFont)); + let mut long = a.clone(); + set32(&mut long, record + 12, u32::MAX); + assert_eq!(collection(&[&long]), Err(FontError::MalformedFont)); +} + +#[test] +fn collection_rejects_short_head() { + let font = face(&[(b"head", head()[..8].to_vec())]); + assert_eq!(collection(&[&font]), Err(FontError::MalformedFont)); +} + +#[test] +fn collection_rejects_offset_overflow() { + // 4,096 references to one face with a 1 MiB table add up to more than 4 GiB of output, which + // 32-bit offsets cannot address. The function refuses before allocating any of it. + let big = face(&[(b"zzzz", vec![0; 1 << 20])]); + let faces = vec![&big[..]; 4096]; + assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); +} From 15cdfd8512bf88736f4f0077741911c96afcd851 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:26:23 -0800 Subject: [PATCH 02/33] craft-testkit: fonts reads Mac Roman names by character and rewrites only the family name rename_family compares a Macintosh Roman record with the family name character by character, using the Unicode mapping of Mac Roman, so a record whose non-ASCII letters differ from the name is left as it is instead of failing the rename with UnsupportedEncoding. A rename now writes only the bytes of the family name at the start of each matching string, and records that point at the same string are read once. A style name that shares the unchanged end of a full name keeps its bytes, and a name table with many records on one long string no longer allocates a copy of the string for each record. --- crates/testkit/src/fonts.rs | 163 ++++++++++++++++++++++------------ crates/testkit/tests/fonts.rs | 24 +++++ 2 files changed, 129 insertions(+), 58 deletions(-) diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs index 7231980c7a..04345b66a2 100644 --- a/crates/testkit/src/fonts.rs +++ b/crates/testkit/src/fonts.rs @@ -10,6 +10,7 @@ //! The module reads no file and no environment variable, prints nothing, and builds for //! `wasm32-unknown-unknown`. +use std::collections::HashMap; use std::fmt; use std::ops::Range; @@ -47,7 +48,7 @@ pub enum FontError { MalformedFont, /// A matching Macintosh Roman record would need a name that is not ASCII. UnsupportedEncoding, - /// A string the rename changes shares bytes with a string it keeps, or with a different replacement. + /// Bytes the rename changes are shared with a string it keeps, or with a different replacement. ConflictingNameStorage, /// [`collection`] was given no faces. EmptyCollection, @@ -66,7 +67,7 @@ impl fmt::Display for FontError { Self::MissingNameTable => "the font has no name table", Self::MalformedFont => "the font's table directory or name table is truncated or out of range", Self::UnsupportedEncoding => "a Macintosh Roman name record can only take an ASCII name", - Self::ConflictingNameStorage => "a renamed string shares its bytes with a string that must not change", + Self::ConflictingNameStorage => "the bytes of a renamed family name are shared with a string that must not change", Self::EmptyCollection => "a collection needs at least one face", Self::UnsupportedFace => "the input is not a standalone TrueType or CFF face", Self::OutputTooLarge => "the output is too large", @@ -91,7 +92,7 @@ impl std::error::Error for FontError {} /// [`FontError::InvalidName`] when a name is empty, [`FontError::UnequalLength`] when the names have /// different UTF-16 lengths, [`FontError::NameNotFound`] when no family record holds `from`, /// [`FontError::UnsupportedEncoding`] when a matching Macintosh Roman record would need non-ASCII -/// bytes, [`FontError::ConflictingNameStorage`] when a changed string shares bytes with a kept one, +/// bytes, [`FontError::ConflictingNameStorage`] when changed bytes are shared with a kept string, /// [`FontError::MissingNameTable`], [`FontError::UnsupportedFace`] for a collection, and /// [`FontError::MalformedFont`] when the directory, the `name` table or the `head` table is out of /// range or of an unknown version, or when the `name` or `head` table shares bytes with the directory @@ -244,7 +245,7 @@ fn write_face(out: &mut Vec, face: &[u8], tables: &[Table]) -> Result<(), Fo } /// How the bytes of a name record are encoded, as far as renaming reads them. -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] enum Encoding { Utf16, MacRoman, @@ -314,28 +315,42 @@ fn name_strings(face: &[u8], table: &Table) -> Result { Ok(NameStrings { names, lang_tags }) } -/// A string the rename writes: its range in the face and its new bytes. +/// Bytes the rename writes: the range of the family name at the start of a string, and the new name. +/// The rest of the string keeps its bytes. struct Edit { range: Range, bytes: Vec, } -/// Works out the strings to rewrite and the ranges of the strings that must keep their bytes. +/// Works out the family names to rewrite and the ranges of the strings that must keep their bytes. /// Refuses with [`FontError::NameNotFound`] when no family record (IDs 1, 16 and 21) holds `from`. +/// Records that point at the same string are read once. fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Result<(Vec, Vec>), FontError> { let mut edits = Vec::new(); let mut kept = strings.lang_tags.clone(); let mut family_found = false; + let mut read: HashMap<(usize, usize, Encoding, bool), bool> = HashMap::new(); for string in &strings.names { let family = FAMILY_IDS.contains(&string.name_id); - let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?; - let new = if family || string.name_id == FULL_NAME_ID { renamed(string, bytes, from, to)? } else { None }; - match new { - Some(new) => { - family_found |= family; - edits.push(Edit { range: string.range.clone(), bytes: new }); + if !family && string.name_id != FULL_NAME_ID { + kept.push(string.range.clone()); + continue; + } + let key = (string.range.start, string.range.end, string.encoding, family); + let edited = match read.get(&key) { + Some(&edited) => edited, + None => { + let edit = renamed(string, face, from, to)?; + let edited = edit.is_some(); + edits.extend(edit); + read.insert(key, edited); + edited } - None => kept.push(string.range.clone()), + }; + if edited { + family_found |= family; + } else { + kept.push(string.range.clone()); } } if !family_found { @@ -344,67 +359,99 @@ fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Resul Ok((edits, kept)) } -/// The new bytes of a family or full-name string, or `None` when it does not hold `from`. -fn renamed(string: &NameString, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { +/// The edit of a family or full-name string, or `None` when it does not hold `from`. +fn renamed(string: &NameString, face: &[u8], from: &str, to: &str) -> Result, FontError> { let family = FAMILY_IDS.contains(&string.name_id); - let encoded = match string.encoding { + let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?; + let renamed = match string.encoding { Encoding::Utf16 => renamed_utf16(family, bytes, from, to)?, Encoding::MacRoman => renamed_mac_roman(family, bytes, from, to)?, Encoding::Other => None, }; - if encoded.as_ref().is_some_and(|encoded| encoded.len() != bytes.len()) { + let Some((old_length, new)) = renamed else { + return Ok(None); + }; + if new.len() != old_length { return Err(FontError::UnequalLength); } - Ok(encoded) + let start = string.range.start; + Ok(Some(Edit { range: start..start + old_length, bytes: new })) } -/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and a space. -fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { - let value = utf16_value(bytes)?; - let new = if family { - (value == from).then(|| to.to_owned()) - } else { - value.strip_prefix(from).filter(|rest| rest.is_empty() || rest.starts_with(' ')).map(|rest| format!("{to}{rest}")) - }; - Ok(new.map(|new| new.encode_utf16().flat_map(u16::to_be_bytes).collect())) -} - -/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, byte by byte; only ASCII names are written. -fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { - if !from.is_ascii() { - return if mac_roman_may_hold(family, bytes, from) { Err(FontError::UnsupportedEncoding) } else { Ok(None) }; - } - let Some(rest) = bytes.strip_prefix(from.as_bytes()) else { - return Ok(None); - }; - if !(rest.is_empty() || (!family && rest.first() == Some(&b' '))) { - return Ok(None); - } - if !to.is_ascii() { - return Err(FontError::UnsupportedEncoding); - } - Ok(Some([to.as_bytes(), rest].concat())) -} - -/// Whether a Macintosh Roman string could hold a non-ASCII `from`. The encoding has one byte per -/// character and shares its ASCII range with Unicode, so a string that differs from `from` in length -/// or in an ASCII position cannot hold it. -fn mac_roman_may_hold(family: bool, bytes: &[u8], from: &str) -> bool { - let count = from.chars().count(); - let fits = bytes.len() == count || (!family && bytes.get(count) == Some(&b' ')); - fits && bytes.iter().zip(from.chars()).all(|(&byte, c)| !(byte.is_ascii() || c.is_ascii()) || char::from(byte) == c) -} - -/// Decodes a UTF-16BE string, refusing an odd length or an unpaired surrogate. -fn utf16_value(bytes: &[u8]) -> Result { +/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and +/// a space. Returns the byte length of `from` in the string and the bytes of `to`. +fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result)>, FontError> { let (pairs, rest) = bytes.as_chunks::<2>(); if !rest.is_empty() { return Err(FontError::MalformedFont); } let units = pairs.iter().map(|&pair| u16::from_be_bytes(pair)); - char::decode_utf16(units).collect::>().map_err(|_| FontError::MalformedFont) + if char::decode_utf16(units.clone()).any(|c| c.is_err()) { + return Err(FontError::MalformedFont); + } + let count = from.encode_utf16().count(); + if !units.clone().take(count).eq(from.encode_utf16()) { + return Ok(None); + } + match units.clone().nth(count) { + None => {} + Some(unit) if !family && unit == u16::from(b' ') => {} + Some(_) => return Ok(None), + } + Ok(Some((count * 2, to.encode_utf16().flat_map(u16::to_be_bytes).collect()))) } +/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, comparing its decoded characters +/// with `from`. Only ASCII names are written. +fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result)>, FontError> { + let count = from.chars().count(); + let Some(name) = bytes.get(..count) else { + return Ok(None); + }; + if !name.iter().map(|&byte| mac_roman_char(byte)).eq(from.chars()) { + return Ok(None); + } + match bytes.get(count) { + None => {} + Some(b' ') if !family => {} + Some(_) => return Ok(None), + } + if !from.is_ascii() || !to.is_ascii() { + return Err(FontError::UnsupportedEncoding); + } + Ok(Some((count, to.as_bytes().to_vec()))) +} + +/// The character a Macintosh Roman byte stands for. Bytes below 0x80 are ASCII; the others follow +/// the mapping at . +fn mac_roman_char(byte: u8) -> char { + match byte.checked_sub(0x80) { + None => char::from(byte), + Some(high) => MAC_ROMAN_HIGH.get(usize::from(high)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), + } +} + +/// The characters of Macintosh Roman bytes 0x80 to 0xFF. +#[rustfmt::skip] +const MAC_ROMAN_HIGH: [char; 128] = [ + '\u{00C4}', '\u{00C5}', '\u{00C7}', '\u{00C9}', '\u{00D1}', '\u{00D6}', '\u{00DC}', '\u{00E1}', + '\u{00E0}', '\u{00E2}', '\u{00E4}', '\u{00E3}', '\u{00E5}', '\u{00E7}', '\u{00E9}', '\u{00E8}', + '\u{00EA}', '\u{00EB}', '\u{00ED}', '\u{00EC}', '\u{00EE}', '\u{00EF}', '\u{00F1}', '\u{00F3}', + '\u{00F2}', '\u{00F4}', '\u{00F6}', '\u{00F5}', '\u{00FA}', '\u{00F9}', '\u{00FB}', '\u{00FC}', + '\u{2020}', '\u{00B0}', '\u{00A2}', '\u{00A3}', '\u{00A7}', '\u{2022}', '\u{00B6}', '\u{00DF}', + '\u{00AE}', '\u{00A9}', '\u{2122}', '\u{00B4}', '\u{00A8}', '\u{2260}', '\u{00C6}', '\u{00D8}', + '\u{221E}', '\u{00B1}', '\u{2264}', '\u{2265}', '\u{00A5}', '\u{00B5}', '\u{2202}', '\u{2211}', + '\u{220F}', '\u{03C0}', '\u{222B}', '\u{00AA}', '\u{00BA}', '\u{03A9}', '\u{00E6}', '\u{00F8}', + '\u{00BF}', '\u{00A1}', '\u{00AC}', '\u{221A}', '\u{0192}', '\u{2248}', '\u{2206}', '\u{00AB}', + '\u{00BB}', '\u{2026}', '\u{00A0}', '\u{00C0}', '\u{00C3}', '\u{00D5}', '\u{0152}', '\u{0153}', + '\u{2013}', '\u{2014}', '\u{201C}', '\u{201D}', '\u{2018}', '\u{2019}', '\u{00F7}', '\u{25CA}', + '\u{00FF}', '\u{0178}', '\u{2044}', '\u{20AC}', '\u{2039}', '\u{203A}', '\u{FB01}', '\u{FB02}', + '\u{2021}', '\u{00B7}', '\u{201A}', '\u{201E}', '\u{2030}', '\u{00C2}', '\u{00CA}', '\u{00C1}', + '\u{00CB}', '\u{00C8}', '\u{00CD}', '\u{00CE}', '\u{00CF}', '\u{00CC}', '\u{00D3}', '\u{00D4}', + '\u{F8FF}', '\u{00D2}', '\u{00DA}', '\u{00DB}', '\u{00D9}', '\u{0131}', '\u{02C6}', '\u{02DC}', + '\u{00AF}', '\u{02D8}', '\u{02D9}', '\u{02DA}', '\u{00B8}', '\u{02DD}', '\u{02DB}', '\u{02C7}', +]; + /// Refuses a rename whose strings overlap a string that keeps its bytes. fn check_kept(edits: &[Edit], mut kept: Vec>) -> Result<(), FontError> { kept.retain(|range| !range.is_empty()); diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/fonts.rs index f2722f11d3..6ff688c7fa 100644 --- a/crates/testkit/tests/fonts.rs +++ b/crates/testkit/tests/fonts.rs @@ -206,6 +206,16 @@ fn rename_rejects_non_ascii_mac_roman() { // "Café Sans 3" in Mac Roman, where é is 0x8E. let font = family_face(&[win(1, "Café Sans 3"), mac(1, b"Caf\x8E Sans 3")]); assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding)); + let font = family_face(&[win(1, "Café Sans 3"), mac(4, b"Caf\x8E Sans 3 Bold")]); + assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding)); +} + +#[test] +fn rename_keeps_mac_roman_names_with_other_letters() { + // Mac Roman 0x80 is "Ä" and 0x8F is "è", so neither Mac record holds "Café Sans 3". + let list = [win(1, "Café Sans 3"), mac(1, b"Caf\x80 Sans 3"), mac(4, b"Caf\x8F Sans 3 Bold")]; + let out = rename_family(&family_face(&list), "Café Sans 3", "Cafe Sans 3").unwrap(); + assert_eq!(strings(&out), vec![win(1, "Cafe Sans 3"), list[1].clone(), list[2].clone()]); } #[test] @@ -274,6 +284,20 @@ fn rename_rejects_shared_nonfamily_storage() { assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage)); } +#[test] +fn rename_keeps_a_style_sharing_the_full_name_suffix() { + // The style name (ID 2) "Bold" is the last 8 bytes of the full name, which the rename does not change. + let storage = [utf16(FROM), utf16("Source Sans 3 Bold")].concat(); + let records = [ + Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, + Rec { platform: 3, encoding: 1, name_id: 2, offset: 54, length: 8 }, + Rec { platform: 3, encoding: 1, name_id: 4, offset: 26, length: 36 }, + ]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &storage))]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), win(2, "Bold"), win(4, "Sysfont Sans3 Bold")]); +} + #[test] fn rename_updates_name_checksum() { let font = family_face(&[win(1, FROM), win(2, "Regular")]); From 466471e920cce1d66e7f4ec2f3641b07b05a38f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:44:14 -0800 Subject: [PATCH 03/33] craft-xtask: pack PNG images into .ico and .icns files The icon module packs the PNGs an app renders into a Windows .ico (icon::ico::pack) or a macOS .icns (icon::icns::pack). The app keeps its ico and icns commands, its size lists and its paths. - Every PNG is checked whole: signature, chunk lengths, types and CRCs, a 13-byte IHDR with valid fields, PLTE and IDAT order, no unknown critical chunk, and a final IEND with nothing after it. ICO entries must be 8-bit RGBA, the 32 bits per pixel a PNG entry of an ICO holds. - Images are written in increasing size whatever the input order, and two images of one size are an error. - Limits bounds the image count (16), each PNG (16 MiB) and the packed file (128 MiB). Lengths and offsets are checked against 32 bits and the output is reserved before any byte is written. read_pngs reads the input files within the same limits. - ico::read_file and icns::read_file check a committed icon at the path the app passes, for its committed_icon_is_valid test. A file with no images or no elements is an error. From DeckCraft xtask/src/ico.rs (ae9d525b), craft-launcher xtask/src/icns.rs (019330f9) and MaterialCraft xtask/src/ico.rs (6e952a9a); their tests move in under the same names, with complete PNG fixtures in place of the IHDR-only test bytes. DeckCraft, CADCraft, craft-launcher and MaterialCraft are the planned consumers; no app switches here. --- README.md | 2 +- crates/xtask/Cargo.toml | 2 +- crates/xtask/README.md | 52 +++ crates/xtask/src/icon.rs | 594 ++++++++++++++++++++++++++++++++++ crates/xtask/src/icon/icns.rs | 246 ++++++++++++++ crates/xtask/src/icon/ico.rs | 284 ++++++++++++++++ crates/xtask/src/lib.rs | 4 + 7 files changed, 1182 insertions(+), 2 deletions(-) create mode 100644 crates/xtask/src/icon.rs create mode 100644 crates/xtask/src/icon/icns.rs create mode 100644 crates/xtask/src/icon/ico.rs diff --git a/README.md b/README.md index 34bba45518..60493521a7 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-assuan`](crates/assuan/README.md): the Assuan protocol and gpg-agent's operations (key lookup, signing a digest, decrypting a session key) over any `Read + Write` stream, with a bounded canonical S-expression reader. No sockets; everything the agent sends is capped. - [`craft-affinity`](crates/affinity/README.md): bounded reader for native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): archive, object stream and a neutral document model with layers, artboards, vectors, text, tables, images and masks. Read only; mapping onto an app's document stays in the app. - [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite. -- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft. +- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes, an optional per-step JSON report, and PNG images packed into `.ico` and `.icns` files. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft; icon packing for DeckCraft, CADCraft, craft-launcher and MaterialCraft. - [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..2cead82ec1 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes and a per-step JSON report" +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes, a per-step JSON report, and .ico and .icns packing" [lints] workspace = true diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..273cd9aaaf 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -9,6 +9,7 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | +| `icon` | always | `ico::pack`, `icns::pack`, `png_size`, `png_info`, `read_pngs`, `Limits`, and `ico::read_file` and `icns::read_file` for an app's test of its committed icons | No feature is on by default. `report` adds `serde_json` and `craft-atomic`. @@ -91,6 +92,49 @@ cancel while waiting) runs no step and writes no report. The report looks like t so a reader never sees a partial report, and a failed write leaves the previous report in place. Machine, GPU, corpus and skip details stay in the app's own report. +## Icons + +```rust,no_run +use std::path::Path; +use craft_xtask::icon::{self, Limits, ico}; + +fn cmd_ico(out: &Path, inputs: &[&Path]) -> Result<(), icon::Error> { + let limits = Limits::default(); + let pngs = icon::read_pngs(inputs, &limits)?; + let file = ico::pack(&pngs, &limits)?; + std::fs::write(out, &file).map_err(|e| icon::Error::io(out, &e))?; + Ok(()) +} +``` + +The app renders the PNGs and chooses the sizes, the paths and the command name. Both formats store +each PNG as is; no image is decoded. + +- Every PNG is checked whole: the signature, each chunk's length and CRC, a first `IHDR` of 13 bytes + with valid fields, at most one `PLTE` before the first `IDAT`, at least one `IDAT` with no other + chunk between two of them, no other critical chunk, and a final empty `IEND` with nothing after + it. Images must be square and at least 1 px. +- `ico::pack` takes 1 to 256 px images in 8-bit RGBA, the form a PNG entry of an `.ico` holds + ([ICO format, part 4](https://devblogs.microsoft.com/oldnewthing/20101022-00/?p=12473/)). A 256 px + side is written as 0. +- `icns::pack` takes 16, 32, 64, 128, 256, 512 and 1024 px images and writes each into every slot of + its size: 16 `icp4`; 32 `icp5`, `ic11`; 64 `icp6`, `ic12`; 128 `ic07`; 256 `ic08`, `ic13`; 512 + `ic09`, `ic14`; 1024 `ic10` ([ICNS format](https://hexbase.dev/formats/icns/)). +- Both write the images in increasing size, whatever the input order. Two images of one size are an + error. +- `Limits` bounds the image count (default 16), each PNG (16 MiB) and the packed file (128 MiB). The + formats' 32-bit offsets and lengths also cap a file at 4 GiB - 1 byte. Sizes are checked and the + file's memory reserved before any byte is written. `read_pngs` stops reading a file one byte past + the smaller of the PNG limit and what the total limit has left. +- `ico::read_file` and `icns::read_file` read a file within the same limits and check its structure. + `ico::read` accepts only the entries `ico::pack` writes. Both readers hold each image to the PNG + limit. `icns::read` returns at most four elements for each image `Limits` allows, and returns + elements that are not PNGs as stored. An app's `committed_icon_is_valid` test passes its own icon + path, for example `assets/app-icon/.ico`. + +Errors are `icon::Error`: `Empty`, `TooManyImages`, `InvalidPng`, `NotSquare`, `UnsupportedSize`, +`DuplicateSize`, `TooLarge`, `Allocation`, `InvalidIcon` or `Io`. + ## Origin | Part | Source | @@ -98,7 +142,11 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | | `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | | `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | +| `icon::ico`: `pack`, `png_size` and the tests `packs_directory_and_payloads`, `rejects_bad_input`, `committed_icon_is_valid` | DeckCraft `xtask/src/ico.rs` at [ae9d525](https://github.com/storytold/deckcraft/blob/ae9d525bce365083bb62b4754bdd346feb2a79b0/xtask/src/ico.rs); CADCraft's copy differs only in its icon path | +| `icon::icns`: `pack`, the slot table and the tests `fills_every_slot_of_each_size`, `rejects_bad_input`, `committed_icon_is_valid`, `packs_icns_elements` | craft-launcher `xtask/src/icns.rs` at [019330f](https://github.com/storytold/craft-launcher/blob/019330f99aa90a3d6501e134fc48df8d719e15a2/xtask/src/icns.rs); MaterialCraft `xtask/src/ico.rs` at [6e952a9](https://github.com/storytold/materialcraft/blob/6e952a9a10f9bce77f330e430a828c066be6ad9b/xtask/src/ico.rs) | +| `icon`: the test `rejects_non_png` | VectorCraft `xtask/src/ico.rs` at [4373205](https://github.com/storytold/vectorcraft/blob/437320509da102f5d9aca44d411ffb254f071932/xtask/src/ico.rs) | | The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | +| The whole-PNG check, the RGBA check for `.ico`, the size order and duplicate check, `Limits`, the checked lengths and offsets, `read_pngs` and the readers | written here | ## Migration @@ -108,6 +156,10 @@ No app uses this crate yet. |---|---| | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | +| DeckCraft | Planned: `xtask/src/ico.rs` moves to `icon::ico`. The `ico` command and `packaging/icons.sh` stay in the app. | +| CADCraft | Planned: `xtask/src/ico.rs` moves to `icon::ico`. The `ico` command and `packaging/icons.sh` stay in the app. | +| craft-launcher | Planned: `xtask/src/ico.rs` and `icns.rs` move to `icon`. The `ico` and `icns` commands stay in the app. | +| MaterialCraft | Planned: `pack_ico` and `pack_icns` move to `icon`. The `ico` and `icns` commands stay in the app. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the review of this crate's first pull request. diff --git a/crates/xtask/src/icon.rs b/crates/xtask/src/icon.rs new file mode 100644 index 0000000000..dfdd907cbb --- /dev/null +++ b/crates/xtask/src/icon.rs @@ -0,0 +1,594 @@ +//! Icon packing: PNG images into a Windows `.ico` ([`ico`]) or a macOS `.icns` ([`icns`]). +//! +//! Both formats store each PNG as is, so no image is decoded. The app renders the PNGs, chooses the +//! sizes, the input and output paths and the command name, and calls [`ico::pack`] or +//! [`icns::pack`]: +//! +//! ```no_run +//! use std::path::Path; +//! use craft_xtask::icon::{self, Limits, ico}; +//! +//! fn cmd_ico(out: &Path, inputs: &[&Path]) -> Result<(), icon::Error> { +//! let limits = Limits::default(); +//! let pngs = icon::read_pngs(inputs, &limits)?; +//! let file = ico::pack(&pngs, &limits)?; +//! std::fs::write(out, &file).map_err(|e| icon::Error::io(out, &e))?; +//! Ok(()) +//! } +//! ``` +//! +//! Every PNG is checked before anything is written: the signature, every chunk's length and CRC, +//! a first `IHDR` chunk of 13 bytes with valid fields, at least one `IDAT` chunk and a final `IEND` +//! chunk with nothing after it. The pixel data is not decompressed. Images are written in increasing +//! size, whatever the order of the input, and two images of one size are an error. + +pub mod icns; +pub mod ico; + +use std::fmt; +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +/// The PNG file signature. +const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n"; + +/// The largest chunk length and image side the PNG format allows (2^31 - 1). +const PNG_MAX_U31: u32 = 0x7fff_ffff; + +/// Size limits for the images and the packed file. Every input over a limit is an error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The most images in one icon file. Default 16. + pub max_images: usize, + /// The most bytes in one PNG. Default 16 MiB. + pub max_png_bytes: usize, + /// The most bytes in the packed file, and in the PNGs that [`read_pngs`] reads together. + /// Default 128 MiB. The formats' 32-bit offsets and lengths also cap a packed file at + /// 4 GiB - 1 byte. + pub max_total_bytes: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { max_images: 16, max_png_bytes: 16 << 20, max_total_bytes: 128 << 20 } + } +} + +/// Why an icon could not be packed, read or checked. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// No images were given. + Empty, + /// More images than [`Limits::max_images`], or than the format can hold. + TooManyImages { + /// The number of images given. + count: usize, + /// The most allowed. + max: usize, + }, + /// The bytes are not a complete, well-formed PNG, or not the PNG kind the format needs. + InvalidPng(String), + /// The image is not square, or a side is 0. + NotSquare { + /// The width from `IHDR`. + width: u32, + /// The height from `IHDR`. + height: u32, + }, + /// The format has no entry for an image of this size. + UnsupportedSize { + /// `"ICO"` or `"ICNS"`. + format: &'static str, + /// The image's side in pixels. + size: u32, + }, + /// Two images have the same size. + DuplicateSize(u32), + /// An input or the packed file is over a limit. + TooLarge(String), + /// The memory for the packed file could not be reserved. + Allocation(usize), + /// An icon file that was read is not well formed. + InvalidIcon(String), + /// A file could not be read or written. + Io { + /// The file. + path: PathBuf, + /// The error the OS returned. + cause: String, + }, +} + +impl Error { + /// An [`Error::Io`] for `path`. + pub fn io(path: &Path, e: &io::Error) -> Self { + Error::Io { path: path.to_path_buf(), cause: e.to_string() } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Empty => f.write_str("need at least one PNG"), + Error::TooManyImages { count, max } => write!(f, "{count} images given, at most {max} allowed"), + Error::InvalidPng(m) => write!(f, "not a valid PNG: {m}"), + Error::NotSquare { width, height } => write!(f, "icon images must be square and at least 1 px, got {width}x{height}"), + Error::UnsupportedSize { format: "ICO", size } => write!(f, "ICO images must be 1 to 256 px, got {size}"), + Error::UnsupportedSize { format, size } => { + write!(f, "{format} images must be 16, 32, 64, 128, 256, 512 or 1024 px, got {size}") + } + Error::DuplicateSize(size) => write!(f, "two images are {size} px; give each size once"), + Error::TooLarge(m) => write!(f, "too large: {m}"), + Error::Allocation(n) => write!(f, "could not reserve {n} bytes for the icon file"), + Error::InvalidIcon(m) => write!(f, "not a valid icon file: {m}"), + Error::Io { path, cause } => write!(f, "{}: {cause}", path.display()), + } + } +} + +impl std::error::Error for Error {} + +impl From for String { + fn from(e: Error) -> Self { + e.to_string() + } +} + +/// The `IHDR` fields of a PNG that [`png_info`] checked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PngInfo { + /// Width in pixels, 1 to 2^31 - 1. + pub width: u32, + /// Height in pixels, 1 to 2^31 - 1. + pub height: u32, + /// Bits per sample or per palette index. + pub bit_depth: u8, + /// 0 gray, 2 RGB, 3 palette, 4 gray and alpha, 6 RGBA. + pub color_type: u8, +} + +impl PngInfo { + /// 8-bit RGBA, the 32 bits per pixel that a PNG entry of an ICO file holds. + pub fn is_rgba8(&self) -> bool { + self.color_type == 6 && self.bit_depth == 8 + } +} + +/// Width and height from a PNG's `IHDR` chunk, after [`png_info`] has checked the whole PNG. +pub fn png_size(png: &[u8]) -> Result<(u32, u32), Error> { + png_info(png).map(|i| (i.width, i.height)) +} + +/// Checks the structure of a whole PNG and returns its `IHDR` fields. +/// +/// The checks are the signature; every chunk's length (at most 2^31 - 1), type (four ASCII letters, +/// the third uppercase) and CRC; a first `IHDR` chunk of 13 bytes with a width and height of 1 to 2^31 - 1, a valid +/// color type and bit depth pair, compression and filter method 0 and interlace method 0 or 1; at +/// most one `PLTE` chunk, of 1 to 256 entries (2^bit depth in a palette image), before the first +/// `IDAT` chunk, required in a palette image and absent from a gray one; at least one `IDAT` chunk, +/// all of them consecutive; no critical chunk other than these four; and an empty `IEND` chunk at the +/// end with nothing after it. +pub fn png_info(png: &[u8]) -> Result { + let bad = |m: &str| Error::InvalidPng(m.to_string()); + if png.get(..8) != Some(PNG_SIGNATURE.as_slice()) { + return Err(bad("no PNG signature")); + } + let mut at = 8usize; + let mut info = None; + // `idat_done` is set by the first chunk after a run of IDAT chunks. + let (mut plte, mut idat, mut idat_done) = (false, false, false); + loop { + let header = png.get(at..at + 8).ok_or_else(|| bad("truncated chunk header"))?; + let len = be32(&header[..4]); + let kind: [u8; 4] = [header[4], header[5], header[6], header[7]]; + if len > PNG_MAX_U31 { + return Err(bad("chunk length over 2^31 - 1")); + } + if !kind.iter().all(u8::is_ascii_alphabetic) || !kind[2].is_ascii_uppercase() { + return Err(bad("chunk type is not four ASCII letters with an uppercase third letter")); + } + let data_end = (at + 8).checked_add(len as usize).ok_or_else(|| bad("chunk length overflows"))?; + let crc_end = data_end.checked_add(4).ok_or_else(|| bad("chunk length overflows"))?; + let (Some(body), Some(stored)) = (png.get(at + 4..data_end), png.get(data_end..crc_end)) else { + return Err(bad("truncated chunk")); + }; + if crc32(body) != be32(stored) { + return Err(Error::InvalidPng(format!("bad CRC in the {} chunk", String::from_utf8_lossy(&kind)))); + } + let data = &body[4..]; + if idat && &kind != b"IDAT" { + idat_done = true; + } + match (&kind, info) { + (b"IHDR", None) => info = Some(ihdr(data)?), + (_, None) => return Err(bad("the first chunk is not IHDR")), + (b"IHDR", Some(_)) => return Err(bad("a second IHDR chunk")), + (b"PLTE", Some(i)) => { + if plte || idat { + return Err(bad("a second PLTE chunk, or a PLTE chunk after IDAT")); + } + if matches!(i.color_type, 0 | 4) { + return Err(bad("a PLTE chunk in a gray image")); + } + // A palette image indexes at most 2^bit_depth entries. + let max_entries = if i.color_type == 3 { 1usize << i.bit_depth } else { 256 }; + if data.is_empty() || data.len() > 3 * max_entries || data.len() % 3 != 0 { + return Err(Error::InvalidPng(format!("PLTE chunk is not 1 to {max_entries} entries of 3 bytes"))); + } + plte = true; + } + (b"IDAT", Some(i)) => { + if i.color_type == 3 && !plte { + return Err(bad("a palette image without a PLTE chunk before its IDAT")); + } + if idat_done { + return Err(bad("IDAT chunks are not consecutive")); + } + idat = true; + } + (b"IEND", Some(i)) => { + if len != 0 { + return Err(bad("IEND chunk with data")); + } + if !idat { + return Err(bad("no IDAT chunk")); + } + if crc_end != png.len() { + return Err(bad("bytes after the IEND chunk")); + } + return Ok(i); + } + // An uppercase first letter marks a critical chunk, which a decoder must understand. + (k, Some(_)) if k[0].is_ascii_uppercase() => { + return Err(Error::InvalidPng(format!("unknown critical chunk {}", String::from_utf8_lossy(k)))); + } + _ => {} + } + at = crc_end; + } +} + +/// The checked fields of an `IHDR` chunk's 13 data bytes. +fn ihdr(data: &[u8]) -> Result { + let bad = |m: &str| Error::InvalidPng(m.to_string()); + let [w0, w1, w2, w3, h0, h1, h2, h3, bit_depth, color_type, compression, filter, interlace] = data else { + return Err(bad("IHDR chunk is not 13 bytes")); + }; + let (width, height) = (u32::from_be_bytes([*w0, *w1, *w2, *w3]), u32::from_be_bytes([*h0, *h1, *h2, *h3])); + if width == 0 || height == 0 || width > PNG_MAX_U31 || height > PNG_MAX_U31 { + return Err(Error::InvalidPng(format!("image size {width}x{height} is outside 1 to 2^31 - 1"))); + } + let depths: &[u8] = match color_type { + 0 => &[1, 2, 4, 8, 16], + 3 => &[1, 2, 4, 8], + 2 | 4 | 6 => &[8, 16], + _ => return Err(Error::InvalidPng(format!("color type {color_type}"))), + }; + if !depths.contains(bit_depth) { + return Err(Error::InvalidPng(format!("bit depth {bit_depth} with color type {color_type}"))); + } + if *compression != 0 || *filter != 0 || *interlace > 1 { + return Err(bad("unknown compression, filter or interlace method")); + } + Ok(PngInfo { width, height, bit_depth: *bit_depth, color_type: *color_type }) +} + +/// Reads the PNGs at `paths`, in order, within `limits`: at most [`Limits::max_images`] files, each +/// at most [`Limits::max_png_bytes`] and together at most [`Limits::max_total_bytes`]. A file over a +/// limit is an error before more than one byte past the limit is read. The bytes are not checked; +/// [`ico::pack`] and [`icns::pack`] check them. +pub fn read_pngs>(paths: &[P], limits: &Limits) -> Result>, Error> { + if paths.len() > limits.max_images { + return Err(Error::TooManyImages { count: paths.len(), max: limits.max_images }); + } + let mut out = Vec::with_capacity(paths.len()); + let mut left = limits.max_total_bytes; + for path in paths { + let path = path.as_ref(); + // Each read stops at the smaller of the file limit and what the total limit has left. + let png = match read_bounded(path, limits.max_png_bytes.min(left)) { + Err(Error::TooLarge(_)) if left < limits.max_png_bytes => { + return Err(Error::TooLarge(format!("the PNGs hold more than {} bytes together", limits.max_total_bytes))); + } + r => r?, + }; + left -= png.len(); + out.push(png); + } + Ok(out) +} + +/// The bytes of the file at `path`, or [`Error::TooLarge`] when it holds more than `max` bytes. +pub(crate) fn read_bounded(path: &Path, max: usize) -> Result, Error> { + let too_large = || Error::TooLarge(format!("{} holds more than {max} bytes", path.display())); + let file = File::open(path).map_err(|e| Error::io(path, &e))?; + let len = file.metadata().map_err(|e| Error::io(path, &e))?.len(); + if len > max as u64 { + return Err(too_large()); + } + let mut buf = Vec::new(); + // `len` is at most `max`, a usize. The file can grow after the size check, so the read stops one + // byte past the limit. + buf.try_reserve_exact(len as usize).map_err(|_| Error::Allocation(len as usize))?; + file.take((max as u64).saturating_add(1)).read_to_end(&mut buf).map_err(|e| Error::io(path, &e))?; + if buf.len() > max { + return Err(too_large()); + } + Ok(buf) +} + +/// Checks every PNG against `limits`, returns each one's side in pixels with its index, sorted by +/// size, and rejects two images of one size. `check` checks each square image's `IHDR` fields and +/// side for the format; `format_max` is the most images the format can hold. +fn sorted_sizes>( + pngs: &[P], + limits: &Limits, + format_max: usize, + check: impl Fn(&PngInfo) -> Result<(), Error>, +) -> Result, Error> { + if pngs.is_empty() { + return Err(Error::Empty); + } + let max = limits.max_images.min(format_max); + if pngs.len() > max { + return Err(Error::TooManyImages { count: pngs.len(), max }); + } + let mut sizes = Vec::with_capacity(pngs.len()); + for (i, png) in pngs.iter().enumerate() { + let png = png.as_ref(); + if png.len() > limits.max_png_bytes { + return Err(Error::TooLarge(format!("image {} holds {} bytes, more than {}", i + 1, png.len(), limits.max_png_bytes))); + } + let info = png_info(png)?; + if info.width != info.height { + return Err(Error::NotSquare { width: info.width, height: info.height }); + } + check(&info)?; + sizes.push((info.width, i)); + } + sizes.sort_unstable(); + if let Some(w) = sizes.windows(2).find(|w| w[0].0 == w[1].0) { + return Err(Error::DuplicateSize(w[0].0)); + } + Ok(sizes) +} + +/// Checks a packed file's size against `limits` and the formats' 32-bit fields, and reserves it. +fn reserve(total: u64, limits: &Limits) -> Result, Error> { + if total > u64::from(u32::MAX) { + return Err(Error::TooLarge(format!("the icon file would hold {total} bytes, more than 32-bit offsets reach"))); + } + if total > limits.max_total_bytes as u64 { + return Err(Error::TooLarge(format!("the icon file would hold {total} bytes, more than {}", limits.max_total_bytes))); + } + let total = total as usize; + let mut out = Vec::new(); + out.try_reserve_exact(total).map_err(|_| Error::Allocation(total))?; + Ok(out) +} + +/// A big-endian u32 from the first four bytes of `b`, which holds at least four. +fn be32(b: &[u8]) -> u32 { + u32::from_be_bytes([b[0], b[1], b[2], b[3]]) +} + +/// The CRC-32 table of the PNG specification (polynomial 0xedb88320). +const CRC_TABLE: [u32; 256] = { + let mut table = [0u32; 256]; + let mut n = 0; + while n < 256 { + let mut c = n as u32; + let mut k = 0; + while k < 8 { + c = if c & 1 != 0 { 0xedb8_8320 ^ (c >> 1) } else { c >> 1 }; + k += 1; + } + table[n] = c; + n += 1; + } + table +}; + +/// The CRC-32 that a PNG chunk stores over its type and data. +fn crc32(bytes: &[u8]) -> u32 { + !bytes.iter().fold(u32::MAX, |c, &b| CRC_TABLE[((c ^ u32::from(b)) & 0xff) as usize] ^ (c >> 8)) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// A complete PNG of `width` x `height` transparent pixels, with its pixel data in stored + /// (uncompressed) deflate blocks. + pub(crate) fn png_of(width: u32, height: u32, bit_depth: u8, color_type: u8) -> Vec { + let channels: usize = match color_type { + 2 => 3, + 4 => 2, + 6 => 4, + _ => 1, + }; + let row = (width as usize * channels * usize::from(bit_depth)).div_ceil(8) + 1; + let raw = vec![0u8; row * height as usize]; + let mut z = vec![0x78, 0x01]; + let mut blocks = raw.chunks(0xffff).peekable(); + while let Some(block) = blocks.next() { + let n = block.len() as u16; + z.push(u8::from(blocks.peek().is_none())); + z.extend_from_slice(&n.to_le_bytes()); + z.extend_from_slice(&(!n).to_le_bytes()); + z.extend_from_slice(block); + } + let (mut a, mut b) = (1u32, 0u32); + for &x in &raw { + a = (a + u32::from(x)) % 65521; + b = (b + a) % 65521; + } + z.extend_from_slice(&((b << 16) | a).to_be_bytes()); + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&width.to_be_bytes()); + ihdr.extend_from_slice(&height.to_be_bytes()); + ihdr.extend_from_slice(&[bit_depth, color_type, 0, 0, 0]); + let mut png = PNG_SIGNATURE.to_vec(); + let mut chunks = vec![(*b"IHDR", ihdr)]; + if color_type == 3 { + chunks.push((*b"PLTE", vec![0, 0, 0])); + } + chunks.push((*b"IDAT", z)); + chunks.push((*b"IEND", Vec::new())); + for (kind, data) in chunks { + push_chunk(&mut png, &kind, &data); + } + png + } + + /// A square 8-bit RGBA PNG of `size` px. + pub(crate) fn rgba(size: u32) -> Vec { + png_of(size, size, 8, 6) + } + + pub(crate) fn push_chunk(png: &mut Vec, kind: &[u8; 4], data: &[u8]) { + png.extend_from_slice(&(data.len() as u32).to_be_bytes()); + let start = png.len(); + png.extend_from_slice(kind); + png.extend_from_slice(data); + let crc = crc32(&png[start..]); + png.extend_from_slice(&crc.to_be_bytes()); + } + + /// A 1x1 transparent RGBA PNG written by an independent encoder (Python's `struct`, `zlib.crc32` + /// and `zlib.compress` at level 0) from the layout in the W3C PNG specification. + const ONE_PIXEL_PNG: [u8; 73] = [ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x10, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0x01, 0x05, 0x00, + 0xfa, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x64, 0x78, 0x95, 0x38, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, + 0xae, 0x42, 0x60, 0x82, + ]; + + #[test] + fn crc_matches_the_standard_check_values() { + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + assert_eq!(crc32(b"IEND"), 0xae42_6082); + } + + #[test] + fn fixtures_match_an_independent_encoder() { + assert_eq!(rgba(1), ONE_PIXEL_PNG); + assert_eq!(png_info(&ONE_PIXEL_PNG), Ok(PngInfo { width: 1, height: 1, bit_depth: 8, color_type: 6 })); + } + + #[test] + fn rejects_non_png() { + assert!(matches!(png_size(b"GIF89a"), Err(Error::InvalidPng(_)))); + assert!(matches!(png_size(&[]), Err(Error::InvalidPng(_)))); + assert_eq!(png_size(&rgba(48)), Ok((48, 48))); + assert_eq!(png_size(&png_of(3, 5, 1, 3)), Ok((3, 5))); + } + + #[test] + fn rejects_a_header_only_png() { + // The 33-byte prefix the app copies' tests used: signature and IHDR, without the IHDR's CRC, + // an IDAT or an IEND. + let full = rgba(16); + for cut in [24, 29, 33, full.len() - 12, full.len() - 1] { + assert!(matches!(png_info(&full[..cut]), Err(Error::InvalidPng(_))), "accepted {cut} of {} bytes", full.len()); + } + } + + #[test] + fn rejects_a_wrong_ihdr_length() { + let mut png = PNG_SIGNATURE.to_vec(); + push_chunk(&mut png, b"IHDR", &[0, 0, 0, 16, 0, 0, 0, 16, 8, 6, 0, 0]); + push_chunk(&mut png, b"IDAT", &[0]); + push_chunk(&mut png, b"IEND", &[]); + assert_eq!(png_info(&png), Err(Error::InvalidPng("IHDR chunk is not 13 bytes".into()))); + } + + #[test] + fn rejects_a_bad_crc_and_trailing_bytes() { + let mut png = rgba(16); + png[29] ^= 1; // the IHDR's CRC + assert!(matches!(png_info(&png), Err(Error::InvalidPng(m)) if m.contains("CRC"))); + let mut png = rgba(16); + png.push(0); + assert_eq!(png_info(&png), Err(Error::InvalidPng("bytes after the IEND chunk".into()))); + } + + #[test] + fn rejects_bad_ihdr_fields() { + let mut zero = PNG_SIGNATURE.to_vec(); + push_chunk(&mut zero, b"IHDR", &[0, 0, 0, 0, 0, 0, 0, 1, 8, 6, 0, 0, 0]); + assert!(matches!(png_info(&zero), Err(Error::InvalidPng(_)))); + for (depth, color) in [(8, 1), (4, 6), (16, 3), (8, 7)] { + let mut png = PNG_SIGNATURE.to_vec(); + push_chunk(&mut png, b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, depth, color, 0, 0, 0]); + assert!(matches!(png_info(&png), Err(Error::InvalidPng(_))), "accepted depth {depth} color {color}"); + } + let mut no_plte = PNG_SIGNATURE.to_vec(); + push_chunk(&mut no_plte, b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 3, 0, 0, 0]); + push_chunk(&mut no_plte, b"IDAT", &[0]); + push_chunk(&mut no_plte, b"IEND", &[]); + assert!(matches!(png_info(&no_plte), Err(Error::InvalidPng(m)) if m.contains("PLTE"))); + } + + #[test] + fn rejects_chunks_out_of_order() { + let build = |ihdr: [u8; 13], chunks: &[(&[u8; 4], &[u8])]| { + let mut png = PNG_SIGNATURE.to_vec(); + push_chunk(&mut png, b"IHDR", &ihdr); + for (kind, data) in chunks { + push_chunk(&mut png, kind, data); + } + push_chunk(&mut png, b"IEND", &[]); + png + }; + let rgba = [0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]; + let gray = [0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0]; + let palette = [0, 0, 0, 1, 0, 0, 0, 1, 8, 3, 0, 0, 0]; + assert!(png_info(&build(rgba, &[(b"IDAT", &[0]), (b"IDAT", &[0])])).is_ok()); + assert!(png_info(&build(palette, &[(b"PLTE", &[0, 0, 0]), (b"IDAT", &[0])])).is_ok()); + assert!(png_info(&build([0, 0, 0, 1, 0, 0, 0, 1, 1, 3, 0, 0, 0], &[(b"PLTE", &[0; 6]), (b"IDAT", &[0])])).is_ok()); + assert!(png_info(&build(rgba, &[(b"zzZz", &[]), (b"IDAT", &[0])])).is_ok()); + let bad = [ + build(rgba, &[(b"IDAT", &[0]), (b"tEXt", b"a\0b"), (b"IDAT", &[0])]), + build(rgba, &[(b"IDAT", &[0]), (b"PLTE", &[0, 0, 0])]), + build(rgba, &[(b"PLTE", &[0, 0, 0]), (b"PLTE", &[0, 0, 0]), (b"IDAT", &[0])]), + build(rgba, &[(b"PLTE", &[0, 0]), (b"IDAT", &[0])]), + build(gray, &[(b"PLTE", &[0, 0, 0]), (b"IDAT", &[0])]), + build([0, 0, 0, 1, 0, 0, 0, 1, 1, 3, 0, 0, 0], &[(b"PLTE", &[0; 9]), (b"IDAT", &[0])]), + build(rgba, &[(b"IDAT", &[0]), (b"ZZZZ", &[])]), + build(rgba, &[(b"zzzz", &[]), (b"IDAT", &[0])]), + ]; + for (n, png) in bad.iter().enumerate() { + assert!(matches!(png_info(png), Err(Error::InvalidPng(_))), "accepted case {n}"); + } + } + + #[test] + fn read_pngs_stops_at_the_limits() { + let dir = tempfile::tempdir().expect("temporary directory"); + let (a, b) = (dir.path().join("a.png"), dir.path().join("b.png")); + std::fs::write(&a, rgba(16)).expect("write a"); + std::fs::write(&b, rgba(32)).expect("write b"); + let limits = Limits::default(); + assert_eq!(read_pngs(&[&a, &b], &limits), Ok(vec![rgba(16), rgba(32)])); + + let small = Limits { max_png_bytes: rgba(16).len(), ..limits }; + assert!(matches!(read_pngs(&[&a, &b], &small), Err(Error::TooLarge(m)) if m.contains("b.png"))); + let one = Limits { max_images: 1, ..limits }; + assert_eq!(read_pngs(&[&a, &b], &one), Err(Error::TooManyImages { count: 2, max: 1 })); + let total = Limits { max_total_bytes: rgba(16).len() + 1, ..limits }; + assert!(matches!(read_pngs(&[&a, &b], &total), Err(Error::TooLarge(m)) if m.contains("together"))); + let first = Limits { max_total_bytes: rgba(16).len() - 1, ..limits }; + assert!(matches!(read_pngs(&[&a], &first), Err(Error::TooLarge(m)) if m.contains("together"))); + assert!(matches!(read_pngs(&[dir.path().join("missing.png")], &limits), Err(Error::Io { .. }))); + } + + #[test] + fn reserve_rejects_sizes_past_32_bits_and_the_limit() { + let limits = Limits { max_total_bytes: usize::MAX, ..Limits::default() }; + assert!(matches!(reserve(u64::from(u32::MAX) + 1, &limits), Err(Error::TooLarge(_)))); + assert!(matches!(reserve(101, &Limits { max_total_bytes: 100, ..limits }), Err(Error::TooLarge(_)))); + assert_eq!(reserve(100, &Limits { max_total_bytes: 100, ..limits }).map(|v| v.capacity() >= 100), Ok(true)); + } +} diff --git a/crates/xtask/src/icon/icns.rs b/crates/xtask/src/icon/icns.rs new file mode 100644 index 0000000000..27e773fd13 --- /dev/null +++ b/crates/xtask/src/icon/icns.rs @@ -0,0 +1,246 @@ +//! macOS `.icns` files of PNG images, written on any OS. +//! +//! The file starts with the magic `icns` and the file's length, followed by elements: a four-letter +//! type, the element's length including its 8-byte header, and a PNG. Both lengths are big-endian +//! ([ICNS format](https://hexbase.dev/formats/icns/)). Each PNG fills every slot of its pixel size in +//! [`SLOTS`]: a 32 px image is both the 32 pt icon (`icp5`) and the 16 pt @2x one (`ic11`). + +use std::path::Path; + +use super::{Error, Limits, read_bounded, reserve, sorted_sizes}; + +/// The PNG element types, by pixel size, in the order they are written. +pub const SLOTS: [(u32, [u8; 4]); 11] = [ + (16, *b"icp4"), + (32, *b"icp5"), + (32, *b"ic11"), // 16 @2x + (64, *b"icp6"), + (64, *b"ic12"), // 32 @2x + (128, *b"ic07"), + (256, *b"ic08"), + (256, *b"ic13"), // 128 @2x + (512, *b"ic09"), + (512, *b"ic14"), // 256 @2x + (1024, *b"ic10"), // 512 @2x +]; + +/// The number of different sizes in [`SLOTS`], and so the most images an `.icns` file holds. +pub const MAX_IMAGES: usize = 7; + +/// The most elements [`read`] returns for each image [`Limits::max_images`] allows. A file from +/// [`pack`] holds at most 2 per image, and other tools also write a table of contents and other +/// elements that are not images. +pub const ELEMENTS_PER_IMAGE: usize = 4; + +/// The magic and length at the start of the file, and the type and length of each element, in bytes. +const HEADER: u64 = 8; + +/// The element types of [`SLOTS`] that an image of `size` px fills. +fn types(size: u32) -> impl Iterator { + let slots: &'static [(u32, [u8; 4]); 11] = &SLOTS; + slots.iter().filter(move |(s, _)| *s == size).map(|(_, kind)| kind) +} + +/// An `.icns` file holding `pngs`: each square, one of the sizes in [`SLOTS`] and a different size +/// from the others. The elements are written in increasing size, whatever the order of `pngs`, and +/// in [`SLOTS`] order within a size. +pub fn pack>(pngs: &[P], limits: &Limits) -> Result, Error> { + let sizes = sorted_sizes(pngs, limits, MAX_IMAGES, |info| match types(info.width).next() { + Some(_) => Ok(()), + None => Err(Error::UnsupportedSize { format: "ICNS", size: info.width }), + })?; + let total = sizes.iter().fold(HEADER, |t, &(size, i)| { + let element = HEADER.saturating_add(pngs[i].as_ref().len() as u64); + t.saturating_add(element.saturating_mul(types(size).count() as u64)) + }); + let mut out = reserve(total, limits)?; + // `reserve` checked that the whole file, and so every element, fits in a u32. + out.extend_from_slice(b"icns"); + out.extend_from_slice(&(total as u32).to_be_bytes()); + for &(size, i) in &sizes { + let png = pngs[i].as_ref(); + let len = (HEADER + png.len() as u64) as u32; + for kind in types(size) { + out.extend_from_slice(kind); + out.extend_from_slice(&len.to_be_bytes()); + out.extend_from_slice(png); + } + } + Ok(out) +} + +/// One element of an `.icns` file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Element { + /// The four-letter type, for example `ic10`. + pub kind: [u8; 4], + /// The data after the 8-byte element header. + pub data: Vec, +} + +/// The elements of an `.icns` file, in file order. +/// +/// The checks are the magic `icns`, a stated length equal to the file's length and at most +/// [`Limits::max_total_bytes`], 1 to [`ELEMENTS_PER_IMAGE`] times [`Limits::max_images`] +/// elements, and elements of at least 8 bytes, with at most [`Limits::max_png_bytes`] of data, that +/// end exactly at the end of the file. The data is returned as stored: files written by other tools also hold elements that are not +/// PNGs, such as a table of contents. Pass an element's data to [`png_info`](super::png_info) to check +/// it. +pub fn read(icns: &[u8], limits: &Limits) -> Result, Error> { + let bad = Error::InvalidIcon; + if icns.len() > limits.max_total_bytes { + return Err(Error::TooLarge(format!("the icon file holds {} bytes, more than {}", icns.len(), limits.max_total_bytes))); + } + let [b'i', b'c', b'n', b's', l0, l1, l2, l3, ..] = icns else { + return Err(bad("no icns header".into())); + }; + let stated = u32::from_be_bytes([*l0, *l1, *l2, *l3]) as usize; + if stated != icns.len() { + return Err(bad(format!("the header says {stated} bytes but the file holds {}", icns.len()))); + } + let max_elements = limits.max_images.saturating_mul(ELEMENTS_PER_IMAGE); + let mut out = Vec::new(); + let mut at = 8; + while at < icns.len() { + if out.len() == max_elements { + return Err(Error::TooLarge(format!("the icon file holds more than {max_elements} elements"))); + } + let header = icns.get(at..at + 8).ok_or_else(|| bad(format!("truncated element at byte {at}")))?; + let kind = [header[0], header[1], header[2], header[3]]; + let len = u32::from_be_bytes([header[4], header[5], header[6], header[7]]) as usize; + let data = at + .checked_add(len) + .filter(|_| len >= 8) + .and_then(|end| icns.get(at + 8..end)) + .ok_or_else(|| bad(format!("the element at byte {at} has a bad length {len}")))?; + if data.len() > limits.max_png_bytes { + return Err(Error::TooLarge(format!("the element at byte {at} holds {} bytes, more than {}", data.len(), limits.max_png_bytes))); + } + out.push(Element { kind, data: data.to_vec() }); + at += len; + } + if out.is_empty() { + return Err(bad("the icon file holds no elements".into())); + } + Ok(out) +} + +/// [`read`] on the file at `path`, which is read only up to [`Limits::max_total_bytes`]. An app's +/// test of its committed icon passes the icon's path. +pub fn read_file(path: &Path, limits: &Limits) -> Result, Error> { + read(&read_bounded(path, limits.max_total_bytes)?, limits) +} + +#[cfg(test)] +mod tests { + use super::super::png_size; + use super::super::tests::{png_of, rgba}; + use super::*; + + fn kinds(icns: &[u8]) -> Vec { + read(icns, &Limits::default()).unwrap().iter().map(|e| String::from_utf8_lossy(&e.kind).into_owned()).collect() + } + + #[test] + fn fills_every_slot_of_each_size() { + let (a, b) = (rgba(32), rgba(1024)); + let icns = pack(&[a.clone(), b.clone()], &Limits::default()).unwrap(); + assert_eq!(&icns[..4], b"icns"); + assert_eq!(u32::from_be_bytes(icns[4..8].try_into().unwrap()) as usize, icns.len()); + let e = read(&icns, &Limits::default()).unwrap(); + assert_eq!(kinds(&icns), ["icp5", "ic11", "ic10"]); + assert_eq!(e[0].data, a); + assert_eq!(e[1].data, a); + assert_eq!(e[2].data, b); + } + + #[test] + fn packs_icns_elements() { + let (a, b) = (rgba(16), rgba(32)); + let icns = pack(&[a.clone(), b.clone()], &Limits::default()).unwrap(); + // The header and the first element's header, byte for byte from the documented layout. + let total = (8 + (8 + a.len()) + 2 * (8 + b.len())) as u32; + let mut want = b"icns".to_vec(); + want.extend_from_slice(&total.to_be_bytes()); + want.extend_from_slice(b"icp4"); + want.extend_from_slice(&((a.len() + 8) as u32).to_be_bytes()); + assert_eq!(&icns[..16], &want[..]); + assert_eq!(icns.len(), total as usize); + let at = 16 + a.len(); + assert_eq!(&icns[at..at + 4], b"icp5"); + assert_eq!(u32::from_be_bytes(icns[at + 4..at + 8].try_into().unwrap()) as usize, b.len() + 8); + assert_eq!(kinds(&icns), ["icp4", "icp5", "ic11"]); + } + + #[test] + fn writes_every_size_in_slot_order() { + let sizes = [1024, 512, 256, 128, 64, 32, 16]; + let icns = pack(&sizes.map(rgba), &Limits::default()).unwrap(); + let want: Vec = SLOTS.iter().map(|(_, k)| String::from_utf8_lossy(k).into_owned()).collect(); + assert_eq!(kinds(&icns), want); + for e in read(&icns, &Limits::default()).unwrap() { + let size = SLOTS.iter().find(|(_, k)| *k == e.kind).map(|(s, _)| *s).unwrap(); + assert_eq!(png_size(&e.data), Ok((size, size))); + } + } + + #[test] + fn rejects_bad_input() { + let limits = Limits::default(); + assert_eq!(pack::>(&[], &limits), Err(Error::Empty)); + assert_eq!(pack(&[rgba(48)], &limits), Err(Error::UnsupportedSize { format: "ICNS", size: 48 })); + assert!(matches!(pack(&[b"GIF89a".to_vec()], &limits), Err(Error::InvalidPng(_)))); + assert_eq!(pack(&[png_of(32, 16, 8, 6)], &limits), Err(Error::NotSquare { width: 32, height: 16 })); + assert_eq!(pack(&[rgba(32), rgba(32)], &limits), Err(Error::DuplicateSize(32))); + // Each image fills two slots here, so the file holds twice its PNG bytes. + let one = rgba(32).len() as u64; + let tight = Limits { max_total_bytes: (8 + 2 * (8 + one) - 1) as usize, ..limits }; + assert!(matches!(pack(&[rgba(32)], &tight), Err(Error::TooLarge(_)))); + assert!(pack(&[rgba(32)], &Limits { max_total_bytes: tight.max_total_bytes + 1, ..limits }).is_ok()); + } + + #[test] + fn read_rejects_bad_files() { + let limits = Limits::default(); + let icns = pack(&[rgba(16)], &limits).unwrap(); + assert!(matches!(read(b"GIF89a", &limits), Err(Error::InvalidIcon(_)))); + assert!(matches!(read(b"icns\0\0\0\x08", &limits), Err(Error::InvalidIcon(m)) if m.contains("no elements"))); + assert!(matches!(read(&icns[..icns.len() - 1], &limits), Err(Error::InvalidIcon(_)))); + let mut short = icns.clone(); + short[12..16].copy_from_slice(&4u32.to_be_bytes()); + assert!(matches!(read(&short, &limits), Err(Error::InvalidIcon(_)))); + let mut long = icns.clone(); + long[12..16].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(matches!(read(&long, &limits), Err(Error::InvalidIcon(_)))); + assert!(matches!(read(&icns, &Limits { max_total_bytes: 8, ..limits }), Err(Error::TooLarge(_)))); + let small = Limits { max_png_bytes: rgba(16).len() - 1, ..limits }; + assert!(matches!(read(&icns, &small), Err(Error::TooLarge(m)) if m.contains("byte 8"))); + } + + #[test] + fn read_stops_at_the_element_limit() { + let empty_elements = |n: u32| { + let mut f = b"icns".to_vec(); + f.extend_from_slice(&(8 + 8 * n).to_be_bytes()); + for _ in 0..n { + f.extend_from_slice(b"TOC "); + f.extend_from_slice(&8u32.to_be_bytes()); + } + f + }; + let one = Limits { max_images: 1, ..Limits::default() }; + assert_eq!(read(&empty_elements(4), &one).map(|e| e.len()), Ok(4)); + assert!(matches!(read(&empty_elements(5), &one), Err(Error::TooLarge(m)) if m.contains("4 elements"))); + } + + #[test] + fn committed_icon_is_valid() { + // An app passes its own committed icon, for example `/assets/app-icon/.icns`. + let dir = tempfile::tempdir().expect("temporary directory"); + let path = dir.path().join("app.icns"); + let limits = Limits::default(); + std::fs::write(&path, pack(&[rgba(16), rgba(1024)], &limits).unwrap()).expect("write the icon"); + let elements = read_file(&path, &limits).unwrap(); + assert!(elements.iter().any(|e| &e.kind == b"ic10"), "expected a 1024 px image in {}", path.display()); + } +} diff --git a/crates/xtask/src/icon/ico.rs b/crates/xtask/src/icon/ico.rs new file mode 100644 index 0000000000..d45264b001 --- /dev/null +++ b/crates/xtask/src/icon/ico.rs @@ -0,0 +1,284 @@ +//! Windows `.ico` files of PNG images. +//! +//! The file starts with a 6-byte header (reserved 0, type 1 for an icon, the image count) and one +//! 16-byte directory entry per image (width, height, palette size 0, reserved 0, 1 plane, 32 bits per +//! pixel, the PNG's byte length and its offset from the start of the file), all little-endian. The +//! PNGs follow in the order of the entries. A side of 256 px is written as 0 in the one-byte width +//! and height. Each PNG must be 8-bit RGBA, the 32 bits per pixel that Windows reads from a PNG entry +//! ([ICO format, part 4](https://devblogs.microsoft.com/oldnewthing/20101022-00/?p=12473/)). + +use std::path::Path; + +use super::{Error, Limits, png_info, read_bounded, reserve, sorted_sizes}; + +/// The most images an ICO file holds: its image count is 16 bits. +pub const MAX_IMAGES: usize = u16::MAX as usize; + +/// The largest image side, in pixels. +pub const MAX_SIZE: u32 = 256; + +/// The header and one directory entry, in bytes. +const HEADER: u64 = 6; +const ENTRY: u64 = 16; + +/// An ICO file holding `pngs`: each square, 1 to 256 px, 8-bit RGBA and a different size from the +/// others. The entries are written in increasing size, whatever the order of `pngs`. +pub fn pack>(pngs: &[P], limits: &Limits) -> Result, Error> { + let sizes = sorted_sizes(pngs, limits, MAX_IMAGES, |info| { + if info.width > MAX_SIZE { + return Err(Error::UnsupportedSize { format: "ICO", size: info.width }); + } + if !info.is_rgba8() { + return Err(Error::InvalidPng(format!("ICO images must be 8-bit RGBA, got color type {} at {} bits", info.color_type, info.bit_depth))); + } + Ok(()) + })?; + let dir_end = HEADER + ENTRY * sizes.len() as u64; + let total = pngs.iter().fold(dir_end, |t, png| t.saturating_add(png.as_ref().len() as u64)); + let mut out = reserve(total, limits)?; + // `reserve` checked that the whole file, and so every length and offset, fits in a u32, and + // `sorted_sizes` that the count fits in a u16. + out.extend_from_slice(&0u16.to_le_bytes()); // reserved + out.extend_from_slice(&1u16.to_le_bytes()); // type: icon + out.extend_from_slice(&(sizes.len() as u16).to_le_bytes()); + let mut offset = dir_end; + for &(size, i) in &sizes { + let len = pngs[i].as_ref().len() as u64; + let dim = if size == MAX_SIZE { 0 } else { size as u8 }; + out.extend_from_slice(&[dim, dim, 0, 0]); // width, height, palette size, reserved + out.extend_from_slice(&1u16.to_le_bytes()); // color planes + out.extend_from_slice(&32u16.to_le_bytes()); // bits per pixel + out.extend_from_slice(&(len as u32).to_le_bytes()); + out.extend_from_slice(&(offset as u32).to_le_bytes()); + offset += len; + } + for &(_, i) in &sizes { + out.extend_from_slice(pngs[i].as_ref()); + } + Ok(out) +} + +/// One image of an ICO file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + /// The side in pixels, with a stored 0 read as 256. + pub size: u32, + /// The PNG. + pub png: Vec, +} + +/// The images of an ICO file of PNG entries, in directory order. +/// +/// The checks are the header (reserved 0, type 1, 1 to [`Limits::max_images`] images), the file +/// size against [`Limits::max_total_bytes`], and for each entry: a PNG of at most +/// [`Limits::max_png_bytes`], square dimensions, palette size 0, reserved 0, 1 plane and 32 bits per +/// pixel, as [`pack`] writes them, a size no other entry has, and an 8-bit RGBA PNG that +/// [`png_info`](super::png_info) accepts, of the size the entry states, lying wholly after the +/// directory and inside the file. The PNGs together hold at most [`Limits::max_total_bytes`]. +pub fn read(ico: &[u8], limits: &Limits) -> Result, Error> { + let bad = Error::InvalidIcon; + if ico.len() > limits.max_total_bytes { + return Err(Error::TooLarge(format!("the icon file holds {} bytes, more than {}", ico.len(), limits.max_total_bytes))); + } + let [0, 0, 1, 0, c0, c1, ..] = ico else { + return Err(bad("no ICO header (reserved 0, type 1)".into())); + }; + let count = usize::from(u16::from_le_bytes([*c0, *c1])); + if count == 0 { + return Err(bad("no images".into())); + } + if count > limits.max_images { + return Err(Error::TooManyImages { count, max: limits.max_images }); + } + let dir_end = 6 + 16 * count; + let dir = ico.get(6..dir_end).ok_or_else(|| bad(format!("the directory of {count} entries is truncated")))?; + let mut out = Vec::with_capacity(count); + let mut copied = 0usize; + for (n, e) in dir.as_chunks::<16>().0.iter().enumerate() { + let (w, h) = (e[0], e[1]); + if w != h { + return Err(bad(format!("entry {} is {w}x{h}, not square", n + 1))); + } + if e[2..8] != [0, 0, 1, 0, 32, 0] { + return Err(bad(format!("entry {} is not palette size 0, reserved 0, 1 plane and 32 bits per pixel", n + 1))); + } + let size = if w == 0 { MAX_SIZE } else { u32::from(w) }; + let len = u32::from_le_bytes([e[8], e[9], e[10], e[11]]) as usize; + let offset = u32::from_le_bytes([e[12], e[13], e[14], e[15]]) as usize; + if len > limits.max_png_bytes { + return Err(Error::TooLarge(format!("entry {} holds {len} bytes, more than {}", n + 1, limits.max_png_bytes))); + } + let png = offset + .checked_add(len) + .filter(|_| offset >= dir_end) + .and_then(|end| ico.get(offset..end)) + .ok_or_else(|| bad(format!("entry {} points outside the file", n + 1)))?; + let info = png_info(png)?; + if (info.width, info.height) != (size, size) { + return Err(bad(format!("entry {} says {size} px but its PNG is {}x{}", n + 1, info.width, info.height))); + } + if !info.is_rgba8() { + return Err(bad(format!("the PNG of entry {} is not 8-bit RGBA", n + 1))); + } + if out.iter().any(|e: &Entry| e.size == size) { + return Err(Error::DuplicateSize(size)); + } + // Entries can point at overlapping bytes, so the copies are counted against the limit. + copied = copied.saturating_add(len); + if copied > limits.max_total_bytes { + return Err(Error::TooLarge(format!("the entries hold more than {} bytes together", limits.max_total_bytes))); + } + out.push(Entry { size, png: png.to_vec() }); + } + Ok(out) +} + +/// [`read`] on the file at `path`, which is read only up to [`Limits::max_total_bytes`]. An app's +/// test of its committed icon passes the icon's path. +pub fn read_file(path: &Path, limits: &Limits) -> Result, Error> { + read(&read_bounded(path, limits.max_total_bytes)?, limits) +} + +#[cfg(test)] +mod tests { + use super::super::tests::{png_of, push_chunk, rgba}; + use super::*; + + fn u32_le(b: &[u8]) -> u32 { + u32::from_le_bytes(b.try_into().unwrap()) + } + + #[test] + fn packs_directory_and_payloads() { + let (a, b) = (rgba(16), rgba(256)); + let ico = pack(&[a.clone(), b.clone()], &Limits::default()).unwrap(); + // Header and entries, byte for byte from the documented layout. + let (la, lb) = ((a.len() as u32).to_le_bytes(), (b.len() as u32).to_le_bytes()); + let off_b = (38 + a.len() as u32).to_le_bytes(); + let mut want = vec![0, 0, 1, 0, 2, 0]; + want.extend_from_slice(&[16, 16, 0, 0, 1, 0, 32, 0]); + want.extend_from_slice(&la); + want.extend_from_slice(&[38, 0, 0, 0]); + want.extend_from_slice(&[0, 0, 0, 0, 1, 0, 32, 0]); // 256 px is stored as 0 + want.extend_from_slice(&lb); + want.extend_from_slice(&off_b); + assert_eq!(&ico[..38], &want[..]); + assert_eq!(u32_le(&ico[34..38]), 38 + a.len() as u32); + assert_eq!(&ico[38..38 + a.len()], &a[..]); + assert_eq!(&ico[38 + a.len()..], &b[..]); + } + + #[test] + fn writes_entries_in_increasing_size() { + let (a, b, c) = (rgba(48), rgba(16), rgba(32)); + let ico = pack(&[&a[..], &b[..], &c[..]], &Limits::default()).unwrap(); + let sizes: Vec = read(&ico, &Limits::default()).unwrap().iter().map(|e| e.size).collect(); + assert_eq!(sizes, [16, 32, 48]); + assert_eq!(ico, pack(&[b, c, a], &Limits::default()).unwrap()); + } + + #[test] + fn rejects_bad_input() { + let limits = Limits::default(); + assert_eq!(pack::>(&[], &limits), Err(Error::Empty)); + assert_eq!(pack(&[rgba(512)], &limits), Err(Error::UnsupportedSize { format: "ICO", size: 512 })); + assert!(matches!(pack(&[b"GIF89a".to_vec()], &limits), Err(Error::InvalidPng(_)))); + assert_eq!(pack(&[png_of(16, 32, 8, 6)], &limits), Err(Error::NotSquare { width: 16, height: 32 })); + assert_eq!(pack(&[rgba(16), rgba(32), rgba(16)], &limits), Err(Error::DuplicateSize(16))); + assert_eq!(pack(&[rgba(16), rgba(32)], &Limits { max_images: 1, ..limits }), Err(Error::TooManyImages { count: 2, max: 1 })); + assert!(matches!(pack(&[rgba(16)], &Limits { max_png_bytes: 10, ..limits }), Err(Error::TooLarge(_)))); + assert!(matches!(pack(&[rgba(16)], &Limits { max_total_bytes: 40, ..limits }), Err(Error::TooLarge(_)))); + } + + #[test] + fn rejects_a_png_that_is_not_rgba8() { + let limits = Limits::default(); + for (depth, color) in [(8, 2), (16, 6), (8, 3), (8, 0), (8, 4)] { + assert!(matches!(pack(&[png_of(16, 16, depth, color)], &limits), Err(Error::InvalidPng(m)) if m.contains("RGBA"))); + } + } + + #[test] + fn reads_what_it_packs() { + let pngs = [rgba(1), rgba(16), rgba(256)]; + let ico = pack(&pngs, &Limits::default()).unwrap(); + let entries = read(&ico, &Limits::default()).unwrap(); + let got: Vec<(u32, &[u8])> = entries.iter().map(|e| (e.size, &e.png[..])).collect(); + assert_eq!(got, [(1, &pngs[0][..]), (16, &pngs[1][..]), (256, &pngs[2][..])]); + } + + #[test] + fn read_rejects_bad_files() { + let limits = Limits::default(); + let ico = pack(&[rgba(16), rgba(32)], &limits).unwrap(); + assert!(matches!(read(b"GIF89a", &limits), Err(Error::InvalidIcon(_)))); + assert!(matches!(read(&ico[..30], &limits), Err(Error::InvalidIcon(_)))); + assert!(matches!(read(&ico[..ico.len() - 1], &limits), Err(Error::InvalidIcon(_)))); + let mut wrong_size = ico.clone(); + wrong_size[6] = 17; + wrong_size[7] = 17; + assert!(matches!(read(&wrong_size, &limits), Err(Error::InvalidIcon(m)) if m.contains("17 px"))); + let mut into_directory = ico.clone(); + into_directory[18..22].copy_from_slice(&6u32.to_le_bytes()); + assert!(matches!(read(&into_directory, &limits), Err(Error::InvalidIcon(_)))); + for (at, value) in [(8, 1), (9, 1), (10, 0), (12, 24)] { + let mut field = ico.clone(); + field[at] = value; + assert!(matches!(read(&field, &limits), Err(Error::InvalidIcon(m)) if m.contains("32 bits")), "accepted byte {at} = {value}"); + } + let mut gray = ico.clone(); + let png = png_of(16, 16, 8, 0); + gray.splice(38..38 + rgba(16).len(), png.iter().copied()); + let delta = png.len() as i64 - rgba(16).len() as i64; + gray[14..18].copy_from_slice(&(png.len() as u32).to_le_bytes()); + let off = (u32_le(&gray[34..38]) as i64 + delta) as u32; + gray[34..38].copy_from_slice(&off.to_le_bytes()); + assert!(matches!(read(&gray, &limits), Err(Error::InvalidIcon(m)) if m.contains("RGBA"))); + let mut huge = ico.clone(); + huge[14..18].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(matches!(read(&huge, &limits), Err(Error::TooLarge(_)))); + assert!(matches!(read(&huge, &Limits { max_png_bytes: usize::MAX, ..limits }), Err(Error::InvalidIcon(_)))); + assert_eq!(read(&ico, &Limits { max_images: 1, ..limits }), Err(Error::TooManyImages { count: 2, max: 1 })); + let small = Limits { max_png_bytes: rgba(32).len() - 1, ..limits }; + assert!(matches!(read(&ico, &small), Err(Error::TooLarge(m)) if m.contains("entry 2"))); + // Entry 2 made a second 16 px entry that points at entry 1's PNG. + let mut shared = ico.clone(); + shared[22..24].copy_from_slice(&[16, 16]); + shared.copy_within(14..22, 30); + assert_eq!(read(&shared, &limits), Err(Error::DuplicateSize(16))); + } + + #[test] + fn read_counts_overlapping_entries_against_the_limit() { + // A 32 px PNG that carries a whole 16 px PNG in an ancillary chunk, and a 16 px entry that + // points inside it. + let (inner, outer) = (rgba(16), rgba(32)); + let mut png = outer[..33].to_vec(); + push_chunk(&mut png, b"zzZz", &inner); + png.extend_from_slice(&outer[33..]); + let mut ico = vec![0, 0, 1, 0, 2, 0]; + for (size, len, offset) in [(16u8, inner.len(), 38 + 33 + 8), (32, png.len(), 38)] { + ico.extend_from_slice(&[size, size, 0, 0, 1, 0, 32, 0]); + ico.extend_from_slice(&(len as u32).to_le_bytes()); + ico.extend_from_slice(&(offset as u32).to_le_bytes()); + } + ico.extend_from_slice(&png); + let fits = Limits { max_total_bytes: ico.len(), ..Limits::default() }; + assert!(matches!(read(&ico, &fits), Err(Error::TooLarge(m)) if m.contains("together"))); + let sizes: Vec = read(&ico, &Limits::default()).unwrap().iter().map(|e| e.size).collect(); + assert_eq!(sizes, [16, 32]); + } + + #[test] + fn committed_icon_is_valid() { + // An app passes its own committed icon, for example `/assets/app-icon/.ico`. + let dir = tempfile::tempdir().expect("temporary directory"); + let path = dir.path().join("app.ico"); + let limits = Limits::default(); + let pngs = [16, 24, 32, 48, 64, 128, 256].map(rgba); + std::fs::write(&path, pack(&pngs, &limits).unwrap()).expect("write the icon"); + let entries = read_file(&path, &limits).unwrap(); + assert!(entries.len() >= 4, "expected several sizes in {}", path.display()); + assert!(matches!(read_file(&path, &Limits { max_total_bytes: 64, ..limits }), Err(Error::TooLarge(_)))); + } +} diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..19a9532a4e 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -12,6 +12,9 @@ //! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. +//! - [`icon`]: PNG images packed into a Windows `.ico` ([`icon::ico::pack`]) or a macOS `.icns` +//! ([`icon::icns::pack`]), with [`icon::png_size`] and readers for an app's test of its committed +//! icons. //! //! ```no_run //! use std::path::Path; @@ -35,6 +38,7 @@ //! } //! ``` +pub mod icon; #[cfg(feature = "lock")] pub mod lock; #[cfg(feature = "report")] From 6701acfcf1f13757f4485755722dc27d97fe57c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:03:39 -0800 Subject: [PATCH 04/33] craft-testkit: bound collection and use-path allocations and fix guard edge cases - fonts::collection counts the table directories from each face's numTables before reading any record, then adds the tables one face at a time, so oversized input returns OutputTooLarge without keeping a directory for every face. - fonts::rename_family keeps the rest of each renamed full name, so a family name stored inside that suffix is refused with ConflictingNameStorage. - The guards read `use<...>` as a capturing bound, not a declaration, and keep use paths of at most eight segments, so a long prefix shared by many names is not copied into each. - std_instant finds the modules of a file that a #[path] attribute names next to that file, separately from a plain load of the same file. - predefined_quit reports ::quit. - wgsl_float_literals ends line comments and counts lines at every WGSL line break, and skips digits inside Unicode identifiers. --- crates/testkit/README.md | 2 +- crates/testkit/src/fonts.rs | 59 ++++++--- crates/testkit/src/guards.rs | 233 +++++++++++++++++++++++---------- crates/testkit/tests/fonts.rs | 34 +++++ crates/testkit/tests/guards.rs | 68 ++++++++++ 5 files changed, 303 insertions(+), 93 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 1e1a254e9f..fd2c621ec7 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -6,7 +6,7 @@ Source-level platform regression guards and verification utilities for the Craft `craft-testkit` provides lightweight, non-panicking source guards that prevent applications in the Craft ecosystem from repeating platform defects that were previously diagnosed and resolved in peer applications: -1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::` and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. +1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::`, in the qualified form `::quit`, and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. 2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value, rounded to `f64`, exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. A literal that exceeds the maximum by less than `f64` precision rounds to the maximum and is not reported. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. `f32::MAX` can be written as the hex float `0x1.fffffep+127f`, which equals it, or as the decimal `3.4028234663852886e38`, which rounds to it. 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs index 04345b66a2..cfc3096a0c 100644 --- a/crates/testkit/src/fonts.rs +++ b/crates/testkit/src/fonts.rs @@ -143,24 +143,26 @@ pub fn rename_family(bytes: &[u8], from: &str, to: &str) -> Result, Font /// [`FontError::EmptyCollection`] for no faces, [`FontError::UnsupportedFace`] for a face that is /// itself a collection, [`FontError::MalformedFont`] for a face shorter than its table directory or /// with a table out of range, and [`FontError::OutputTooLarge`] when the collection would pass the -/// 4 GiB that its 32-bit offsets reach or cannot be allocated. +/// 4 GiB that its 32-bit offsets reach or cannot be allocated. The headers and table directories are +/// counted from each face's `numTables` before any table record is read, so faces whose directories +/// alone pass 4 GiB return [`FontError::OutputTooLarge`] even when a table record is out of range. pub fn collection(faces: &[&[u8]]) -> Result, FontError> { if faces.is_empty() { return Err(FontError::EmptyCollection); } - let directories = faces.iter().map(|face| directory(face)).collect::, _>>()?; let count = u32::try_from(faces.len()).map_err(|_| FontError::OutputTooLarge)?; - let size = collection_size(&directories)?; + let size = collection_size(faces)?; let mut out = Vec::new(); out.try_reserve_exact(size).map_err(|_| FontError::OutputTooLarge)?; out.extend_from_slice(b"ttcf"); out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); out.extend_from_slice(&count.to_be_bytes()); out.resize(SFNT_HEADER + faces.len() * 4, 0); - for (index, (face, tables)) in faces.iter().zip(&directories).enumerate() { + for (index, face) in faces.iter().enumerate() { + let tables = directory(face)?; let directory = offset32(out.len())?; put_u32(&mut out, SFNT_HEADER + index * 4, directory)?; - write_face(&mut out, face, tables)?; + write_face(&mut out, face, &tables)?; } Ok(out) } @@ -176,11 +178,7 @@ struct Table { /// Reads a standalone face's table directory, checking that every record and table lies in `face`. fn directory(face: &[u8]) -> Result, FontError> { - let version = bytes_at(face, 0, 4)?; - if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) { - return Err(FontError::UnsupportedFace); - } - let count = usize::from(u16_at(face, 4)?); + let count = table_count(face)?; bytes_at(face, 0, SFNT_HEADER + count * TABLE_RECORD)?; let mut tables = Vec::with_capacity(count); for index in 0..count { @@ -194,6 +192,15 @@ fn directory(face: &[u8]) -> Result, FontError> { Ok(tables) } +/// Reads a standalone face's sfnt version and `numTables`, without reading the table records. +fn table_count(face: &[u8]) -> Result { + let version = bytes_at(face, 0, 4)?; + if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) { + return Err(FontError::UnsupportedFace); + } + Ok(usize::from(u16_at(face, 4)?)) +} + /// Whether `table` shares bytes with the table directory or with another table of the face. fn shares_bytes(tables: &[Table], table: &Table) -> bool { let end = table.offset + table.length; @@ -203,18 +210,24 @@ fn shares_bytes(tables: &[Table], table: &Table) -> bool { } /// Bytes a collection of these faces takes, refused past what a 32-bit offset reaches. -fn collection_size(directories: &[Vec
]) -> Result { - let mut size = u64::try_from(SFNT_HEADER + directories.len() * 4).map_err(|_| FontError::OutputTooLarge)?; - for tables in directories { - let directory = SFNT_HEADER + tables.len() * TABLE_RECORD; - size = size.checked_add(u64::try_from(directory).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?; - for table in tables { - let padded = u64::try_from(table.length).map_err(|_| FontError::OutputTooLarge)?.div_ceil(4) * 4; - size = size.checked_add(padded).ok_or(FontError::OutputTooLarge)?; - } +/// +/// The headers and table directories are added up first, from each face's `numTables` alone, so that +/// input whose directories already pass the limit is refused before any table record is read. The +/// tables are then added one face at a time, and no face's directory is kept. +fn collection_size(faces: &[&[u8]]) -> Result { + let add = |size: u64, bytes: usize| -> Result { + let size = size.checked_add(u64::try_from(bytes).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?; + if size > u64::from(u32::MAX) { Err(FontError::OutputTooLarge) } else { Ok(size) } + }; + let mut size = add(0, SFNT_HEADER)?; + size = add(size, faces.len().checked_mul(4).ok_or(FontError::OutputTooLarge)?)?; + for face in faces { + size = add(size, SFNT_HEADER + table_count(face)? * TABLE_RECORD)?; } - if size > u64::from(u32::MAX) { - return Err(FontError::OutputTooLarge); + for face in faces { + for table in directory(face)? { + size = add(size, table.length.div_ceil(4).checked_mul(4).ok_or(FontError::OutputTooLarge)?)?; + } } usize::try_from(size).map_err(|_| FontError::OutputTooLarge) } @@ -342,6 +355,10 @@ fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Resul None => { let edit = renamed(string, face, from, to)?; let edited = edit.is_some(); + if let Some(edit) = &edit { + // The rest of a full name, after the family name, must keep its bytes. + kept.push(edit.range.end..string.range.end); + } edits.extend(edit); read.insert(key, edited); edited diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 77006af6f3..8a68eb0b72 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -114,6 +114,11 @@ impl AsFileSource for &(&str, String) { /// read as far as this depth, so hostile nesting cannot exhaust the stack. const MAX_NESTING: usize = 64; +/// The most segments of a `use` path that [`use_leaves`] keeps. The guards compare paths of at most +/// three segments, so a leaf with a longer path is left out, and a long prefix shared by many leaves +/// is not copied into each of them. +const MAX_USE_PATH: usize = 8; + /// The kind of a Rust token. Comments are dropped; string, character and number literals keep no text /// except string contents, which `cfg` predicates compare. #[derive(Debug, Clone, PartialEq, Eq)] @@ -344,6 +349,29 @@ fn then_path(toks: &[Token], i: usize, name: impl Fn(&str) -> bool) -> bool { && toks.get(i + 2).is_some_and(|t| matches!(&t.kind, Kind::Ident(s) if name(s))) } +/// Whether the path that ends at `toks[i]` starts right after the `<` of a qualified path, as in +/// `::quit`, rather than after the `<` of generic arguments (`Vec::new`, +/// `f::`). +fn opens_qualified_path(toks: &[Token], i: usize) -> bool { + let mut start = i; + while start >= 2 && toks[start - 1].is_punct(':') && toks[start - 2].is_punct(':') { + if start >= 3 && matches!(toks[start - 3].kind, Kind::Ident(_)) { + start -= 3; + } else { + start -= 2; + break; + } + } + start >= 1 + && toks[start - 1].is_punct('<') + && match start.checked_sub(2).map(|j| &toks[j].kind) { + None => true, + Some(Kind::Ident(s)) => KEYWORDS.contains(&s.as_str()), + Some(Kind::Punct(c)) => !matches!(*c, ':' | '>'), + Some(_) => false, + } +} + /// One name a `use` declaration brings into scope. #[derive(Debug)] struct UseLeaf { @@ -361,7 +389,8 @@ fn use_leaves(toks: &[Token]) -> Vec { let mut leaves = Vec::new(); let mut i = 0; while i < toks.len() { - if toks[i].is_ident("use") && !continues_a_path(toks, i) { + // `use<...>` is a precise capturing bound on `impl Trait`, not a `use` declaration. + if toks[i].is_ident("use") && !continues_a_path(toks, i) && !toks.get(i + 1).is_some_and(|t| t.is_punct('<')) { let start = i; let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len()); let mut pos = i + 1; @@ -389,24 +418,30 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, sta *pos += 2; continue; } - let mut path = prefix.clone(); - if name != "self" { - path.push(name.clone()); - } - let mut bound = path.last().cloned(); - if toks.get(*pos).is_some_and(|t| t.is_ident("as")) - && let Some(Kind::Ident(alias)) = toks.get(*pos + 1).map(|t| &t.kind) - { - bound = Some(alias.clone()); - *pos += 2; - } - if let Some(bound) = bound.filter(|b| b != "_") { - out.push(UseLeaf { path, name: Some(bound), line: tok.line, start }); + let length = prefix.len() + usize::from(name != "self"); + let alias = match (toks.get(*pos), toks.get(*pos + 1).map(|t| &t.kind)) { + (Some(t), Some(Kind::Ident(alias))) if t.is_ident("as") => { + *pos += 2; + Some(alias) + } + _ => None, + }; + if length <= MAX_USE_PATH { + let mut path = prefix.clone(); + if name != "self" { + path.push(name.clone()); + } + let bound = alias.cloned().or_else(|| path.last().cloned()); + if let Some(bound) = bound.filter(|b| b != "_") { + out.push(UseLeaf { path, name: Some(bound), line: tok.line, start }); + } } break; } Kind::Punct('*') => { - out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start }); + if prefix.len() <= MAX_USE_PATH { + out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start }); + } *pos += 1; break; } @@ -797,19 +832,20 @@ fn join_path(parent: &str, child: &str) -> String { /// The paths, normalized, where the module `decl` declared in the file at `parent` (normalized) can be. /// -/// The modules of `lib.rs`, `main.rs` and `mod.rs` are in the file's folder, and those of any other file -/// are in the folder named after its stem. Each inline module around the declaration adds a folder named +/// The modules of `lib.rs`, `main.rs` and `mod.rs`, and with `path_loaded`, of a file that a `#[path]` +/// attribute names, are in the file's folder, and those of any other file are in the folder named after +/// its stem. Each inline module around the declaration adds a folder named /// after it, or with a `path` attribute, moves to that path relative to the current folder (without the /// stem folder). The module is then `.rs` or `/mod.rs` there, or with a `path` attribute, that /// path relative to the current folder, again without the stem folder. -fn module_files(parent: &str, decl: &ModDecl) -> Vec { +fn module_files(parent: &str, decl: &ModDecl, path_loaded: bool) -> Vec { let (dir, file) = match parent.rsplit_once('/') { Some(("", file)) => ("/", file), Some(split) => split, None => ("", parent), }; let mut folder = dir.to_string(); - let mut stem = (!matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); + let mut stem = (!path_loaded && !matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); for inline in &decl.inline { if let Some(attr) = &inline.path_attribute { folder = join_path(&folder, attr); @@ -839,67 +875,88 @@ fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { for (i, path) in paths.iter().enumerate() { index.entry(path.as_str()).or_default().push(i); } - // The files each declaration names, in the order of `decls`. - let children: Vec)>> = decls - .iter() - .enumerate() - .map(|(parent, file_decls)| { - file_decls - .iter() - .map(|decl| { - let files = - module_files(&paths[parent], decl).iter().flat_map(|c| index.get(c.as_str()).into_iter().flatten().copied()).collect(); - (decl.native, files) - }) - .collect() + // rustc reads a file that a `#[path]` attribute names as if it were a `mod.rs`, so the modules it + // declares are in its own folder rather than its stem folder. Each file is therefore two nodes: node + // `2 * file` for the file loaded by a plain `mod name;` (or as a crate root), and node `2 * file + 1` + // for the file loaded through a `#[path]` attribute. Each node lists the nodes its declarations name, + // with whether the declaration is in a native-only item. + let edges: Vec> = (0..paths.len() * 2) + .map(|node| { + let (parent, path_loaded) = (node / 2, node % 2 == 1); + let mut targets = Vec::new(); + for decl in &decls[parent] { + let by_path = usize::from(decl.module.path_attribute.is_some()); + for candidate in module_files(&paths[parent], decl, path_loaded) { + for &j in index.get(candidate.as_str()).into_iter().flatten() { + targets.push((decl.native, 2 * j + by_path)); + } + } + } + targets }) .collect(); + // The nodes that are loaded: a file that no loaded node names is a crate root, loaded plainly, and a + // node is loaded when a loaded node names it. Every file starts out loaded plainly, and the set is + // narrowed until it stops changing, or after `MAX_MODULE_ROUNDS` rounds. + let mut loaded: Vec = (0..paths.len() * 2).map(|node| node % 2 == 0).collect(); + let mut named = vec![false; paths.len()]; + for _ in 0..MAX_MODULE_ROUNDS { + let mut reached = vec![false; paths.len() * 2]; + for (node, targets) in edges.iter().enumerate() { + if loaded[node] { + for &(_, target) in targets { + reached[target] = true; + } + } + } + named = (0..paths.len()).map(|j| reached[2 * j] || reached[2 * j + 1]).collect(); + let next: Vec = (0..paths.len() * 2).map(|node| reached[node] || (node % 2 == 0 && !named[node / 2])).collect(); + if next == loaded { + break; + } + loaded = next; + } + // Files the web build compiles: crate roots, and every file a declaration outside a native-only item // of such a file names. - let mut named = vec![false; paths.len()]; - for (_, files) in children.iter().flatten() { - for &j in files { - named[j] = true; - } - } - let mut web = vec![false; paths.len()]; - let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).collect(); - for &j in &queue { - web[j] = true; + let mut web = vec![false; paths.len() * 2]; + let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).map(|j| 2 * j).collect(); + for &node in &queue { + web[node] = true; } while let Some(parent) = queue.pop() { - for (_, files) in children[parent].iter().filter(|(is_native, _)| !is_native) { - for &j in files { - if !web[j] { - web[j] = true; - queue.push(j); - } + for &(_, target) in edges[parent].iter().filter(|(is_native, _)| !is_native) { + if !web[target] { + web[target] = true; + queue.push(target); } } } - // Files a native-only declaration names, and their descendants. - let mut native = vec![false; paths.len()]; - let mut mark = |files: &[usize], queue: &mut Vec| { - for &j in files { - if !native[j] { - native[j] = true; - queue.push(j); - } + // Files a native-only declaration of a loaded node names, and their descendants. + let mut native = vec![false; paths.len() * 2]; + let starts = edges.iter().enumerate().filter(|&(node, _)| loaded[node]).flat_map(|(_, targets)| targets.iter()); + for &(_, target) in starts.filter(|(is_native, _)| *is_native) { + if !native[target] { + native[target] = true; + queue.push(target); } - }; - for (_, files) in children.iter().flatten().filter(|(is_native, _)| *is_native) { - mark(files, &mut queue); } while let Some(parent) = queue.pop() { - for (_, files) in &children[parent] { - mark(files, &mut queue); + for &(_, target) in &edges[parent] { + if !native[target] { + native[target] = true; + queue.push(target); + } } } - native.iter().zip(&web).map(|(&n, &w)| n && !w).collect() + (0..paths.len()).map(|j| (native[2 * j] || native[2 * j + 1]) && !web[2 * j] && !web[2 * j + 1]).collect() } +/// The most rounds [`native_only_files`] spends narrowing the set of loaded files. +const MAX_MODULE_ROUNDS: usize = 16; + /// Add one finding for each line in `lines`, in line order, with the trimmed text of that line. fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeSet) { if lines.is_empty() { @@ -919,7 +976,8 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS /// Applications should route Quit through custom menu items or interceptors connected to `craft-quit`. /// /// The guard reads Rust tokens, so comments, strings and character literals are ignored, and whitespace -/// or line breaks around `::` do not hide a call. It also follows a `use` that renames muda's type +/// or line breaks around `::` do not hide a call. A qualified path such as `::quit` +/// is reported too. It also follows a `use` that renames muda's type /// (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's /// `PredefinedMenuItem` is not followed. Each finding names the line where the /// type's name starts, once per line, in line order. @@ -943,7 +1001,10 @@ where for (i, tok) in toks.iter().enumerate() { let Kind::Ident(name) = &tok.kind else { continue }; let named = name == "PredefinedMenuItem" || (aliases.contains(name) && !continues_a_path(&toks, i)); - if named && then_path(&toks, i + 1, |s| s == "quit" || s == "Quit") { + let quit = |at: usize| then_path(&toks, at, |s| s == "quit" || s == "Quit"); + // `::quit`, a qualified path to the same function. + let qualified = || toks.get(i + 1).is_some_and(|t| t.is_punct('>')) && quit(i + 2) && opens_qualified_path(&toks, i); + if named && (quit(i + 1) || qualified()) { lines.insert(tok.line); } } @@ -974,8 +1035,8 @@ where /// * **Module files**: a `mod name;` inside such an item makes the module's file native-only, and so are the /// files of the modules declared in it, when they are among `files`, unless a chain of declarations outside /// such items also reaches the file from a crate root (a file that no declaration names). The module's file is `name.rs` or -/// `name/mod.rs` next to `lib.rs`, `main.rs` or `mod.rs`, and in the folder named after any other file's -/// stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration +/// `name/mod.rs` next to `lib.rs`, `main.rs`, `mod.rs` or a file that a `#[path]` attribute names, and in +/// the folder named after any other file's stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration /// or on an enclosing inline module is followed. Paths are compared as text with `\` read as `/`, so the files must be named the same way /// (for example all from one `rust_sources` call), and a crate root other than `lib.rs` or `main.rs` /// (such as `src/bin/tool.rs`) is read as an ordinary module file. A declaration inside more than 64 inline @@ -1050,7 +1111,11 @@ where findings } -/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, keeping line breaks. +/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, and write each WGSL line break as +/// `\n`: line feed, vertical tab, form feed, carriage return, carriage return and line feed as one +/// break, next line (U+0085), line separator (U+2028) and paragraph separator (U+2029) +/// (). A line comment ends at any of them, and `str::lines` +/// then counts lines the way WGSL does. fn mask_wgsl_comments(code: &str) -> String { let chars: Vec = code.chars().collect(); let len = chars.len(); @@ -1061,10 +1126,15 @@ fn mask_wgsl_comments(code: &str) -> String { while i < len { let c = chars[i]; let next = chars.get(i + 1).copied(); - if c == '\n' { + let line_break = match c { + '\r' if next == Some('\n') => 2, + '\n' | '\u{000B}' | '\u{000C}' | '\r' | '\u{0085}' | '\u{2028}' | '\u{2029}' => 1, + _ => 0, + }; + if line_break > 0 { in_line = false; out.push('\n'); - i += 1; + i += line_break; } else if in_line { out.push(' '); i += 1; @@ -1183,7 +1253,9 @@ fn scan_wgsl_hex(code: &[u8], start: usize) -> (usize, usize, bool) { /// * **Which literals**: decimal floats (with a `.`, an exponent or an `f`/`h` suffix) and hexadecimal floats /// (`0x` with a `.` or a `p` exponent). Integer literals (`123`, `123u`, `0xFFi`, `0x1f`) are not floats and /// are not reported. A `-` in front is not part of the literal, so `-1e39` is reported as `1e39`. -/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. +/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. A `//` comment +/// ends at any WGSL line break, a lone carriage return included, and finding lines count every one of them. +/// * **Identifiers**: digits inside an identifier, `π1e39` included, are not a literal. pub fn wgsl_float_literals(wgsl: &str) -> Vec { wgsl_float_literals_in([("", wgsl)]) } @@ -1205,7 +1277,14 @@ where let mut i = 0; while i < code.len() { let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); - let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); + // Outside comments, a character that is not ASCII and not blankspace (U+200E, U+200F) is part of an + // identifier, as in `π1e39`. + let word_before = digit_or_dot + && i > 0 + && (code[i - 1].is_ascii_alphanumeric() + || code[i - 1] == b'_' + || code[i - 1] == b'.' + || (!code[i - 1].is_ascii() && !line[..i].ends_with(['\u{200E}', '\u{200F}']))); if !digit_or_dot || word_before { i += 1; continue; @@ -1392,3 +1471,15 @@ pub fn rust_sources_with_limits(dir: impl AsRef, limits: SourceLimits) -> files.sort_by(|a, b| a.0.cmp(&b.0)); Ok(files) } + +#[cfg(test)] +mod tests { + use super::{MAX_USE_PATH, lex_rust, use_leaves}; + + #[test] + fn use_leaves_keep_no_path_longer_than_the_limit() { + let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH)); + let paths: Vec> = use_leaves(&lex_rust(&source)).into_iter().map(|leaf| leaf.path).collect(); + assert_eq!(paths, vec![vec!["a"; MAX_USE_PATH], vec!["std", "time", "Instant"], vec!["std", "time"]]); + } +} diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/fonts.rs index 6ff688c7fa..56e20b79ac 100644 --- a/crates/testkit/tests/fonts.rs +++ b/crates/testkit/tests/fonts.rs @@ -298,6 +298,16 @@ fn rename_keeps_a_style_sharing_the_full_name_suffix() { assert_eq!(strings(&out), vec![win(1, TO), win(2, "Bold"), win(4, "Sysfont Sans3 Bold")]); } +#[test] +fn rename_rejects_a_family_name_in_the_full_name_suffix() { + // The full name "A A" is stored once, and the family name (ID 1) is its last "A". Renaming the + // family would change the full name's suffix " A". + let records = + [Rec { platform: 3, encoding: 1, name_id: 4, offset: 0, length: 6 }, Rec { platform: 3, encoding: 1, name_id: 1, offset: 4, length: 2 }]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &utf16("A A")))]); + assert_eq!(rename_family(&font, "A", "B"), Err(FontError::ConflictingNameStorage)); +} + #[test] fn rename_updates_name_checksum() { let font = family_face(&[win(1, FROM), win(2, "Regular")]); @@ -580,3 +590,27 @@ fn collection_rejects_offset_overflow() { let faces = vec![&big[..]; 4096]; assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); } + +#[test] +fn collection_rejects_directories_past_the_offset_limit() { + // 65,536 references to one face with 4,096 empty tables: the table directories alone take more + // than 4 GiB. The function refuses without keeping a directory for every face. + let tables: Vec<(&[u8; 4], Vec)> = (0..4096).map(|_| (b"zzzz", Vec::new())).collect(); + let many = face(&tables); + let faces = vec![&many[..]; 65536]; + assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); +} + +#[test] +fn collection_counts_directories_before_reading_records() { + // The same number of directories, each with every table record out of range. The size limit is + // found from the faces' table counts before any table record is read. + let mut directory = vec![0u8; 12 + 16 * 4096]; + set32(&mut directory, 0, 0x0001_0000); + set16(&mut directory, 4, 4096); + for index in 0..4096 { + set32(&mut directory, 12 + 16 * index + 8, u32::MAX); + } + let faces = vec![&directory[..]; 65536]; + assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); +} diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 169fdd5734..e568422645 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -412,6 +412,21 @@ fn menu() { assert!(predefined_quit([("src/menu.rs", other_crate)]).is_empty()); } +#[test] +fn predefined_quit_reports_a_qualified_path() { + let source = r#" +use muda::PredefinedMenuItem as Item; +fn menu() { + let a = ::quit(None); + let b = < PredefinedMenuItem >::quit(None); + let c = ::quit(None); + let d = Vec::::quit(None); + let e = Wrapper::quit(None); +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 5, 6]); +} + #[test] fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() { let source = r#" @@ -566,6 +581,12 @@ use std::time::{ assert_eq!(findings[0].text, "Instant"); } +#[test] +fn std_instant_reads_a_use_after_a_precise_capturing_bound() { + let source = "fn clock() -> impl Fn() + use<> {\n use std::{time::Instant};\n || { let _ = Instant::now(); }\n}\n"; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![2]); +} + #[test] fn std_instant_does_not_count_brace_character_literals_as_braces() { let source = r#" @@ -601,6 +622,15 @@ fn deeply_nested_use_groups_and_cfg_predicates_do_not_exhaust_the_stack() { assert_eq!(lines(&std_instant([("src/shallow.rs", shallow)])), vec![1]); } +#[test] +fn a_long_use_path_shared_by_many_names_is_read_without_copying_it_to_each() { + // 10,000 path segments shared by 10,000 names, followed by a `use` the guard reports. + let names: Vec = (0..10_000).map(|n| format!("x{n}")).collect(); + let source = format!("use {}{{{}}};\nuse std::time::Instant;\n", "a::".repeat(10_000), names.join(", ")); + assert_eq!(lines(&std_instant([("src/wide.rs", source.as_str())])), vec![2]); + assert!(predefined_quit([("src/wide.rs", source.as_str())]).is_empty()); +} + fn finding_paths(findings: &[Finding]) -> Vec<&str> { findings.iter().map(|f| f.path.as_str()).collect() } @@ -733,6 +763,28 @@ mod platform { assert_eq!(finding_paths(&std_instant(files)), vec!["src/a/native.rs", "src/a/native/clock.rs"]); } +#[test] +fn std_instant_finds_the_modules_of_a_path_attribute_file_next_to_it() { + let lib = r#" +#[cfg(not(target_arch = "wasm32"))] +#[path = "platform/native.rs"] +mod native; +"#; + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib), ("src/platform/native.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/web.rs", clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/web.rs"]); +} + +#[test] +fn std_instant_resolves_a_file_loaded_both_plainly_and_by_path_attribute_once_for_each() { + // `platform.rs` is a web module, and a native-only `#[path]` declaration loads it again. Its + // `mod clock;` is `src/platform/clock.rs` for the first and `src/clock.rs` for the second. + let lib = "mod platform;\n#[cfg(unix)]\n#[path = \"platform.rs\"]\nmod native;\n"; + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib), ("src/platform.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/clock.rs", clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/platform/clock.rs"]); +} + #[test] fn std_instant_checks_module_files_declared_deeper_than_its_nesting_limit() { let lib = format!("{}#[cfg(unix)]\nmod deep;\n{}", "mod m {\n".repeat(70), "}\n".repeat(70)); @@ -807,6 +859,22 @@ fn wgsl_half_floats_use_the_f16_range() { assert_eq!(findings[0].text, "70000.0"); } +#[test] +fn wgsl_line_comments_end_and_lines_count_at_every_line_break() { + let shader = "// note\rconst A: f32 = 4e38;\r\nconst B: f32 = 5e38;\n// x\u{2028}const C: f32 = 6e38;\u{2029}const D: f32 = 7e38;\u{000B}// y\u{0085}const E: f32 = 8e38;\u{000C}const F: f32 = 9e38;"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![2, 3, 5, 6, 8, 9]); + assert_eq!(findings[0].text, "4e38"); +} + +#[test] +fn wgsl_digits_inside_unicode_identifiers_are_not_literals() { + let shader = "const π1e39 = 1.0;\nconst é2e40: f32 = 2.0;\nconst A: f32 =\u{200E}1e39;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![3]); + assert_eq!(findings[0].text, "1e39"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn test_rust_sources_filtering() { From a01bfbd6de1a407ba70be794248473b209f26a32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:52:25 -0800 Subject: [PATCH 05/33] craft-testkit: add the mcp feature, an MCP stdio test client with deadlines and line limits McpChild::spawn(path, args, env) starts an MCP server with an environment list for the child only; McpChild::connect uses any reader and writer. initialize(version), request, call_tool, list_tools, notify, take_notifications and close(), which returns the exit status and whether the child had to be stopped. Every wait has a deadline and every stdout line a length limit, both in McpLimits with documented defaults (64 MiB, 30 s, 60 s for initialize, 2 s close grace). A deadline, an over-long line, a stdout line that is not JSON-RPC 2.0 or a malformed reply closes the connection and stops the child; an error reply returns its code, message and data and leaves the connection usable. The child's pings get an empty result and its other requests error -32601. stderr goes to the null device unless a bounded tail is asked for. The cases of craft-ai-integrations' child_tests.rs are moved in under their own names; tests that start a real child run in a harness = false target that re-runs itself as the server. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 16 + crates/testkit/README.md | 62 ++ crates/testkit/src/lib.rs | 6 + crates/testkit/src/mcp.rs | 878 ++++++++++++++++++++++++ crates/testkit/tests/mcp.rs | 435 ++++++++++++ crates/testkit/tests/mcp_child.rs | 17 + crates/testkit/tests/mcp_child/child.rs | 160 +++++ 8 files changed, 1577 insertions(+) create mode 100644 crates/testkit/src/mcp.rs create mode 100644 crates/testkit/tests/mcp.rs create mode 100644 crates/testkit/tests/mcp_child.rs create mode 100644 crates/testkit/tests/mcp_child/child.rs diff --git a/Cargo.lock b/Cargo.lock index fab3c89a3d..5ec7cc7b14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2576,6 +2576,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "serde_json", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..7819ddd0ed 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -8,7 +8,23 @@ repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" publish = false +[features] +# `mcp::McpChild`: an MCP stdio test client. +mcp = ["dep:serde_json"] + [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +serde_json = { workspace = true, optional = true } + +[[test]] +name = "mcp" +required-features = ["mcp"] + +[[test]] +name = "mcp_child" +harness = false +required-features = ["mcp"] + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index ff159f4da1..2143dc5b11 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,68 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`, under any name. The parts of a path may be split by whitespace, comments or line breaks. Other crates' `Instant` (such as `web_time::Instant` or `tokio::time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`; code before that attribute or after its item on the same line is still checked. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. +## MCP test client: `mcp` + +The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The module is built on every target except `wasm32`, and it opens no network connection. + +`McpChild::spawn(path, args, env)` starts an MCP server program with its stdin and stdout piped. The variables in `env` are set for the child only; the test process's environment is not changed. `McpChild::connect(reader, writer, limits)` talks to a server that runs in the test process. Each message is one line of JSON-RPC 2.0, as the [MCP stdio transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) describes. + +| Call | What it does | +|---|---| +| `initialize(version)` | Sends `initialize` with `version` (`mcp::PROTOCOL_VERSION` is `2025-06-18`), waits for the reply, then sends `notifications/initialized`. A reply with another version returns `UnsupportedVersion` and closes the connection. | +| `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. | +| `call_tool(name, args)`, `call_tool_within(.., timeout)` | Sends `tools/call` and returns the tool result unchanged, `content` and `isError` included. | +| `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. | +| `notify(method, params)` | Sends a notification, which has no id and gets no reply. | +| `take_notifications()` | Returns the notifications kept so far without waiting. | +| `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. | + +While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error, close the connection and stop the child; later calls return `Closed`. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics. + +`McpLimits` holds the limits. These defaults are the crate's own values: + +| Field | Default | Range | +|---|---|---| +| `max_line_bytes` | 64 MiB, for one stdout line and for the whole `list_tools` result | at least 1 | +| `request_timeout` | 30 s | more than zero, at most 1 hour | +| `initialize_timeout` | 60 s | more than zero, at most 1 hour | +| `close_grace` | 2 s | at most 1 hour | +| `max_pages` | 64 | at least 1 | +| `max_notifications` | 0 (notifications are not kept); the oldest is dropped when the queue is full | at most 4096 | +| `stderr_tail_bytes` | 0 (stderr goes to the null device); otherwise the last bytes written are kept | at most 16 MiB | + +`McpLimits::timeouts_from_var(name)` sets both deadlines from a variable that holds a whole number of seconds from 1 to 3600; `mcp::TIMEOUT_VAR` (`CRAFT_TEST_MCP_TIMEOUT_SECS`) is the default name. Any other value returns an error. + +```rust +use craft_testkit::mcp::{McpChild, PROTOCOL_VERSION}; + +let mut mcp = McpChild::spawn(env!("CARGO_BIN_EXE_my-cli"), ["mcp"], [("MYCRAFT_CONFIG_DIR", dir.path())])?; +mcp.initialize(PROTOCOL_VERSION)?; +let result = mcp.call_tool("doc.new", serde_json::json!({}))?; +assert_eq!(result["isError"], false); +assert!(mcp.close()?.status.is_some_and(|s| s.success())); +``` + +The tests that start a real child are in `tests/mcp_child.rs`, a target with `harness = false`: the child is that test program, and the standard harness writes its own lines on stdout. Both test targets build to nothing on `wasm32`. + +### Origin + +| Module | Source repository | Path | Revision | +|---|---|---|---| +| `mcp` | storytold/craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs` (`Conn`, `request`, `call_tool`, `MAX_LINE`, deadlines) and the 14 tests of `child_tests.rs`, written again here | `e8b31cb0` | +| `mcp` | storytold/vectorcraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | `460d2119` | +| `mcp` | storytold/photocraft | `apps/photocraft-cli/tests/it/cli.rs` (`mcp_recv`) | `58d11d91` | + +### Migration + +| Consumer | Helper | State | +|---|---|---| +| VectorCraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | Not switched | +| PhotoCraft | `apps/photocraft-cli/tests/it/cli.rs` | Not switched | +| CADCraft, DeckCraft, DesignCraft, EffectCraft | the MCP helpers in their CLI tests | Not switched | +| FigCraft, FilmCraft, GridCraft, LightCraft, PdfCraft, SoundCraft | the MCP helpers in their CLI tests | Not switched | +| craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs`, production code | Kept as it is | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..2697566098 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,10 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! With the `mcp` feature, on targets other than `wasm32`, `mcp::McpChild` runs an MCP server as a +//! child process and talks to it over stdin and stdout, with a deadline on every wait and a length +//! limit on every line it reads. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -26,6 +30,8 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))] +pub mod mcp; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs new file mode 100644 index 0000000000..eedf52c694 --- /dev/null +++ b/crates/testkit/src/mcp.rs @@ -0,0 +1,878 @@ +//! A test client for an MCP server that runs as a child process and exchanges JSON-RPC 2.0 +//! messages, one per line, on the child's stdin and stdout. +//! +//! [`McpChild::spawn`] starts the program with an environment list for the child only; +//! [`McpChild::connect`] uses any reader and writer, for a server that runs in the test process. +//! Every wait has a deadline and every line read from the child has a length limit, both set in +//! [`McpLimits`]. A child that does not answer makes the call return [`McpError::Deadline`]; the +//! call does not hang. +//! +//! After a deadline, a protocol error, an over-long line or the end of the child's output, the +//! connection is closed: the child is stopped and reaped, and later calls return +//! [`McpError::Closed`]. A JSON-RPC error reply returns [`McpError::Rpc`] and the connection stays +//! usable. A tool result with `isError: true` is a successful reply and is returned unchanged. + +use std::collections::VecDeque; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::process::{Child, ChildStderr, Command, ExitStatus, Stdio}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, TryRecvError, TrySendError, sync_channel}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use serde_json::{Map, Value, json}; + +/// The MCP revision the Craft applications' servers speak today. +pub const PROTOCOL_VERSION: &str = "2025-06-18"; +/// The default name of the variable read by [`McpLimits::timeouts_from_var`]. +pub const TIMEOUT_VAR: &str = "CRAFT_TEST_MCP_TIMEOUT_SECS"; +/// The longest deadline or close grace period [`McpLimits`] accepts. +pub const MAX_TIMEOUT: Duration = Duration::from_secs(3600); +/// The most notifications [`McpLimits::max_notifications`] may keep. +pub const MAX_NOTIFICATIONS: usize = 4096; +/// The most bytes of stderr [`McpLimits::stderr_tail_bytes`] may keep. +pub const MAX_STDERR_TAIL: usize = 16 << 20; + +/// Parsed messages the reader thread holds before the client takes them. When the queue is full, +/// the reader thread waits, and so does a child writing more. +const READ_QUEUE: usize = 4; +/// Lines waiting for the writer thread. A full queue means the child stopped reading its input. +const WRITE_QUEUE: usize = 64; +/// How often [`McpChild::close`] checks whether the child has exited. +const EXIT_POLL: Duration = Duration::from_millis(10); +/// Bytes of an unreadable stdout line quoted in a protocol error. +const PREVIEW: usize = 80; +/// The JSON-RPC error code for a method the client does not offer. +const METHOD_NOT_FOUND: i64 = -32601; + +/// Limits and deadlines of one connection. [`McpChild::spawn`] and [`McpChild::connect`] return +/// [`McpError::Setup`] for a value out of range. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct McpLimits { + /// The longest stdout line read, without its newline, and the most bytes of JSON + /// [`McpChild::list_tools`] returns in all. Default 64 MiB; must be at least 1. + pub max_line_bytes: usize, + /// How long [`McpChild::request`], [`McpChild::call_tool`] and each page of + /// [`McpChild::list_tools`] wait for the reply. Default 30 s; from 1 ns to [`MAX_TIMEOUT`]. + pub request_timeout: Duration, + /// How long [`McpChild::initialize`] waits. Default 60 s; from 1 ns to [`MAX_TIMEOUT`]. + pub initialize_timeout: Duration, + /// How long [`McpChild::close`] waits for the child to exit after closing its stdin before it + /// stops the child. Default 2 s; at most [`MAX_TIMEOUT`]. + pub close_grace: Duration, + /// The most pages [`McpChild::list_tools`] reads. Default 64; must be at least 1. + pub max_pages: usize, + /// The most notifications kept for [`McpChild::take_notifications`]; when the queue is full, + /// the oldest is dropped. Default 0, which keeps none; at most [`MAX_NOTIFICATIONS`]. + pub max_notifications: usize, + /// The most bytes of the child's stderr kept, the last ones written. Default 0, which sends + /// stderr to the null device; at most [`MAX_STDERR_TAIL`]. Not used by [`McpChild::connect`]. + pub stderr_tail_bytes: usize, +} + +impl Default for McpLimits { + fn default() -> Self { + Self { + max_line_bytes: 64 << 20, + request_timeout: Duration::from_secs(30), + initialize_timeout: Duration::from_secs(60), + close_grace: Duration::from_secs(2), + max_pages: 64, + max_notifications: 0, + stderr_tail_bytes: 0, + } + } +} + +impl McpLimits { + /// Sets [`McpLimits::request_timeout`] and [`McpLimits::initialize_timeout`] from the variable + /// `name` ([`TIMEOUT_VAR`] by default), a whole number of seconds from 1 to 3600. An unset + /// variable leaves the limits unchanged; any other value, and a name that is empty or holds `=` + /// or NUL, returns [`McpError::Setup`]. + pub fn timeouts_from_var(mut self, name: &str) -> Result { + if name.is_empty() || name.contains(['=', '\0']) { + return Err(McpError::Setup(format!("{name:?} is not a variable name"))); + } + let Some(value) = std::env::var_os(name) else { return Ok(self) }; + let timeout = parse_timeout_secs(name, &value)?; + self.request_timeout = timeout; + self.initialize_timeout = timeout; + Ok(self) + } + + fn validate(&self) -> Result<(), McpError> { + if self.max_line_bytes == 0 { + return Err(McpError::Setup("max_line_bytes must be at least 1".into())); + } + check_timeout("request_timeout", self.request_timeout)?; + check_timeout("initialize_timeout", self.initialize_timeout)?; + if self.close_grace > MAX_TIMEOUT { + return Err(McpError::Setup(format!("close_grace must be at most {MAX_TIMEOUT:?}"))); + } + if self.max_pages == 0 { + return Err(McpError::Setup("max_pages must be at least 1".into())); + } + if self.max_notifications > MAX_NOTIFICATIONS { + return Err(McpError::Setup(format!("max_notifications must be at most {MAX_NOTIFICATIONS}"))); + } + if self.stderr_tail_bytes > MAX_STDERR_TAIL { + return Err(McpError::Setup(format!("stderr_tail_bytes must be at most {MAX_STDERR_TAIL}"))); + } + Ok(()) + } +} + +fn check_timeout(what: &str, timeout: Duration) -> Result<(), McpError> { + if timeout.is_zero() || timeout > MAX_TIMEOUT { + return Err(McpError::Setup(format!("{what} must be more than zero and at most {MAX_TIMEOUT:?}"))); + } + Ok(()) +} + +fn parse_timeout_secs(name: &str, value: &OsStr) -> Result { + let bad = || McpError::Setup(format!("{name} must be a whole number of seconds from 1 to {}, not {value:?}", MAX_TIMEOUT.as_secs())); + let text = value.to_str().ok_or_else(bad)?; + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return Err(bad()); + } + let secs: u64 = text.parse().map_err(|_| bad())?; + if secs == 0 || secs > MAX_TIMEOUT.as_secs() { + return Err(bad()); + } + Ok(Duration::from_secs(secs)) +} + +/// Why a call failed. +#[derive(Debug)] +#[non_exhaustive] +pub enum McpError { + /// A limit, a timeout, an environment pair or a variable is not valid. Nothing was started. + Setup(String), + /// The program could not be started. + Spawn { + /// The program as given to [`McpChild::spawn`]. + program: OsString, + /// The error from the operating system. + source: io::Error, + }, + /// Reading from, writing to or waiting for the child failed. + Io { + /// What failed, such as "writing to the child". + what: &'static str, + /// The underlying error. + source: io::Error, + }, + /// The reply to `method` did not arrive within `after`. + Deadline { + /// The method of the request. + method: String, + /// The deadline that passed. + after: Duration, + }, + /// The child wrote a stdout line longer than `limit` bytes. + LineTooLong { + /// [`McpLimits::max_line_bytes`]. + limit: usize, + }, + /// The child closed its stdout. + Ended, + /// The child wrote something on stdout that is not a JSON-RPC 2.0 message, or a reply that + /// does not hold exactly one of `result` and `error`. + Protocol(String), + /// The child answered `method` with a JSON-RPC error. The connection stays usable. + Rpc { + /// The method of the request. + method: String, + /// The error's `code`. + code: i64, + /// The error's `message`. + message: String, + /// The error's `data`, when present. + data: Option, + }, + /// The child answered `initialize` with a protocol version other than the one asked for. + UnsupportedVersion { + /// The version sent in `initialize`. + requested: String, + /// The version in the child's reply. + returned: String, + }, + /// [`McpChild::list_tools`] read [`McpLimits::max_pages`] pages and the list went on. + TooManyPages { + /// [`McpLimits::max_pages`]. + limit: usize, + }, + /// The tools [`McpChild::list_tools`] read add up to more than `limit` bytes of JSON. + ToolListTooLarge { + /// [`McpLimits::max_line_bytes`]. + limit: usize, + }, + /// An earlier failure closed the connection; this is its message. + Closed(String), +} + +impl fmt::Display for McpError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Setup(why) => write!(f, "invalid MCP test setup: {why}"), + Self::Spawn { program, source } => write!(f, "could not start {}: {source}", program.to_string_lossy()), + Self::Io { what, source } => write!(f, "{what} failed: {source}"), + Self::Deadline { method, after } => write!(f, "the child did not answer `{method}` within {after:?}"), + Self::LineTooLong { limit } => write!(f, "the child wrote a line longer than {limit} bytes"), + Self::Ended => write!(f, "the child closed its output"), + Self::Protocol(why) => write!(f, "MCP protocol error: {why}"), + Self::Rpc { method, code, message, .. } => write!(f, "`{method}` returned error {code}: {message}"), + Self::UnsupportedVersion { requested, returned } => { + write!(f, "asked for MCP version {requested}, and the child answered with {returned}") + } + Self::TooManyPages { limit } => write!(f, "the tool list did not end within {limit} pages"), + Self::ToolListTooLarge { limit } => write!(f, "the tool list is larger than {limit} bytes"), + Self::Closed(why) => write!(f, "the MCP connection is closed: {why}"), + } + } +} + +impl std::error::Error for McpError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Spawn { source, .. } | Self::Io { source, .. } => Some(source), + _ => None, + } + } +} + +/// How [`McpChild::close`] ended the child. +#[derive(Debug)] +pub struct CloseOutcome { + /// The child's exit status; `None` for a connection made with [`McpChild::connect`]. + pub status: Option, + /// The child was stopped because it did not exit within [`McpLimits::close_grace`], or an + /// earlier failure stopped it. + pub forced: bool, + /// The last [`McpLimits::stderr_tail_bytes`] bytes the child wrote on stderr. + pub stderr: Vec, +} + +/// What the reader and writer threads hand to the client. +enum Incoming { + Message(Value), + TooLong, + Ended, + Invalid(String), + ReadFailed(io::Error), + WriteFailed(io::Error), +} + +enum LineError { + TooLong, + Io(io::Error), +} + +/// Reads one line of at most `cap` bytes, without its newline. `Ok(None)` at the end of the +/// stream. A line is rejected as soon as it passes `cap`, without waiting for its newline, and at +/// most `cap` bytes of it are kept. +fn read_line_capped(r: &mut impl BufRead, cap: usize) -> Result>, LineError> { + let mut line = Vec::new(); + loop { + let buf = match r.fill_buf() { + Ok(buf) => buf, + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) => return Err(LineError::Io(e)), + }; + if buf.is_empty() { + return Ok(if line.is_empty() { None } else { Some(line) }); + } + let (chunk, used, done) = match buf.iter().position(|b| *b == b'\n') { + Some(i) => (&buf[..i], i + 1, true), + None => (buf, buf.len(), false), + }; + if line.len().saturating_add(chunk.len()) > cap { + return Err(LineError::TooLong); + } + line.extend_from_slice(chunk); + r.consume(used); + if done { + return Ok(Some(line)); + } + } +} + +/// Parses one stdout line as a JSON-RPC 2.0 message object. +fn parse_line(line: &[u8]) -> Incoming { + let preview = || String::from_utf8_lossy(&line[..line.len().min(PREVIEW)]).into_owned(); + match serde_json::from_slice::(line) { + Ok(v) if v.get("jsonrpc").and_then(Value::as_str) == Some("2.0") => Incoming::Message(v), + Ok(_) => Incoming::Invalid(format!("a stdout line is not a JSON-RPC 2.0 message: {}", preview())), + Err(e) => Incoming::Invalid(format!("a stdout line is not JSON ({e}): {}", preview())), + } +} + +fn start_thread(name: &str, f: impl FnOnce() + Send + 'static) -> Result<(), McpError> { + std::thread::Builder::new().name(name.into()).spawn(f).map(drop).map_err(|source| McpError::Io { what: "starting a client thread", source }) +} + +/// The last bytes of the child's stderr, kept by a thread that reads it until it ends. +struct StderrTail { + bytes: Arc>>, + done: Receiver<()>, +} + +impl StderrTail { + fn start(mut stderr: ChildStderr, keep: usize) -> Result { + let bytes: Arc>> = Arc::default(); + let (done_tx, done) = sync_channel(1); + let store = Arc::clone(&bytes); + start_thread("craft-testkit-mcp-stderr", move || { + let mut chunk = [0u8; 8192]; + loop { + let n = match stderr.read(&mut chunk) { + Ok(0) => break, + Ok(n) => n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(_) => break, + }; + let mut tail = store.lock().unwrap_or_else(PoisonError::into_inner); + tail.extend(chunk.iter().take(n)); + let extra = tail.len().saturating_sub(keep); + tail.drain(..extra); + } + let _ = done_tx.try_send(()); + })?; + Ok(Self { bytes, done }) + } + + fn copy(&self) -> Vec { + self.bytes.lock().unwrap_or_else(PoisonError::into_inner).iter().copied().collect() + } +} + +/// A connection to an MCP server. Dropping it stops and reaps a child that is still running. +pub struct McpChild { + /// Lines for the writer thread. `None` once the connection is closed, which ends the thread + /// and closes the child's stdin. + writer: Option>>, + rx: Receiver, + next_id: u64, + limits: McpLimits, + child: Option, + /// The exit status of a child already reaped, and whether it was stopped. + exit: Option<(ExitStatus, bool)>, + closed: Option, + notifications: VecDeque, + stderr: Option, +} + +impl fmt::Debug for McpChild { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("McpChild").field("next_id", &self.next_id).field("closed", &self.closed).finish_non_exhaustive() + } +} + +impl McpChild { + /// Starts `path` with `args` and, for the child only, the variables in `env`, with + /// [`McpLimits::default`]. The process's own environment is not changed. + pub fn spawn( + path: impl AsRef, + args: impl IntoIterator>, + env: impl IntoIterator, + ) -> Result + where + K: AsRef, + V: AsRef, + { + Self::spawn_with_limits(path, args, env, McpLimits::default()) + } + + /// [`McpChild::spawn`] with the given limits. A variable name that is empty or holds `=` or + /// NUL, or a value that holds NUL, returns [`McpError::Setup`]. + pub fn spawn_with_limits( + path: impl AsRef, + args: impl IntoIterator>, + env: impl IntoIterator, + limits: McpLimits, + ) -> Result + where + K: AsRef, + V: AsRef, + { + limits.validate()?; + let program = path.as_ref(); + let mut cmd = Command::new(program); + cmd.args(args); + for (key, value) in env { + let (key, value) = (key.as_ref(), value.as_ref()); + let key_bytes = key.as_encoded_bytes(); + if key_bytes.is_empty() || key_bytes.contains(&b'=') || key_bytes.contains(&0) { + return Err(McpError::Setup(format!("{key:?} is not a variable name"))); + } + if value.as_encoded_bytes().contains(&0) { + return Err(McpError::Setup(format!("the value of {key:?} holds NUL"))); + } + cmd.env(key, value); + } + cmd.stdin(Stdio::piped()).stdout(Stdio::piped()); + cmd.stderr(if limits.stderr_tail_bytes == 0 { Stdio::null() } else { Stdio::piped() }); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + /// Starts a console program without opening a console window. + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + cmd.creation_flags(CREATE_NO_WINDOW); + } + let mut child = cmd.spawn().map_err(|source| McpError::Spawn { program: program.to_os_string(), source })?; + let started = Self::attach(&mut child, limits); + match started { + Ok(mut conn) => { + conn.child = Some(child); + Ok(conn) + } + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + Err(e) + } + } + } + + fn attach(child: &mut Child, limits: McpLimits) -> Result { + let missing = || McpError::Io { what: "connecting to the child", source: io::Error::other("a pipe was not opened") }; + let stdin = child.stdin.take().ok_or_else(missing)?; + let stdout = child.stdout.take().ok_or_else(missing)?; + let stderr = match child.stderr.take() { + Some(stderr) if limits.stderr_tail_bytes > 0 => Some(StderrTail::start(stderr, limits.stderr_tail_bytes)?), + _ => None, + }; + let mut conn = Self::start(stdout, stdin, limits)?; + conn.stderr = stderr; + Ok(conn) + } + + /// Connects to a server that reads `writer` and writes `reader`, such as one running on a + /// thread of the test. [`McpLimits::stderr_tail_bytes`] is not used. + pub fn connect(reader: impl Read + Send + 'static, writer: impl Write + Send + 'static, limits: McpLimits) -> Result { + limits.validate()?; + Self::start(reader, writer, limits) + } + + fn start(reader: impl Read + Send + 'static, writer: impl Write + Send + 'static, limits: McpLimits) -> Result { + let (tx, rx) = sync_channel(READ_QUEUE); + let write_failed = tx.clone(); + let cap = limits.max_line_bytes; + start_thread("craft-testkit-mcp-read", move || { + let mut r = BufReader::new(reader); + loop { + let incoming = match read_line_capped(&mut r, cap) { + Ok(None) => Incoming::Ended, + Ok(Some(line)) if line.iter().all(u8::is_ascii_whitespace) => continue, + Ok(Some(line)) => parse_line(&line), + Err(LineError::TooLong) => Incoming::TooLong, + Err(LineError::Io(e)) => Incoming::ReadFailed(e), + }; + let last = !matches!(incoming, Incoming::Message(_)); + if tx.send(incoming).is_err() || last { + return; + } + } + })?; + let (wtx, wrx) = sync_channel::>(WRITE_QUEUE); + start_thread("craft-testkit-mcp-write", move || { + let mut w = writer; + for line in wrx { + if let Err(e) = w.write_all(&line).and_then(|()| w.flush()) { + // Wakes a request waiting for its reply. Ends when the client is dropped. + let _ = write_failed.send(Incoming::WriteFailed(e)); + return; + } + } + })?; + Ok(Self { writer: Some(wtx), rx, next_id: 1, limits, child: None, exit: None, closed: None, notifications: VecDeque::new(), stderr: None }) + } + + /// The message of the failure that closed the connection, or `None` while it is usable. + pub fn closed(&self) -> Option<&str> { + self.closed.as_deref() + } + + /// The last bytes the child wrote on stderr so far (see [`McpLimits::stderr_tail_bytes`]). + pub fn stderr_tail(&self) -> Vec { + self.stderr.as_ref().map(StderrTail::copy).unwrap_or_default() + } + + /// Sends `initialize` with `version` (for example [`PROTOCOL_VERSION`]), empty capabilities and + /// this crate's client info, waits up to [`McpLimits::initialize_timeout`] for the reply, then + /// sends `notifications/initialized`. Returns the reply's result. A reply with another protocol + /// version returns [`McpError::UnsupportedVersion`] and closes the connection. + pub fn initialize(&mut self, version: &str) -> Result { + let params = json!({ + "protocolVersion": version, + "capabilities": {}, + "clientInfo": {"name": env!("CARGO_PKG_NAME"), "version": env!("CARGO_PKG_VERSION")}, + }); + let result = self.request_within("initialize", params, self.limits.initialize_timeout)?; + let returned = match result.get("protocolVersion").and_then(Value::as_str) { + Some(returned) => returned.to_string(), + None => return Err(self.fail(McpError::Protocol("the `initialize` result has no `protocolVersion`".into()))), + }; + if returned != version { + return Err(self.fail(McpError::UnsupportedVersion { requested: version.to_string(), returned })); + } + self.notify("notifications/initialized", Value::Null)?; + Ok(result) + } + + /// Sends a notification: a message without an id, to which the child sends no reply. + /// `Value::Null` params are left out of the message. + pub fn notify(&mut self, method: &str, params: Value) -> Result<(), McpError> { + self.check_open()?; + self.send(&Value::Object(message(method, params))) + } + + /// Sends a request and waits up to [`McpLimits::request_timeout`] for the reply with its id. + /// Returns the reply's `result`. `Value::Null` params are left out of the message. + pub fn request(&mut self, method: &str, params: Value) -> Result { + self.request_within(method, params, self.limits.request_timeout) + } + + /// [`McpChild::request`] with its own deadline, from 1 ns to [`MAX_TIMEOUT`]. + /// + /// While it waits, it answers the child's `ping` requests with an empty result and its other + /// requests with error -32601, keeps notifications for [`McpChild::take_notifications`], and + /// skips replies with another id. None of these extend the deadline. + pub fn request_within(&mut self, method: &str, params: Value, timeout: Duration) -> Result { + self.check_open()?; + check_timeout("the request deadline", timeout)?; + let deadline = Instant::now().checked_add(timeout).ok_or_else(|| McpError::Setup("the request deadline is too far away".into()))?; + let id = self.next_id; + self.next_id = self.next_id.saturating_add(1); + let mut msg = message(method, params); + msg.insert("id".into(), json!(id)); + self.send(&Value::Object(msg))?; + loop { + let left = deadline.checked_duration_since(Instant::now()).filter(|left| !left.is_zero()); + let Some(left) = left else { + return Err(self.fail(McpError::Deadline { method: method.to_string(), after: timeout })); + }; + let incoming = match self.rx.recv_timeout(left) { + Ok(incoming) => incoming, + Err(RecvTimeoutError::Timeout) => return Err(self.fail(McpError::Deadline { method: method.to_string(), after: timeout })), + Err(RecvTimeoutError::Disconnected) => return Err(self.fail(McpError::Ended)), + }; + let v = self.receive(incoming)?; + if let Some(reply) = self.route(v, Some(id))? { + return self.reply(method, reply); + } + } + } + + /// Calls the tool `name` with `arguments` (`tools/call`) and returns its result unchanged, + /// `content` and `isError` included. + pub fn call_tool(&mut self, name: &str, arguments: Value) -> Result { + self.request("tools/call", json!({"name": name, "arguments": arguments})) + } + + /// [`McpChild::call_tool`] with its own deadline. + pub fn call_tool_within(&mut self, name: &str, arguments: Value, timeout: Duration) -> Result { + self.request_within("tools/call", json!({"name": name, "arguments": arguments}), timeout) + } + + /// Every tool the child lists, following `nextCursor` for at most [`McpLimits::max_pages`] + /// pages. The entries are returned as the child sent them. A list that goes on past the + /// limit returns [`McpError::TooManyPages`]. Tools whose JSON text adds up to more than + /// [`McpLimits::max_line_bytes`] return [`McpError::ToolListTooLarge`]. + pub fn list_tools(&mut self) -> Result, McpError> { + let mut tools = Vec::new(); + let mut total = 0usize; + let mut cursor: Option = None; + for _ in 0..self.limits.max_pages { + let params = cursor.take().map_or(Value::Null, |c| json!({"cursor": c})); + let mut page = self.request("tools/list", params)?; + let Some(list) = page.get_mut("tools").and_then(Value::as_array_mut) else { + return Err(self.fail(McpError::Protocol("a `tools/list` result has no `tools` array".into()))); + }; + let mut count = ByteCount(0); + for tool in list.iter() { + // Writing into a counter does not fail. + let _ = serde_json::to_writer(&mut count, tool); + } + total = total.saturating_add(count.0); + if total > self.limits.max_line_bytes { + return Err(McpError::ToolListTooLarge { limit: self.limits.max_line_bytes }); + } + tools.append(list); + cursor = match page.get("nextCursor") { + None | Some(Value::Null) => return Ok(tools), + Some(Value::String(next)) => Some(next.clone()), + Some(_) => return Err(self.fail(McpError::Protocol("a `tools/list` result has a `nextCursor` that is not a string".into()))), + }; + } + Err(McpError::TooManyPages { limit: self.limits.max_pages }) + } + + /// Takes the messages already received without waiting: answers the child's requests as + /// [`McpChild::request_within`] does and returns the notifications kept so far, oldest first. + /// One call handles at most as many messages as the reader thread queues, so a child that + /// keeps writing does not keep it running. A failure found here closes the connection, and + /// [`McpChild::closed`] reports it. + pub fn take_notifications(&mut self) -> Vec { + // The reader's queue and the writer thread's failure message. + for _ in 0..=READ_QUEUE { + if self.closed.is_some() { + break; + } + let incoming = match self.rx.try_recv() { + Ok(incoming) => incoming, + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + self.fail(McpError::Ended); + break; + } + }; + let Ok(v) = self.receive(incoming) else { break }; + if self.route(v, None).is_err() { + break; + } + } + self.notifications.drain(..).collect() + } + + /// Closes the child's stdin, waits up to [`McpLimits::close_grace`] for it to exit, then stops + /// it, and returns its exit status. For a connection made with [`McpChild::connect`], it ends + /// the writer thread, which drops the writer once the lines already queued are written, and + /// returns no status without waiting for that thread. A writer blocked on a server that has + /// stopped reading stays with the thread until the server drops its reading end. + pub fn close(mut self) -> Result { + self.writer = None; + let grace = self.limits.close_grace; + let (status, forced) = match self.child.take() { + Some(mut child) => match reap(&mut child, grace) { + Ok((status, forced)) => (Some(status), forced), + Err(source) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(McpError::Io { what: "waiting for the child", source }); + } + }, + None => self.exit.map_or((None, false), |(status, forced)| (Some(status), forced)), + }; + let stderr = match &self.stderr { + Some(tail) => { + let _ = tail.done.recv_timeout(grace); + tail.copy() + } + None => Vec::new(), + }; + Ok(CloseOutcome { status, forced, stderr }) + } + + fn check_open(&self) -> Result<(), McpError> { + match &self.closed { + Some(why) => Err(McpError::Closed(why.clone())), + None => Ok(()), + } + } + + fn send(&mut self, msg: &Value) -> Result<(), McpError> { + let Some(writer) = &self.writer else { return Err(McpError::Closed(self.closed.clone().unwrap_or_default())) }; + let mut line = serde_json::to_vec(msg).map_err(|e| McpError::Protocol(format!("a message could not be written as JSON: {e}")))?; + line.push(b'\n'); + // Never waits for room: a child that stops reading fills the queue, and the connection is + // closed then. + match writer.try_send(line) { + Ok(()) => Ok(()), + Err(TrySendError::Full(_)) => Err(self.fail(McpError::Io { + what: "writing to the child", + source: io::Error::new(io::ErrorKind::WouldBlock, "the child stopped reading its input"), + })), + Err(TrySendError::Disconnected(_)) => { + Err(self.fail(McpError::Io { what: "writing to the child", source: io::Error::from(io::ErrorKind::BrokenPipe) })) + } + } + } + + /// Turns what the threads handed over into a message, or closes the connection. + fn receive(&mut self, incoming: Incoming) -> Result { + Err(self.fail(match incoming { + Incoming::Message(v) => return Ok(v), + Incoming::TooLong => McpError::LineTooLong { limit: self.limits.max_line_bytes }, + Incoming::Ended => McpError::Ended, + Incoming::Invalid(why) => McpError::Protocol(why), + Incoming::ReadFailed(source) => McpError::Io { what: "reading from the child", source }, + Incoming::WriteFailed(source) => McpError::Io { what: "writing to the child", source }, + })) + } + + /// Handles one message: answers a request from the child, keeps a notification, skips a reply + /// to another id, and returns the reply to `waiting`. + fn route(&mut self, v: Value, waiting: Option) -> Result, McpError> { + match (v.get("method"), v.get("id")) { + (Some(Value::String(method)), Some(id)) => { + let reply = if method == "ping" { + json!({"jsonrpc": "2.0", "id": id, "result": {}}) + } else { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": METHOD_NOT_FOUND, "message": "Method not found"}}) + }; + self.send(&reply)?; + Ok(None) + } + (Some(Value::String(_)), None) => { + if self.limits.max_notifications > 0 { + if self.notifications.len() >= self.limits.max_notifications { + self.notifications.pop_front(); + } + self.notifications.push_back(v); + } + Ok(None) + } + (Some(_), _) => Err(self.fail(McpError::Protocol("a message has a `method` that is not a string".into()))), + (None, Some(id)) => Ok((waiting.is_some() && id.as_u64() == waiting).then_some(v)), + (None, None) => Err(self.fail(McpError::Protocol("a message has neither `method` nor `id`".into()))), + } + } + + /// The result of the reply to `method`, or its error. + fn reply(&mut self, method: &str, mut v: Value) -> Result { + let malformed = || McpError::Protocol(format!("the reply to `{method}` does not hold exactly one of `result` and a valid `error`")); + let Some(obj) = v.as_object_mut() else { return Err(self.fail(malformed())) }; + match (obj.remove("result"), obj.remove("error")) { + (Some(result), None) => Ok(result), + (None, Some(Value::Object(mut error))) => { + let code = error.get("code").and_then(Value::as_i64); + let message = error.get("message").and_then(Value::as_str).map(str::to_string); + match (code, message) { + (Some(code), Some(message)) => Err(McpError::Rpc { method: method.to_string(), code, message, data: error.remove("data") }), + _ => Err(self.fail(malformed())), + } + } + _ => Err(self.fail(malformed())), + } + } + + /// Closes the connection with `err`: ends the writer, which closes the child's stdin, and stops + /// and reaps the child. A child that closed its output or input gets + /// [`McpLimits::close_grace`] to exit first. + fn fail(&mut self, err: McpError) -> McpError { + if self.closed.is_none() { + self.closed = Some(err.to_string()); + } + self.writer = None; + if let Some(mut child) = self.child.take() { + let grace = match err { + McpError::Ended | McpError::Io { .. } => self.limits.close_grace, + _ => Duration::ZERO, + }; + match reap(&mut child, grace) { + Ok(exit) => self.exit = Some(exit), + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + } + } + } + err + } +} + +impl Drop for McpChild { + fn drop(&mut self) { + self.writer = None; + if let Some(mut child) = self.child.take() { + let _ = child.kill(); + let _ = child.wait(); + } + } +} + +/// A writer that only counts the bytes written to it. +struct ByteCount(usize); + +impl Write for ByteCount { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0 = self.0.saturating_add(buf.len()); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// A JSON-RPC 2.0 message for `method`; `Value::Null` params are left out. +fn message(method: &str, params: Value) -> Map { + let mut msg = Map::new(); + msg.insert("jsonrpc".into(), json!("2.0")); + msg.insert("method".into(), json!(method)); + if !params.is_null() { + msg.insert("params".into(), params); + } + msg +} + +/// Waits up to `grace` for the child to exit, then stops it. Returns its status and whether it +/// was stopped. +fn reap(child: &mut Child, grace: Duration) -> io::Result<(ExitStatus, bool)> { + let deadline = Instant::now().checked_add(grace); + loop { + if let Some(status) = child.try_wait()? { + return Ok((status, false)); + } + let left = deadline.and_then(|d| d.checked_duration_since(Instant::now())).filter(|left| !left.is_zero()); + let Some(left) = left else { break }; + std::thread::sleep(left.min(EXIT_POLL)); + } + match child.kill() { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::InvalidInput => {} + Err(e) => return Err(e), + } + Ok((child.wait()?, true)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn capped_line_reader() { + let mut r = io::Cursor::new(b"abc\nabcdefgh\nxy".to_vec()); + assert_eq!(read_line_capped(&mut r, 4).ok(), Some(Some(b"abc".to_vec()))); + assert!(matches!(read_line_capped(&mut r, 4), Err(LineError::TooLong))); + let mut r = io::Cursor::new(b"xy".to_vec()); + assert_eq!(read_line_capped(&mut r, 4).ok(), Some(Some(b"xy".to_vec())), "a last line without a newline"); + assert_eq!(read_line_capped(&mut r, 4).ok(), Some(None)); + } + + #[test] + fn an_over_long_line_is_rejected_before_its_newline_arrives() { + // A reader that fails after the first bytes: a reader that waited for the newline would + // return the error instead. + struct Then(io::Cursor>); + impl Read for Then { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self.0.read(buf)? { + 0 => Err(io::Error::other("no newline yet")), + n => Ok(n), + } + } + } + let mut r = BufReader::new(Then(io::Cursor::new(vec![b'x'; 64]))); + assert!(matches!(read_line_capped(&mut r, 16), Err(LineError::TooLong))); + } + + #[test] + fn timeout_variable_values() { + let parse = |v: &str| parse_timeout_secs(TIMEOUT_VAR, OsStr::new(v)).ok(); + assert_eq!(parse("5"), Some(Duration::from_secs(5))); + assert_eq!(parse("3600"), Some(MAX_TIMEOUT)); + for bad in ["", "0", "3601", "-1", "+5", " 5", "5s", "1.5", "99999999999999999999999"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn a_bad_timeout_variable_name_is_a_setup_error_not_a_panic() { + for name in ["", "A=B", "A\0B"] { + assert!(matches!(McpLimits::default().timeouts_from_var(name), Err(McpError::Setup(_))), "{name:?}"); + } + } +} diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs new file mode 100644 index 0000000000..5d730e85d3 --- /dev/null +++ b/crates/testkit/tests/mcp.rs @@ -0,0 +1,435 @@ +#![cfg(not(target_arch = "wasm32"))] + +use std::io::{BufRead, BufReader, Write}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use craft_testkit::mcp::{McpChild, McpError, McpLimits, PROTOCOL_VERSION}; +use serde_json::{Value, json}; + +/// An in-process MCP server: answers each line it reads with `reply(method, message)`; `None` +/// sends nothing. A reply from the client has the method `""`. Returns the client side. +fn fake_with(limits: McpLimits, reply: F) -> McpChild +where + F: Fn(&str, &Value) -> Option> + Send + 'static, +{ + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (server_r, client_w) = std::io::pipe().unwrap(); + std::thread::spawn(move || { + for line in BufReader::new(server_r).lines() { + let Ok(line) = line else { return }; + let Ok(req) = serde_json::from_str::(&line) else { + continue; + }; + let method = req["method"].as_str().unwrap_or("").to_string(); + let Some(out) = reply(&method, &req) else { + continue; + }; + for l in out { + if server_w.write_all(format!("{l}\n").as_bytes()).is_err() { + return; + } + } + } + }); + McpChild::connect(client_r, client_w, limits).unwrap() +} + +fn fake(reply: F) -> McpChild +where + F: Fn(&str, &Value) -> Option> + Send + 'static, +{ + fake_with(McpLimits::default(), reply) +} + +fn result(req: &Value, result: Value) -> String { + json!({"jsonrpc": "2.0", "id": req["id"], "result": result}).to_string() +} + +/// A deadline for replies that never come. +const SHORT: Duration = Duration::from_millis(200); +/// A deadline that a passing test does not reach. +const LONG: Duration = Duration::from_secs(30); + +#[test] +fn handshake_list_and_call() { + let initialized = Arc::new(AtomicBool::new(false)); + let seen = initialized.clone(); + let mut c = fake(move |m, req| match m { + "initialize" => Some(vec![result(req, json!({"protocolVersion": req["params"]["protocolVersion"]}))]), + "notifications/initialized" => { + assert!(req.get("id").is_none(), "a notification has no id"); + seen.store(true, Ordering::SeqCst); + None + } + // The list is sent only after `notifications/initialized`, which the client sends first. + "tools/list" if seen.load(Ordering::SeqCst) => Some(vec![result(req, json!({"tools": [{"name": "doc.new"}, {"no": "name"}]}))]), + "tools/call" => Some(vec![result(req, json!({"content": [{"type": "text", "text": req["params"]["name"]}]}))]), + _ => None, + }); + let init = c.initialize(PROTOCOL_VERSION).unwrap(); + assert_eq!(init["protocolVersion"], PROTOCOL_VERSION); + let tools = c.list_tools().unwrap(); + assert_eq!(tools.len(), 2, "the list is returned as the server sent it"); + assert!(initialized.load(Ordering::SeqCst)); + let r = c.call_tool_within("doc.new", json!({}), Duration::from_secs(5)).unwrap(); + assert_eq!(r["content"][0]["text"], "doc.new"); +} + +#[test] +fn pages_are_followed() { + let mut c = fake(|m, req| match m { + "tools/list" if req["params"]["cursor"].is_null() => Some(vec![result(req, json!({"tools": [{"name": "a"}], "nextCursor": "p2"}))]), + "tools/list" => Some(vec![result(req, json!({"tools": [{"name": "b"}]}))]), + _ => None, + }); + let names: Vec = c.list_tools().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect(); + assert_eq!(names, vec!["a", "b"]); +} + +#[test] +fn notifications_log_lines_and_stale_replies_are_skipped() { + // A log line on stdout is a protocol error (`non_json_stdout_is_protocol_error`); a + // notification and a stale reply are skipped. + let mut c = fake(|_, req| { + Some(vec![ + json!({"jsonrpc": "2.0", "method": "notifications/message", "params": {"level": "info", "data": "starting up"}}).to_string(), + json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {}}).to_string(), + json!({"jsonrpc": "2.0", "id": 999, "result": "stale"}).to_string(), + result(req, json!("mine")), + ]) + }); + assert_eq!(c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(), json!("mine")); +} + +#[test] +fn a_request_from_the_app_is_refused_and_the_reply_still_arrives() { + let refusal: Arc>> = Arc::default(); + let log = refusal.clone(); + let mut c = fake(move |m, req| match m { + "x" => Some(vec![json!({"jsonrpc": "2.0", "id": "srv-1", "method": "sampling/createMessage"}).to_string()]), + // The reply to `x` follows the client's answer to the server's request. + "" => { + *log.lock().unwrap() = Some(req.clone()); + Some(vec![json!({"jsonrpc": "2.0", "id": 1, "result": 1}).to_string()]) + } + _ => None, + }); + assert_eq!(c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(), json!(1)); + let refusal = refusal.lock().unwrap().clone().unwrap(); + assert_eq!(refusal["id"], "srv-1"); + assert_eq!(refusal["error"]["code"], -32601); + assert!(refusal.get("result").is_none()); +} + +#[test] +fn an_error_reply_is_an_err_and_the_connection_stays_usable() { + let mut c = fake(|m, req| match m { + "bad" => { + Some(vec![json!({"jsonrpc": "2.0", "id": req["id"], "error": {"code": -1, "message": "nope", "data": {"why": "test"}}}).to_string()]) + } + _ => Some(vec![result(req, json!(true))]), + }); + match c.request_within("bad", json!({}), Duration::from_secs(5)) { + Err(McpError::Rpc { method, code, message, data }) => { + assert_eq!((method.as_str(), code, message.as_str()), ("bad", -1, "nope")); + assert_eq!(data, Some(json!({"why": "test"}))); + } + other => panic!("{other:?}"), + } + assert!(c.closed().is_none()); + assert_eq!(c.request_within("ok", json!({}), Duration::from_secs(5)).unwrap(), json!(true)); +} + +#[test] +fn a_silent_app_times_out_and_the_connection_is_closed() { + let mut c = fake(|_, _| None); + let err = c.request_within("x", json!({}), Duration::from_millis(100)).unwrap_err(); + assert!(matches!(&err, McpError::Deadline { method, .. } if method == "x"), "{err}"); + assert!(c.closed().is_some()); + assert!(matches!(c.request_within("y", json!({}), Duration::from_secs(5)), Err(McpError::Closed(_)))); +} + +#[test] +fn an_app_that_exits_is_reported() { + let (client_r, server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + drop(server_w); + let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap(); + let err = c.request_within("x", json!({}), Duration::from_secs(5)).unwrap_err(); + assert!(matches!(err, McpError::Ended), "{err}"); + assert!(c.closed().is_some()); +} + +#[test] +fn a_missing_cli_is_an_error_not_a_panic() { + let program = std::env::temp_dir().join("no-such-craft-cli-for-tests"); + let err = McpChild::spawn(&program, ["mcp"], [("CRAFT_TESTKIT_UNUSED", "1")]).unwrap_err(); + assert!(matches!(&err, McpError::Spawn { program: p, .. } if p.as_os_str() == program.as_os_str()), "{err}"); + assert!(err.to_string().contains("could not start"), "{err}"); +} + +#[test] +fn a_tool_list_that_never_ends_is_an_error_not_a_partial_list() { + let mut c = fake(|m, req| match m { + "tools/list" => Some(vec![result(req, json!({"tools": [{"name": "a"}], "nextCursor": "more"}))]), + _ => None, + }); + let err = c.list_tools().unwrap_err(); + assert!(matches!(err, McpError::TooManyPages { limit: 64 }), "{err}"); +} + +#[test] +fn a_tool_list_larger_than_the_limit_is_an_error() { + // Each page fits in a line; the pages together do not. + let limits = McpLimits { max_line_bytes: 256, ..McpLimits::default() }; + let mut c = fake_with(limits, |m, req| match m { + "tools/list" => Some(vec![result(req, json!({"tools": [{"name": "x".repeat(100)}], "nextCursor": "more"}))]), + _ => None, + }); + let err = c.list_tools().unwrap_err(); + assert!(matches!(err, McpError::ToolListTooLarge { limit: 256 }), "{err}"); +} + +#[test] +fn an_app_that_stops_reading_times_out_instead_of_blocking_the_write() { + // The server side never reads, so the pipe fills and the write blocks the writer thread, not + // the request. + let (client_r, _server_w) = std::io::pipe().unwrap(); + let (server_r, client_w) = std::io::pipe().unwrap(); + let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap(); + let big = "x".repeat(4 << 20); + let err = c.call_tool_within("t", json!({"data": big}), Duration::from_millis(300)).unwrap_err(); + assert!(matches!(err, McpError::Deadline { .. }), "{err}"); + drop(server_r); +} + +#[test] +fn a_tools_changed_notification_is_remembered_once() { + let limits = McpLimits { max_notifications: 8, ..McpLimits::default() }; + let mut c = fake_with(limits, |m, req| match m { + "x" => Some(vec![json!({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}).to_string(), result(req, json!(1))]), + _ => None, + }); + assert!(c.take_notifications().is_empty()); + c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(); + let kept = c.take_notifications(); + assert_eq!(kept.len(), 1, "{kept:?}"); + assert_eq!(kept[0]["method"], "notifications/tools/list_changed"); + assert!(c.take_notifications().is_empty()); +} + +#[test] +fn notifications_are_kept_up_to_the_limit_newest_last() { + let limits = McpLimits { max_notifications: 2, ..McpLimits::default() }; + let mut c = fake_with(limits, |m, req| match m { + "x" => { + let mut out: Vec = + (0..5).map(|n| json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {"n": n}}).to_string()).collect(); + out.push(result(req, json!(1))); + Some(out) + } + _ => None, + }); + c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(); + let kept: Vec = c.take_notifications().iter().map(|n| n["params"]["n"].clone()).collect(); + assert_eq!(kept, vec![json!(3), json!(4)]); +} + +#[test] +fn take_notifications_returns_while_the_server_keeps_writing() { + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + std::thread::spawn(move || { + let note = format!("{}\n", json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {}})); + while server_w.write_all(note.as_bytes()).is_ok() {} + }); + let limits = McpLimits { max_notifications: 8, ..McpLimits::default() }; + let mut c = McpChild::connect(client_r, client_w, limits).unwrap(); + for _ in 0..3 { + assert!(c.take_notifications().len() <= 8); + } + assert!(c.closed().is_none()); +} + +#[test] +fn a_failed_write_ends_the_waiting_request_at_once() { + struct Broken; + impl std::io::Write for Broken { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::other("stdin closed")) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + // The app keeps stdout open but takes nothing on stdin. The deadline is an hour, so a write + // failure that did not end the request would show as a hung test. + let (client_r, _server_w) = std::io::pipe().unwrap(); + let mut c = McpChild::connect(client_r, Broken, McpLimits::default()).unwrap(); + let err = c.request_within("x", json!({}), Duration::from_secs(3600)).unwrap_err(); + assert!(matches!(&err, McpError::Io { what: "writing to the child", .. }), "{err}"); + assert!(err.to_string().contains("stdin closed"), "{err}"); + assert!(c.closed().is_some()); +} + +#[test] +fn an_app_ping_gets_an_empty_result_during_a_request_and_between_them() { + // `x` brings a ping before its reply and one after it. The second is read while `y` waits; + // the server answers `y` once both pings have their answers, with those answers. + #[derive(Default)] + struct State { + answers: Vec, + y: Option, + } + let state: Arc> = Arc::default(); + let mut c = fake(move |m, req| { + let mut s = state.lock().unwrap(); + match m { + "x" => Some(vec![ + json!({"jsonrpc": "2.0", "id": "p1", "method": "ping"}).to_string(), + result(req, json!(1)), + json!({"jsonrpc": "2.0", "id": "p2", "method": "ping"}).to_string(), + ]), + "y" => { + s.y = Some(req.clone()); + None + } + "" => { + s.answers.push(req.clone()); + None + } + _ => return None, + } + .or_else(|| { + let ready = s.answers.len() == 2; + let y = if ready { s.y.take() } else { None }?; + Some(vec![result(&y, json!(s.answers))]) + }) + }); + assert_eq!(c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(), json!(1)); + let answers = c.request_within("y", json!({}), Duration::from_secs(5)).unwrap(); + for id in ["p1", "p2"] { + let reply = answers.as_array().unwrap().iter().find(|v| v["id"] == id).unwrap_or_else(|| panic!("no reply to {id}: {answers}")); + assert_eq!(reply["result"], json!({}), "{reply}"); + assert!(reply.get("error").is_none()); + } +} + +#[test] +fn over_long_line_returns_error() { + let limits = McpLimits { max_line_bytes: 16, ..McpLimits::default() }; + // The line has no newline yet, and the server keeps its end open. + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + server_w.write_all(&[b'x'; 64]).unwrap(); + let mut c = McpChild::connect(client_r, client_w, limits).unwrap(); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::LineTooLong { limit: 16 }), "{err}"); + assert!(c.closed().is_some()); + drop(server_w); +} + +#[test] +fn wrong_id_does_not_satisfy_request() { + let mut c = fake(|_, req| { + let id = req["id"].as_u64().unwrap(); + Some(vec![ + json!({"jsonrpc": "2.0", "id": id + 1, "result": "other"}).to_string(), + json!({"jsonrpc": "2.0", "id": id.to_string(), "result": "string id"}).to_string(), + json!({"jsonrpc": "2.0", "id": null, "result": "null id"}).to_string(), + ]) + }); + let err = c.request_within("x", json!({}), SHORT).unwrap_err(); + assert!(matches!(err, McpError::Deadline { .. }), "{err}"); +} + +#[test] +fn a_flood_of_stale_replies_does_not_extend_the_deadline() { + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + std::thread::spawn(move || { + let stale = format!("{}\n", json!({"jsonrpc": "2.0", "id": 999, "result": "stale"})); + while server_w.write_all(stale.as_bytes()).is_ok() {} + }); + let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap(); + let err = c.request_within("x", json!({}), SHORT).unwrap_err(); + assert!(matches!(err, McpError::Deadline { .. }), "{err}"); +} + +#[test] +fn non_json_stdout_is_protocol_error() { + for line in ["starting up...", r#"{"id": 1, "result": 1}"#, "[]", "\u{fffd}\u{0}"] { + let line = line.to_string(); + let mut c = fake(move |_, _| Some(vec![line.clone()])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); + assert!(c.closed().is_some()); + } + // Bytes that are not UTF-8. + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + server_w.write_all(b"{\"jsonrpc\": \"2.0\", \"method\": \"\xff\"}\n").unwrap(); + let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap(); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); +} + +#[test] +fn a_malformed_reply_is_a_protocol_error() { + for reply in [json!({"result": 1, "error": {"code": 1, "message": "both"}}), json!({}), json!({"error": {"code": "x", "message": "m"}})] { + let mut c = fake(move |_, req| { + let mut msg = reply.clone(); + msg["jsonrpc"] = json!("2.0"); + msg["id"] = req["id"].clone(); + Some(vec![msg.to_string()]) + }); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); + assert!(c.closed().is_some()); + } +} + +#[test] +fn a_tool_error_result_is_returned_unchanged() { + let mut c = fake(|_, req| Some(vec![result(req, json!({"content": [{"type": "text", "text": "no document"}], "isError": true}))])); + let r = c.call_tool("doc.save", json!({})).unwrap(); + assert_eq!(r["isError"], true); + assert!(c.closed().is_none()); +} + +#[test] +fn a_different_protocol_version_is_an_error_and_closes() { + let mut c = fake(|m, req| match m { + "initialize" => Some(vec![result(req, json!({"protocolVersion": "2024-11-05"}))]), + _ => None, + }); + let err = c.initialize(PROTOCOL_VERSION).unwrap_err(); + assert!( + matches!(&err, McpError::UnsupportedVersion { requested, returned } if requested == PROTOCOL_VERSION && returned == "2024-11-05"), + "{err}" + ); + assert!(c.closed().is_some()); +} + +#[test] +fn invalid_limits_and_environment_are_setup_errors() { + let zero_line = McpLimits { max_line_bytes: 0, ..McpLimits::default() }; + let zero_deadline = McpLimits { request_timeout: Duration::ZERO, ..McpLimits::default() }; + let long_deadline = McpLimits { initialize_timeout: Duration::from_secs(3601), ..McpLimits::default() }; + let many_notes = McpLimits { max_notifications: 4097, ..McpLimits::default() }; + for limits in [zero_line, zero_deadline, long_deadline, many_notes] { + let (client_r, _server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + assert!(matches!(McpChild::connect(client_r, client_w, limits.clone()), Err(McpError::Setup(_))), "{limits:?}"); + } + let program = std::env::temp_dir().join("no-such-craft-cli-for-tests"); + for (key, value) in [("", "1"), ("A=B", "1"), ("A\0B", "1"), ("A", "1\0")] { + let err = McpChild::spawn(&program, ["mcp"], [(key, value)]).unwrap_err(); + assert!(matches!(err, McpError::Setup(_)), "{key:?}={value:?}: {err}"); + } + let mut c = fake(|_, _| None); + assert!(matches!(c.request_within("x", json!({}), Duration::ZERO), Err(McpError::Setup(_)))); + assert!(c.closed().is_none(), "a bad deadline does not close the connection"); +} diff --git a/crates/testkit/tests/mcp_child.rs b/crates/testkit/tests/mcp_child.rs new file mode 100644 index 0000000000..e44029d18a --- /dev/null +++ b/crates/testkit/tests/mcp_child.rs @@ -0,0 +1,17 @@ +//! `McpChild` against a real child process. The child is this test program, started again with +//! `CRAFT_TESTKIT_MCP_CHILD` naming the server it acts as. The target has `harness = false` +//! because the standard test harness writes its own lines on stdout, which an MCP child must not +//! do. `main` runs each test whose name contains every argument that does not start with `-`, and +//! `--list` lists them. On `wasm32`, where the `mcp` module is not built, `main` does nothing. + +#[cfg(not(target_arch = "wasm32"))] +#[path = "mcp_child/child.rs"] +mod child; + +#[cfg(not(target_arch = "wasm32"))] +fn main() -> std::process::ExitCode { + child::run() +} + +#[cfg(target_arch = "wasm32")] +fn main() {} diff --git a/crates/testkit/tests/mcp_child/child.rs b/crates/testkit/tests/mcp_child/child.rs new file mode 100644 index 0000000000..f172912acf --- /dev/null +++ b/crates/testkit/tests/mcp_child/child.rs @@ -0,0 +1,160 @@ +use std::io::{BufRead, Write}; +use std::process::ExitCode; +use std::time::Duration; + +use craft_testkit::mcp::{McpChild, McpError, McpLimits, PROTOCOL_VERSION}; +use serde_json::{Value, json}; + +/// The server the child acts as. +const CHILD_VAR: &str = "CRAFT_TESTKIT_MCP_CHILD"; +/// Text the `server` child returns from every tool call. +const ECHO_VAR: &str = "CRAFT_TESTKIT_MCP_ECHO"; +/// Bytes the `flood` child writes on stderr before each reply, more than a pipe holds. +const FLOOD: usize = 1 << 20; + +type Test = fn() -> Result<(), String>; + +const TESTS: &[(&str, Test)] = &[ + ("a_spawned_server_answers_and_closes_cleanly", a_spawned_server_answers_and_closes_cleanly), + ("silent_spawned_child_hits_deadline", silent_spawned_child_hits_deadline), + ("child_exits_before_initialize", child_exits_before_initialize), + ("stderr_flood_does_not_block", stderr_flood_does_not_block), + ("close_forces_and_reaps_unresponsive_child", close_forces_and_reaps_unresponsive_child), +]; + +pub fn run() -> ExitCode { + if let Some(mode) = std::env::var_os(CHILD_VAR) { + return serve(&mode.to_string_lossy()); + } + let args: Vec = std::env::args().skip(1).collect(); + let filters: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect(); + let chosen: Vec<&(&str, Test)> = TESTS.iter().filter(|(name, _)| filters.iter().all(|f| name.contains(f.as_str()))).collect(); + if args.iter().any(|a| a == "--list") { + for (name, _) in chosen { + println!("{name}: test"); + } + return ExitCode::SUCCESS; + } + println!("\nrunning {} tests", chosen.len()); + let mut failed = 0; + for (name, test) in &chosen { + match test() { + Ok(()) => println!("test {name} ... ok"), + Err(why) => { + failed += 1; + println!("test {name} ... FAILED\n {why}"); + } + } + } + println!("\ntest result: {}. {} passed; {failed} failed", if failed == 0 { "ok" } else { "FAILED" }, chosen.len() - failed); + if failed == 0 { ExitCode::SUCCESS } else { ExitCode::FAILURE } +} + +/// Runs as the child: `server` answers `initialize` with the version asked for and every tool call +/// with `ECHO_VAR`, and exits when its stdin closes; `flood` also writes `FLOOD` bytes and `END` on +/// stderr before each reply; `silent` reads and never answers; `stubborn` answers but does not +/// exit when its stdin closes; `exit` exits at once with code 3. +fn serve(mode: &str) -> ExitCode { + if mode == "exit" { + return ExitCode::from(3); + } + let stdin = std::io::stdin(); + let mut out = std::io::stdout(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + let Ok(req) = serde_json::from_str::(&line) else { continue }; + if mode == "silent" || req.get("id").is_none() { + continue; + } + let result = match req["method"].as_str() { + Some("initialize") => { + json!({"protocolVersion": req["params"]["protocolVersion"], "capabilities": {}, "serverInfo": {"name": "child", "version": "0"}}) + } + Some("tools/call") => { + let text = std::env::var(ECHO_VAR).unwrap_or_default(); + json!({"content": [{"type": "text", "text": text}], "isError": false}) + } + _ => json!(null), + }; + if mode == "flood" { + let mut err = std::io::stderr(); + if err.write_all(&vec![b'e'; FLOOD]).and_then(|()| err.write_all(b"END")).is_err() { + return ExitCode::FAILURE; + } + } + let reply = json!({"jsonrpc": "2.0", "id": req["id"], "result": result}); + if writeln!(out, "{reply}").and_then(|()| out.flush()).is_err() { + return ExitCode::FAILURE; + } + } + if mode == "stubborn" { + // Waits without a stdin to read until the parent stops it; ends on its own after ten + // minutes so a parent that fails to stop it leaves nothing running. + let (_keep, wait) = std::sync::mpsc::channel::<()>(); + let _ = wait.recv_timeout(Duration::from_secs(600)); + } + ExitCode::SUCCESS +} + +fn start(mode: &str, limits: McpLimits) -> Result { + let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; + McpChild::spawn_with_limits(exe, std::iter::empty::<&str>(), [(CHILD_VAR, mode), (ECHO_VAR, "hello from the child")], limits) + .map_err(|e| format!("spawn {mode}: {e}")) +} + +fn check(ok: bool, what: impl FnOnce() -> String) -> Result<(), String> { + if ok { Ok(()) } else { Err(what()) } +} + +fn a_spawned_server_answers_and_closes_cleanly() -> Result<(), String> { + let mut c = start("server", McpLimits::default())?; + let init = c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?; + check(init["serverInfo"]["name"] == "child", || format!("initialize: {init}"))?; + let r = c.call_tool("echo", json!({})).map_err(|e| e.to_string())?; + check(r["content"][0]["text"] == "hello from the child", || format!("the child did not get its variable: {r}"))?; + check(std::env::var_os(ECHO_VAR).is_none(), || "the test process's environment changed".into())?; + let out = c.close().map_err(|e| e.to_string())?; + check(!out.forced && out.status.is_some_and(|s| s.success()), || format!("close: {out:?}")) +} + +fn silent_spawned_child_hits_deadline() -> Result<(), String> { + let limits = McpLimits { initialize_timeout: Duration::from_millis(200), ..McpLimits::default() }; + let mut c = start("silent", limits)?; + let err = c.initialize(PROTOCOL_VERSION).err(); + check(matches!(err, Some(McpError::Deadline { .. })), || format!("initialize: {err:?}"))?; + check(c.closed().is_some(), || "the connection is still open".into())?; + let out = c.close().map_err(|e| e.to_string())?; + check(out.forced && out.status.is_some(), || format!("the silent child was not stopped: {out:?}")) +} + +fn child_exits_before_initialize() -> Result<(), String> { + let mut c = start("exit", McpLimits::default())?; + // The write of `initialize` and the end of stdout race; either one is reported. + let err = c.initialize(PROTOCOL_VERSION).err(); + check(matches!(err, Some(McpError::Ended | McpError::Io { .. })), || format!("initialize: {err:?}"))?; + let out = c.close().map_err(|e| e.to_string())?; + check(!out.forced && out.status.and_then(|s| s.code()) == Some(3), || format!("close: {out:?}")) +} + +fn stderr_flood_does_not_block() -> Result<(), String> { + let limits = McpLimits { + stderr_tail_bytes: 4096, + initialize_timeout: Duration::from_secs(20), + request_timeout: Duration::from_secs(20), + ..McpLimits::default() + }; + let mut c = start("flood", limits)?; + c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?; + c.call_tool("echo", json!({})).map_err(|e| e.to_string())?; + let out = c.close().map_err(|e| e.to_string())?; + check(!out.forced, || format!("close: {out:?}"))?; + check(out.stderr.len() == 4096 && out.stderr.ends_with(b"eeeEND"), || format!("kept {} bytes of stderr", out.stderr.len())) +} + +fn close_forces_and_reaps_unresponsive_child() -> Result<(), String> { + let limits = McpLimits { close_grace: Duration::from_millis(200), ..McpLimits::default() }; + let mut c = start("stubborn", limits)?; + c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?; + let out = c.close().map_err(|e| e.to_string())?; + check(out.forced && out.status.is_some_and(|s| !s.success()), || format!("close: {out:?}")) +} From 3b0d43204ee9b137d60c9922bb7a9c7e5bbdc537 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:17:14 -0800 Subject: [PATCH 06/33] craft-testkit: blank MCP stdout lines are protocol errors The MCP client no longer skips a blank or whitespace-only stdout line. The line is parsed like any other, so it ends the request with a protocol error and closes the connection instead of waiting for the deadline. --- crates/testkit/src/mcp.rs | 1 - crates/testkit/tests/mcp.rs | 16 ++++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index eedf52c694..400c072718 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -464,7 +464,6 @@ impl McpChild { loop { let incoming = match read_line_capped(&mut r, cap) { Ok(None) => Incoming::Ended, - Ok(Some(line)) if line.iter().all(u8::is_ascii_whitespace) => continue, Ok(Some(line)) => parse_line(&line), Err(LineError::TooLong) => Incoming::TooLong, Err(LineError::Io(e)) => Incoming::ReadFailed(e), diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs index 5d730e85d3..d56b891cf9 100644 --- a/crates/testkit/tests/mcp.rs +++ b/crates/testkit/tests/mcp.rs @@ -376,6 +376,22 @@ fn non_json_stdout_is_protocol_error() { assert!(matches!(err, McpError::Protocol(_)), "{err}"); } +#[test] +fn a_blank_stdout_line_is_protocol_error() { + // The fake ends each line with a newline, so these send "\n" and " \r\n". + for blank in ["", " \r"] { + let mut c = fake(move |_, req| Some(vec![blank.to_string(), result(req, json!(1))])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{blank:?}: {err}"); + assert!(c.closed().is_some()); + // Without a reply after it, the blank line still ends the request before its deadline. + let mut c = fake(move |_, _| Some(vec![blank.to_string()])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{blank:?}: {err}"); + assert!(c.closed().is_some()); + } +} + #[test] fn a_malformed_reply_is_a_protocol_error() { for reply in [json!({"result": 1, "error": {"code": 1, "message": "both"}}), json!({}), json!({"error": {"code": "x", "message": "m"}})] { From 3d0bace80f39fdf43e933b45089aa772db0dc0df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:24:01 -0800 Subject: [PATCH 07/33] craft-testkit: the spawn test compares the parent's variable with its value before the child starts --- crates/testkit/tests/mcp_child/child.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/testkit/tests/mcp_child/child.rs b/crates/testkit/tests/mcp_child/child.rs index f172912acf..254488c3e7 100644 --- a/crates/testkit/tests/mcp_child/child.rs +++ b/crates/testkit/tests/mcp_child/child.rs @@ -107,12 +107,13 @@ fn check(ok: bool, what: impl FnOnce() -> String) -> Result<(), String> { } fn a_spawned_server_answers_and_closes_cleanly() -> Result<(), String> { + let before = std::env::var_os(ECHO_VAR); let mut c = start("server", McpLimits::default())?; let init = c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?; check(init["serverInfo"]["name"] == "child", || format!("initialize: {init}"))?; let r = c.call_tool("echo", json!({})).map_err(|e| e.to_string())?; check(r["content"][0]["text"] == "hello from the child", || format!("the child did not get its variable: {r}"))?; - check(std::env::var_os(ECHO_VAR).is_none(), || "the test process's environment changed".into())?; + check(std::env::var_os(ECHO_VAR) == before, || "the test process's environment changed".into())?; let out = c.close().map_err(|e| e.to_string())?; check(!out.forced && out.status.is_some_and(|s| s.success()), || format!("close: {out:?}")) } From 958ced53eb355e9236c7af292a7b306f8a0199c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 20:13:36 -0800 Subject: [PATCH 08/33] craft-testkit: an MCP message whose id is not a string, number or null is a protocol error A reply or request from the server with an id such as true, an array or an object was skipped as an unrelated reply, so the request waited for its deadline. It now returns a protocol error and closes the connection. --- crates/testkit/src/mcp.rs | 3 +++ crates/testkit/tests/mcp.rs | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index 400c072718..32b9d7bbf3 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -704,6 +704,9 @@ impl McpChild { /// Handles one message: answers a request from the child, keeps a notification, skips a reply /// to another id, and returns the reply to `waiting`. fn route(&mut self, v: Value, waiting: Option) -> Result, McpError> { + if v.get("id").is_some_and(|id| !matches!(id, Value::String(_) | Value::Number(_) | Value::Null)) { + return Err(self.fail(McpError::Protocol("a message has an `id` that is not a string, a number or null".into()))); + } match (v.get("method"), v.get("id")) { (Some(Value::String(method)), Some(id)) => { let reply = if method == "ping" { diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs index d56b891cf9..7fae87f1fc 100644 --- a/crates/testkit/tests/mcp.rs +++ b/crates/testkit/tests/mcp.rs @@ -407,6 +407,22 @@ fn a_malformed_reply_is_a_protocol_error() { } } +#[test] +fn a_message_with_an_invalid_id_is_a_protocol_error() { + let replies = [ + json!({"jsonrpc": "2.0", "id": true, "result": 1}), + json!({"jsonrpc": "2.0", "id": [1], "result": 1}), + json!({"jsonrpc": "2.0", "id": {"n": 1}, "error": {"code": 1, "message": "m"}}), + json!({"jsonrpc": "2.0", "id": false, "method": "ping"}), + ]; + for msg in replies { + let mut c = fake(move |_, _| Some(vec![msg.to_string()])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); + assert!(c.closed().is_some()); + } +} + #[test] fn a_tool_error_result_is_returned_unchanged() { let mut c = fake(|_, req| Some(vec![result(req, json!({"content": [{"type": "text", "text": "no document"}], "isError": true}))])); From 5f47a0abeac436803b2521a4c59a14d5e0921eb5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 20:17:44 -0800 Subject: [PATCH 09/33] craft-testkit: a malformed MCP reply to another id is a protocol error A reply to an id the client is not waiting for was skipped without a look at its shape, so a reply with both or neither of `result` and `error`, or an error without an integer code and a string message, left the waiting request to run into its deadline. It is now a protocol error that closes the connection; a well-formed reply to another id is still skipped. --- crates/testkit/README.md | 2 +- crates/testkit/src/mcp.rs | 22 ++++++++++++++++++---- crates/testkit/tests/mcp.rs | 15 +++++++++++++++ 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index ddce7e0a89..56bc12d7b2 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -215,7 +215,7 @@ The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The | Call | What it does | |---|---| | `initialize(version)` | Sends `initialize` with `version` (`mcp::PROTOCOL_VERSION` is `2025-06-18`), waits for the reply, then sends `notifications/initialized`. A reply with another version returns `UnsupportedVersion` and closes the connection. | -| `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. | +| `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Well-formed replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. | | `call_tool(name, args)`, `call_tool_within(.., timeout)` | Sends `tools/call` and returns the tool result unchanged, `content` and `isError` included. | | `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. | | `notify(method, params)` | Sends a notification, which has no id and gets no reply. | diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index 32b9d7bbf3..de13650cdc 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -298,6 +298,16 @@ fn read_line_capped(r: &mut impl BufRead, cap: usize) -> Result>, } } +/// Whether `v` holds exactly one of `result` and an `error` object with an integer `code` and a +/// string `message`. +fn is_reply(v: &Value) -> bool { + match (v.get("result"), v.get("error")) { + (Some(_), None) => true, + (None, Some(error)) => error.get("code").and_then(Value::as_i64).is_some() && error.get("message").is_some_and(Value::is_string), + _ => false, + } +} + /// Parses one stdout line as a JSON-RPC 2.0 message object. fn parse_line(line: &[u8]) -> Incoming { let preview = || String::from_utf8_lossy(&line[..line.len().min(PREVIEW)]).into_owned(); @@ -537,7 +547,7 @@ impl McpChild { /// /// While it waits, it answers the child's `ping` requests with an empty result and its other /// requests with error -32601, keeps notifications for [`McpChild::take_notifications`], and - /// skips replies with another id. None of these extend the deadline. + /// skips well-formed replies with another id. None of these extend the deadline. pub fn request_within(&mut self, method: &str, params: Value, timeout: Duration) -> Result { self.check_open()?; check_timeout("the request deadline", timeout)?; @@ -701,8 +711,8 @@ impl McpChild { })) } - /// Handles one message: answers a request from the child, keeps a notification, skips a reply - /// to another id, and returns the reply to `waiting`. + /// Handles one message: answers a request from the child, keeps a notification, skips a + /// well-formed reply to another id, and returns the reply to `waiting`. fn route(&mut self, v: Value, waiting: Option) -> Result, McpError> { if v.get("id").is_some_and(|id| !matches!(id, Value::String(_) | Value::Number(_) | Value::Null)) { return Err(self.fail(McpError::Protocol("a message has an `id` that is not a string, a number or null".into()))); @@ -727,7 +737,11 @@ impl McpChild { Ok(None) } (Some(_), _) => Err(self.fail(McpError::Protocol("a message has a `method` that is not a string".into()))), - (None, Some(id)) => Ok((waiting.is_some() && id.as_u64() == waiting).then_some(v)), + (None, Some(id)) if waiting.is_some() && id.as_u64() == waiting => Ok(Some(v)), + (None, Some(_)) if is_reply(&v) => Ok(None), + (None, Some(_)) => { + Err(self.fail(McpError::Protocol("a reply to another id does not hold exactly one of `result` and a valid `error`".into()))) + } (None, None) => Err(self.fail(McpError::Protocol("a message has neither `method` nor `id`".into()))), } } diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs index 7fae87f1fc..408f9ece55 100644 --- a/crates/testkit/tests/mcp.rs +++ b/crates/testkit/tests/mcp.rs @@ -423,6 +423,21 @@ fn a_message_with_an_invalid_id_is_a_protocol_error() { } } +#[test] +fn a_malformed_reply_to_another_id_is_a_protocol_error() { + let replies = [ + json!({"jsonrpc": "2.0", "id": 9999, "result": 1, "error": {"code": 1, "message": "both"}}), + json!({"jsonrpc": "2.0", "id": "other"}), + json!({"jsonrpc": "2.0", "id": null, "error": {"code": "x", "message": "m"}}), + ]; + for msg in replies { + let mut c = fake(move |_, _| Some(vec![msg.to_string()])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); + assert!(c.closed().is_some()); + } +} + #[test] fn a_tool_error_result_is_returned_unchanged() { let mut c = fake(|_, req| Some(vec![result(req, json!({"content": [{"type": "text", "text": "no document"}], "isError": true}))])); From 2e08f63b8c61f29effe07ac7d2595060f783d13a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:28:00 -0800 Subject: [PATCH 10/33] craft-mcp: build resource, prompt and completion results with cursor pages A server that routes resources/list, resources/templates/list, resources/read, prompts/list, prompts/get and completion/complete itself had to build those results by hand. The crate now checks their parameters and builds their results: - page takes one page of a list from the request's cursor and rejects parameters that are not an object and cursors it did not hand out with -32602; resource_list, resource_template_list and prompt_list wrap the page with its nextCursor. - resource_read, text_contents, blob_contents, read_result and resource_not_found (-32002 with the URI in data) cover resources/read. - prompt_get rejects arguments that are not strings; prompt_result and text_message build the prompts/get result. - completion_request reads a ref/prompt or ref/resource reference, and completion_result keeps the first 100 values with total and hasMore. --- crates/mcp/README.md | 23 +++- crates/mcp/src/lib.rs | 280 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 301 insertions(+), 2 deletions(-) diff --git a/crates/mcp/README.md b/crates/mcp/README.md index e84a1a40c5..f5b540f219 100644 --- a/crates/mcp/README.md +++ b/crates/mcp/README.md @@ -1,6 +1,7 @@ # craft-mcp -Transport-independent MCP 2025-03-26 server initialization and tool result helpers. +Transport-independent MCP 2025-03-26 server initialization and result helpers for tools, +resources, prompts and completion. Use one `Session` per client connection with `craft-jsonrpc` for message parsing and batch dispatch. The caller owns transport, tool definitions and execution, response size limits, and shutdown. Pass the outer envelope's batch status to `Session::request`. @@ -15,3 +16,23 @@ This crate does not enforce every MCP lifecycle or capability rule; applications must validate any additional requirements they depend on. See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle). + +The crate also checks the parameters of the resource, prompt and completion methods and +builds their results, for a server that routes those methods itself: + +- `page` takes one page of a list from the request's `cursor`, and `resource_list`, + `resource_template_list` and `prompt_list` wrap the page with its `nextCursor`. A + cursor that `page` did not hand out is rejected with -32602. +- `resource_read` returns the requested URI. `text_contents`, `blob_contents` and + `read_result` build the `resources/read` result, and `resource_not_found` is the + -32002 error with the URI in its data. +- `prompt_get` returns the prompt name and its string arguments. `prompt_result` and + `text_message` build the `prompts/get` result. +- `completion_request` returns the prompt or resource reference and the argument being + completed. `completion_result` keeps the first 100 values and sets `total` and `hasMore`. + +See the [pagination](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/pagination), +[resources](https://modelcontextprotocol.io/specification/2025-03-26/server/resources), +[prompts](https://modelcontextprotocol.io/specification/2025-03-26/server/prompts) and +[completion](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/completion) +specifications. diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index 6ca888fc06..1f25542bab 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -1,10 +1,13 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -//! MCP 2025-03-26 server initialization and tool envelopes, independent of transport and tools. +//! MCP 2025-03-26 server initialization and the envelopes of tools, resources, prompts and +//! completion, independent of transport and of what the server serves. //! The caller owns routing, transport and JSON-RPC batching. Compatibility mode preserves servers //! that accepted calls before initialization and initialize in a batch; strict mode enforces the //! initialization ordering and batch prohibition. Create one session per connection. +use std::collections::BTreeMap; + use craft_jsonrpc::{Request, RpcError}; use serde_json::{Value, json}; @@ -171,6 +174,196 @@ pub fn text_tool_result(text: &str, is_error: bool) -> Value { json!({"content": [{"type": "text", "text": text}], "isError": is_error}) } +/// Most values one `completion/complete` result may carry. +pub const MAX_COMPLETIONS: usize = 100; + +/// One page of a `resources/list`, `resources/templates/list` or `prompts/list` result. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Page { + pub items: Vec, + /// The cursor a client sends to get the next page; `None` on the last page. + pub next_cursor: Option, +} + +impl Page { + /// Every item in one page, for a server that does not paginate. + pub fn all(items: Vec) -> Self { + Self { items, next_cursor: None } + } +} + +/// Take the page of `items` that starts at the `cursor` in a list request's parameters, with at most +/// `page_size` items (0 puts every item in one page). The cursors are the decimal offsets this +/// function returns, which are multiples of `page_size`. Parameters that are not an object, and a +/// cursor that is not one of those offsets, are rejected with -32602. A cursor +/// past the end of a list that has shrunk since gives an empty last page. +pub fn page(params: Option<&Value>, mut items: Vec, page_size: usize) -> Result { + if params.is_some_and(|p| !p.is_object()) { + return Err(RpcError::new(-32602, "List parameters must be an object")); + } + let start = match params.and_then(|p| p.get("cursor")) { + None => 0, + Some(Value::String(cursor)) => match cursor.parse::() { + Ok(offset) if page_size > 0 && offset > 0 && offset % page_size == 0 && offset.to_string() == *cursor => offset, + _ => return Err(invalid_cursor()), + }, + Some(_) => return Err(invalid_cursor()), + }; + let start = start.min(items.len()); + items.drain(..start); + let mut next_cursor = None; + if page_size > 0 && items.len() > page_size { + items.truncate(page_size); + next_cursor = Some((start + page_size).to_string()); + } + Ok(Page { items, next_cursor }) +} + +fn invalid_cursor() -> RpcError { + RpcError::new(-32602, "Invalid cursor") +} + +/// Wrap a page of MCP `Resource` objects in the `resources/list` result. +pub fn resource_list(page: Page) -> Value { + list_result("resources", page) +} + +/// Wrap a page of MCP `ResourceTemplate` objects in the `resources/templates/list` result. +pub fn resource_template_list(page: Page) -> Value { + list_result("resourceTemplates", page) +} + +/// Wrap a page of MCP `Prompt` objects in the `prompts/list` result. +pub fn prompt_list(page: Page) -> Value { + list_result("prompts", page) +} + +fn list_result(key: &str, page: Page) -> Value { + let mut result = serde_json::Map::new(); + result.insert(key.to_owned(), Value::Array(page.items)); + if let Some(cursor) = page.next_cursor { + result.insert("nextCursor".to_owned(), Value::String(cursor)); + } + Value::Object(result) +} + +/// Validate `resources/read` parameters and return the requested URI. +pub fn resource_read(params: &Value) -> Result<&str, RpcError> { + params.get("uri").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing resource URI")) +} + +/// The error MCP specifies for a `resources/read` of a URI the server does not have. +pub fn resource_not_found(uri: &str) -> RpcError { + RpcError { code: -32002, message: "Resource not found".into(), data: Some(json!({"uri": uri})) } +} + +/// Text contents of a resource, for [`read_result`]. +pub fn text_contents(uri: &str, mime_type: Option<&str>, text: &str) -> Value { + contents(uri, mime_type, "text", text) +} + +/// Binary contents of a resource, for [`read_result`]. `base64` is the data in standard base64. +pub fn blob_contents(uri: &str, mime_type: Option<&str>, base64: &str) -> Value { + contents(uri, mime_type, "blob", base64) +} + +fn contents(uri: &str, mime_type: Option<&str>, key: &str, value: &str) -> Value { + let mut result = serde_json::Map::new(); + result.insert("uri".to_owned(), json!(uri)); + if let Some(mime_type) = mime_type { + result.insert("mimeType".to_owned(), json!(mime_type)); + } + result.insert(key.to_owned(), json!(value)); + Value::Object(result) +} + +/// Wrap resource contents in the `resources/read` result. +pub fn read_result(contents: Vec) -> Value { + json!({"contents": contents}) +} + +/// Validate `prompts/get` parameters and return the prompt name and its arguments. MCP prompt +/// arguments are strings, so an argument of any other type is rejected with -32602. +pub fn prompt_get(params: &Value) -> Result<(&str, BTreeMap<&str, &str>), RpcError> { + let name = params.get("name").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing prompt name"))?; + let arguments = match params.get("arguments") { + None => BTreeMap::new(), + Some(Value::Object(map)) => map + .iter() + .map(|(key, value)| value.as_str().map(|v| (key.as_str(), v))) + .collect::>>() + .ok_or_else(|| RpcError::new(-32602, "Prompt arguments must be strings"))?, + Some(_) => return Err(RpcError::new(-32602, "Prompt arguments must be an object")), + }; + Ok((name, arguments)) +} + +/// Wrap prompt messages (MCP `PromptMessage` objects) in the `prompts/get` result. +pub fn prompt_result(description: Option<&str>, messages: Vec) -> Value { + let mut result = json!({"messages": messages}); + if let Some(description) = description { + result["description"] = json!(description); + } + result +} + +/// A prompt message with one text block, from `"user"` or `"assistant"`. +pub fn text_message(role: &str, text: &str) -> Value { + json!({"role": role, "content": {"type": "text", "text": text}}) +} + +/// What a `completion/complete` request refers to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompletionRef<'a> { + /// A prompt, by name (`ref/prompt`). + Prompt(&'a str), + /// A resource or resource template, by URI or URI template (`ref/resource`). + Resource(&'a str), +} + +/// The parameters of a `completion/complete` request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Completion<'a> { + pub reference: CompletionRef<'a>, + /// The name of the argument being completed. + pub argument: &'a str, + /// What the user has typed for it so far. + pub value: &'a str, +} + +/// Validate `completion/complete` parameters. +pub fn completion_request(params: &Value) -> Result, RpcError> { + let invalid = |message: &str| RpcError::new(-32602, message); + let reference = params.get("ref").ok_or_else(|| invalid("Missing completion reference"))?; + let field = |key: &str| reference.get(key).and_then(Value::as_str); + let reference = match reference.get("type").and_then(Value::as_str) { + Some("ref/prompt") => CompletionRef::Prompt(field("name").ok_or_else(|| invalid("Missing prompt name"))?), + Some("ref/resource") => CompletionRef::Resource(field("uri").ok_or_else(|| invalid("Missing resource URI"))?), + _ => return Err(invalid("Unknown completion reference type")), + }; + let argument = params.get("argument"); + let text = |key: &str| argument.and_then(|a| a.get(key)).and_then(Value::as_str); + let (Some(name), Some(value)) = (text("name"), text("value")) else { + return Err(invalid("Completion argument needs a name and a value")); + }; + Ok(Completion { reference, argument: name, value }) +} + +/// Build the `completion/complete` result from every matching value. The result carries the first +/// [`MAX_COMPLETIONS`] values, the number of matches in `total`, and whether any were left out in +/// `hasMore`. +pub fn completion_result(values: impl IntoIterator) -> Value { + let mut kept = Vec::new(); + let mut total = 0usize; + for value in values { + if kept.len() < MAX_COMPLETIONS { + kept.push(value); + } + total += 1; + } + json!({"completion": {"values": kept, "total": total, "hasMore": total > MAX_COMPLETIONS}}) +} + #[cfg(test)] mod tests { use super::*; @@ -272,4 +465,89 @@ mod tests { assert_eq!(reply[1]["result"]["tools"], json!([])); assert_eq!(session.borrow().state(), State::Ready); } + + #[test] + fn list_pages_follow_their_cursors_to_the_end() { + let items: Vec = (0..5).map(|i| json!({"name": i})).collect(); + let mut params = None; + let mut names = Vec::new(); + let mut pages = 0; + loop { + let page = page(params.as_ref(), items.clone(), 2).unwrap(); + let result = prompt_list(page); + pages += 1; + names.extend(result["prompts"].as_array().unwrap().iter().map(|p| p["name"].clone())); + match result.get("nextCursor") { + Some(cursor) => params = Some(json!({"cursor": cursor})), + None => break, + } + } + assert_eq!((pages, names), (3, (0..5).map(|i| json!(i)).collect::>())); + assert_eq!(resource_list(page(None, items.clone(), 0).unwrap()), json!({"resources": items})); + let past_the_end = page(Some(&json!({"cursor": "8"})), items, 2).unwrap(); + assert_eq!(resource_template_list(past_the_end), json!({"resourceTemplates": []})); + } + + #[test] + fn list_cursors_that_were_not_handed_out_are_invalid_params() { + for cursor in [json!(""), json!("-1"), json!("+1"), json!("1.0"), json!("abc"), json!(2), json!(null), json!("99999999999999999999999")] { + let error = page(Some(&json!({"cursor": cursor})), vec![json!(1)], 1).unwrap_err(); + assert_eq!(error.code, -32602, "{cursor}"); + } + for cursor in ["1", "02", "0"] { + assert_eq!(page(Some(&json!({"cursor": cursor})), vec![json!(1); 5], 2).unwrap_err().code, -32602, "{cursor}"); + } + assert_eq!(page(Some(&json!({"cursor": "2"})), vec![json!(1); 5], 0).unwrap_err().code, -32602); + for params in [json!(null), json!([]), json!("0")] { + assert_eq!(page(Some(¶ms), vec![json!(1)], 1).unwrap_err().code, -32602, "{params}"); + } + } + + #[test] + fn resource_reads_validate_the_uri_and_build_contents() { + assert_eq!(resource_read(&json!({"uri": "x://a"})).unwrap(), "x://a"); + assert_eq!(resource_read(&json!({"uri": 1})).unwrap_err().code, -32602); + let missing = resource_not_found("x://b"); + assert_eq!((missing.code, missing.data), (-32002, Some(json!({"uri": "x://b"})))); + let result = read_result(vec![text_contents("x://a", Some("text/markdown"), "# A"), blob_contents("x://c", None, "AAE=")]); + assert_eq!(result, json!({"contents": [{"uri": "x://a", "mimeType": "text/markdown", "text": "# A"}, {"uri": "x://c", "blob": "AAE="}]})); + } + + #[test] + fn prompt_arguments_must_be_strings() { + let params = json!({"name": "describe", "arguments": {"part": "bracket"}}); + let (name, args) = prompt_get(¶ms).unwrap(); + assert_eq!((name, args.get("part").copied()), ("describe", Some("bracket"))); + assert!(prompt_get(&json!({"name": "describe"})).unwrap().1.is_empty()); + for params in [json!({}), json!({"name": "d", "arguments": {"n": 1}}), json!({"name": "d", "arguments": ["x"]})] { + assert_eq!(prompt_get(¶ms).unwrap_err().code, -32602, "{params}"); + } + let result = prompt_result(Some("Describe a part"), vec![text_message("user", "Describe bracket")]); + assert_eq!(result["messages"][0]["content"], json!({"type": "text", "text": "Describe bracket"})); + assert_eq!(result["description"], "Describe a part"); + } + + #[test] + fn completion_requests_name_a_prompt_or_a_resource() { + let prompt = json!({"ref": {"type": "ref/prompt", "name": "describe"}, "argument": {"name": "part", "value": "br"}}); + assert_eq!(completion_request(&prompt).unwrap(), Completion { reference: CompletionRef::Prompt("describe"), argument: "part", value: "br" }); + let resource = json!({"ref": {"type": "ref/resource", "uri": "lib://parts/{part}"}, "argument": {"name": "part", "value": ""}}); + assert_eq!(completion_request(&resource).unwrap().reference, CompletionRef::Resource("lib://parts/{part}")); + for params in [ + json!({"ref": {"type": "ref/tool", "name": "x"}, "argument": {"name": "a", "value": ""}}), + json!({"ref": {"type": "ref/prompt"}, "argument": {"name": "a", "value": ""}}), + json!({"ref": {"type": "ref/prompt", "name": "x"}, "argument": {"name": "a"}}), + json!({"argument": {"name": "a", "value": ""}}), + ] { + assert_eq!(completion_request(¶ms).unwrap_err().code, -32602, "{params}"); + } + } + + #[test] + fn completion_results_carry_at_most_a_hundred_values() { + let result = completion_result((0..150).map(|i| i.to_string())); + assert_eq!(result["completion"]["values"].as_array().map(Vec::len), Some(MAX_COMPLETIONS)); + assert_eq!((&result["completion"]["total"], &result["completion"]["hasMore"]), (&json!(150), &json!(true))); + assert_eq!(completion_result(["a".to_owned()]), json!({"completion": {"values": ["a"], "total": 1, "hasMore": false}})); + } } From 2b90092e9402e7e5aca114f52bfb10246a945e30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 11:43:59 -0800 Subject: [PATCH 11/33] audio-dsp: tremolo gives a live voice a pulsing level with no latency tremolo is a new Modulation effect. The gain is 1 - Depth * m, where the LFO value m runs at Rate (0.1 to 20 Hz, default 5) from 0 at the start of each cycle to 1 at its middle and back, as a sine, a triangle or a square. The square holds each level for half a cycle and moves between them along a 2 ms raised-cosine edge, so it does not click. Rate takes effect from the next sample with the phase kept, and Depth (default 50 %) moves to a new value over 20 ms. A change of Shape, or of Rate while the shape is the square, glides from the last LFO value to the new curve over 20 ms, with the value kept within 0 to 1, so the gain neither jumps nor inverts the input. The effect has no tail. Non-finite samples come out as silence, and nothing allocates while processing. The effect joins the channel-cap test and the no-allocation tests. --- crates/audio-dsp/README.md | 3 +- crates/audio-dsp/src/effects.rs | 3 +- .../audio-dsp/src/effects/behavior_tests.rs | 1 + crates/audio-dsp/src/effects/character.rs | 278 +++++++++++++++++- crates/audio-dsp/tests/it/no_alloc.rs | 44 +++ 5 files changed, 326 insertions(+), 3 deletions(-) diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index b08b39cfac..5d801345e9 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -20,7 +20,8 @@ and contains no `unsafe` code. and `latency()` reports it while the switch is on. A ring modulator for robotic and metallic voices (ring, frequency modulation, and positive or negative comb resonators, with the frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency, and - neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits. + neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits, + or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 255857b783..680e5e4e4c 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -22,7 +22,7 @@ pub(crate) mod util; pub(crate) mod voice; pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing}; -pub use character::{Bitcrusher, RingMod}; +pub use character::{Bitcrusher, RingMod, Tremolo}; pub(crate) use declick::ClickRemover; pub use dither::Dither; pub use dynamics::{Compressor, Gate, Limiter, Maximizer}; @@ -151,6 +151,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("flanger", "Flanger", Modulation, Flanger), entry!("phaser", "Phaser", Modulation, Phaser), entry!("ring_mod", "Ring Modulator", Modulation, RingMod), + entry!("tremolo", "Tremolo", Modulation, Tremolo), entry!("analog_delay", "Analog Delay", Time, AnalogDelay), entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay), entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index 5e628f28ea..da460a06d6 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -992,6 +992,7 @@ fn direct_constructors_cap_the_channel_count() { suppress::NoiseSuppression, character::RingMod, character::Bitcrusher, + character::Tremolo, ); } diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index ec9b82d258..74cd890775 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -17,8 +17,11 @@ //! //! The bitcrusher (`bitcrusher`) takes one input sample every `rate_divide` samples, holds it until //! the next one, and rounds it to a word length of 1 to 16 bits. +//! +//! The tremolo (`tremolo`) lowers the gain of every channel by up to `depth` once per cycle of a +//! sine, triangle or square LFO at `rate`. -use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail}; +use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail, uni_sine, uni_tri}; use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; use std::f64::consts::TAU; @@ -38,6 +41,9 @@ const FM_BASE: f32 = 2.0; const SEED: u64 = 0x5EED_1234; /// Highest frequency the modulation reaches, as a fraction of the sample rate. const MAX_FRACTION: f32 = 0.45; +const TREMOLO_SHAPES: &[&str] = &["Sine", "Triangle", "Square"]; +/// Length of each edge of the tremolo's square, in ms. +const EDGE_MS: f64 = 2.0; /// Ring modulation, frequency modulation and positive or negative comb resonators, with the /// frequency moved by an LFO, an envelope follower or a sample-and-hold source. @@ -308,6 +314,128 @@ impl AudioEffect for Bitcrusher { } } +/// Amplitude modulation. The gain is `1 - depth * m`, where the LFO value `m` runs from 0 at the +/// start of each cycle to 1 at its middle and back, as a sine, a triangle or a square. The square +/// holds 0 and 1 for half a cycle each and moves between them along a raised-cosine edge 2 ms long, +/// centered on the quarter and three-quarter points, so it does not click. Rate takes effect from +/// the next sample with the phase kept. A change of Shape, or of Rate while the shape is the +/// square, glides from the last LFO value to the new curve over 20 ms, with the value kept within +/// 0 ..= 1. Depth moves to a new value over 20 ms. +pub struct Tremolo { + pv: ParamValues, + sr: f32, + channels: usize, + lfo: Lfo, + /// Shape the LFO value follows. + shape: usize, + /// Length of the square's edges, in cycles, for the rate of the last block. + edge: f64, + /// LFO value of the last sample. + last: f32, + /// Difference between the last LFO value and the new curve at a change of Shape, or of the + /// square's edges. It fades to zero over `glide_len` samples. + glide: f32, + glide_left: usize, + glide_len: usize, + depth: Smoothed, +} + +impl Tremolo { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::log("rate", "Rate", 0.1, 20.0, 5.0, Unit::Hertz), + ParamSpec::new("depth", "Depth", 0.0, 100.0, 50.0, Unit::Percent), + ParamSpec::choice("shape", "Shape", TREMOLO_SHAPES, 0), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let mut s = Tremolo { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + channels: crate::sane_channels(channels), + lfo: Lfo::default(), + shape: 0, + edge: 0.0, + last: 0.0, + glide: 0.0, + glide_left: 0, + glide_len: ((SM * 0.001 * sample_rate) as usize).max(1), + depth: Smoothed::with_ms(0.5, sample_rate, SM), + }; + s.apply_params(true); + s.shape = s.pv.idx("shape"); + s.edge = s.edge_len(); + s + } + + /// Length of the square's edges at the current rate, in cycles. + fn edge_len(&self) -> f64 { + (EDGE_MS * 0.001 * f64::from(self.pv.v("rate"))).clamp(1e-9, 0.25) + } + + fn apply_params(&mut self, snap: bool) { + self.depth.set(self.pv.v("depth") / 100.0); + if snap { + self.depth.snap(); + } + } + + /// LFO value of `shape` at phase `p` (cycles), with square edges `edge` cycles long. + fn shape_value(shape: usize, p: f64, edge: f64) -> f32 { + match shape { + 1 => uni_tri(p), + 2 => { + // The triangle crosses 1/2 at the edges' centers with a slope of 2 per cycle, so an + // edge `edge` cycles long spans `2 * edge` of it. + let tri = if p < 0.5 { 2.0 * p } else { 2.0 - 2.0 * p }; + let u = ((tri - 0.5) / (2.0 * edge) + 0.5).clamp(0.0, 1.0); + (0.5 - 0.5 * (std::f64::consts::PI * u).cos()) as f32 + } + _ => uni_sine(p), + } + } +} + +impl AudioEffect for Tremolo { + param_plumbing!("tremolo"); + fn reset(&mut self) { + self.lfo.reset(); + self.shape = self.pv.idx("shape"); + self.edge = self.edge_len(); + self.last = 0.0; + self.glide = 0.0; + self.glide_left = 0; + self.depth.snap(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + let nch = channels.len().min(self.channels); + let rate = self.pv.v("rate"); + let edge = self.edge_len(); + let shape = self.pv.idx("shape"); + if shape != self.shape || (shape == 2 && edge != self.edge) { + self.glide = self.last - Self::shape_value(shape, self.lfo.phase(0.0), edge); + self.glide_left = self.glide_len; + self.shape = shape; + } + self.edge = edge; + for i in 0..n { + let mut m = Self::shape_value(shape, self.lfo.phase(0.0), edge); + if self.glide_left > 0 { + m = (m + self.glide * self.glide_left as f32 / self.glide_len as f32).clamp(0.0, 1.0); + self.glide_left -= 1; + } + self.last = m; + self.lfo.advance(rate, self.sr); + let gain = 1.0 - self.depth.tick() * m; + for c in channels[..nch].iter_mut() { + // A non-finite sample is taken as silence. + c[i] = if c[i].is_finite() { c[i] * gain } else { 0.0 }; + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -614,4 +742,152 @@ mod tests { } } } + + fn tremolo(params: &[(&str, f32)], channels: usize) -> Tremolo { + let mut t = Tremolo::new(SR, channels); + for (id, v) in params { + assert!(t.set_param(id, *v), "{id}"); + } + t.reset(); + t + } + + /// The gain of a tremolo over `n` samples, read from a constant input of 1. + fn gains(t: &mut Tremolo, n: usize) -> Vec { + let mut x = vec![1.0f32; n]; + t.process(&mut [&mut x]); + x + } + + /// At full depth the gain is 1 at the start of each cycle and 0 at its middle. The sine and the + /// triangle follow their curves, the square holds each level for most of half a cycle, and + /// half depth swings the gain between 1 and 1/2. + #[test] + fn tremolo_gain_follows_the_shape() { + let period = 9600; + for shape in 0..3 { + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", shape as f32)], 1); + let g = gains(&mut t, 2 * period); + for (i, v) in g.iter().enumerate() { + let p = (i % period) as f64 / period as f64; + let want = match shape { + 0 => 0.5 + 0.5 * (TAU * p).cos(), + 1 => 1.0 - 2.0 * p.min(1.0 - p), + _ if !(0.24..=0.26).contains(&p) && !(0.74..=0.76).contains(&p) => { + if (0.25..0.75).contains(&p) { + 0.0 + } else { + 1.0 + } + } + _ => continue, + }; + assert!((f64::from(*v) - want).abs() < 1e-4, "shape {shape} at {i}: {v}, want {want}"); + } + let mut t = tremolo(&[("rate", 5.0), ("depth", 50.0), ("shape", shape as f32)], 1); + let g = gains(&mut t, period); + let (lo, hi) = g.iter().fold((f32::MAX, f32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + assert!((lo - 0.5).abs() < 1e-4 && (hi - 1.0).abs() < 1e-6, "shape {shape}: {lo} ..= {hi}"); + } + } + + /// The square's edges are 2 ms raised-cosine ramps at every rate, centered on the quarter and + /// three-quarter points of the cycle. + #[test] + fn tremolo_square_edges_do_not_click() { + let edge = (0.002 * SR) as usize; + for rate in [0.1f32, 1.0, 20.0] { + let mut t = tremolo(&[("rate", rate), ("depth", 100.0), ("shape", 2.0)], 1); + let g = gains(&mut t, (SR / rate) as usize); + let worst = g.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0f32, f32::max); + // A raised cosine over `edge` samples moves at most pi / 2 / edge per sample. + assert!(worst <= std::f32::consts::FRAC_PI_2 / edge as f32 * 1.01, "rate {rate}: step {worst}"); + let moving = g.windows(2).filter(|w| w[1] != w[0]).count(); + assert!(moving <= 2 * edge + 2, "rate {rate}: the gain moves on {moving} samples"); + let quarter = (SR / rate / 4.0) as usize; + assert!((g[quarter] - 0.5).abs() < 0.02, "rate {rate}: {} at the quarter point", g[quarter]); + } + } + + /// A new rate takes effect from the next sample, with the phase kept. + #[test] + fn tremolo_rate_change_keeps_the_phase() { + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0)], 1); + let a = gains(&mut t, 2400); + assert!(t.set_param("rate", 10.0)); + let b = gains(&mut t, 2400); + // A quarter of a cycle at 5 Hz, then a quarter at 10 Hz ends at the middle of the cycle. + assert!((a[2399] - 0.5).abs() < 1e-3 && (b[0] - a[2399]).abs() < 1e-3, "{} then {}", a[2399], b[0]); + assert!(b[1199] < 1e-3 && b[1201] < 1e-3, "{} {}", b[1199], b[1201]); + } + + /// A change of shape glides from where the old shape was to the new one over 20 ms, so the + /// gain does not jump, and the new shape is followed exactly afterward. + #[test] + fn tremolo_shape_change_glides() { + let glide = (0.02 * SR) as usize; + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + let mut s = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 2.0)], 1); + // 2,000 samples in, the sine has the gain at 0.63 and the square at 1. + let a = gains(&mut t, 2000); + gains(&mut s, 2000); + assert!(t.set_param("shape", 2.0)); + let b = gains(&mut t, 2 * glide); + let want = gains(&mut s, 2 * glide); + // The square's own edge moves the gain by up to pi / 2 / 96 (0.0164) per sample. + let step = (b[0] - a[1999]).abs(); + assert!(step < 0.02, "the gain jumped by {step}"); + assert!(b.windows(2).all(|w| (w[1] - w[0]).abs() < 0.02), "the glide jumped"); + assert_eq!(b[glide..], want[glide..]); + assert!((b[0] - want[0]).abs() > 0.2, "{} {}", b[0], want[0]); + } + + /// A new rate moves the square's edges to a new share of the cycle. Changed just before an + /// edge, from 0.1 Hz (where the edge is still ahead) to 20 Hz (where the phase is inside it), + /// the gain glides instead of jumping. + #[test] + fn tremolo_square_rate_change_glides() { + let mut t = tremolo(&[("rate", 0.1), ("depth", 100.0), ("shape", 2.0)], 1); + // Phase 0.249 at 0.1 Hz. + let a = gains(&mut t, 119_520); + assert_eq!(a[119_519], 1.0); + assert!(t.set_param("rate", 20.0)); + let b = gains(&mut t, 2000); + let step = (b[0] - a[119_519]).abs(); + assert!(step < 0.02, "the gain jumped by {step}"); + assert!(b.windows(2).all(|w| (w[1] - w[0]).abs() < 0.02), "the glide jumped"); + } + + /// At zero depth the input passes unchanged, a non-finite sample comes out as silence, and a + /// channel past the configured count is left alone. + #[test] + fn tremolo_depth_zero_non_finite_and_extra_channels() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut t = tremolo(&[("depth", 0.0), ("shape", 2.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + t.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut t = tremolo(&[("depth", 100.0)], 1); + let (mut l, mut r) = (x.clone(), x.clone()); + l[99] = f32::NAN; + l[200] = f32::INFINITY; + t.process(&mut [&mut l, &mut r]); + assert!(l[99] == 0.0 && l[200] == 0.0 && l.iter().all(|v| v.is_finite())); + assert_eq!(r, x); + } + + /// A glide keeps the LFO value within 0 ..= 1, so the gain stays between 1 - depth and 1 and + /// never inverts the input, even when the new curve moves away from the glide's offset. + #[test] + fn tremolo_glide_keeps_the_gain_in_range() { + for (from, to) in [(1.0, 2.0), (2.0, 1.0), (0.0, 2.0), (2.0, 0.0)] { + for start in [240, 480, 1680, 1900] { + let mut t = tremolo(&[("rate", 20.0), ("depth", 100.0), ("shape", from)], 1); + gains(&mut t, start); + assert!(t.set_param("shape", to)); + let g = gains(&mut t, 2400); + assert!(g.iter().all(|v| (0.0..=1.0).contains(v)), "{from} to {to} at {start}: {g:?}"); + } + } + } } diff --git a/crates/audio-dsp/tests/it/no_alloc.rs b/crates/audio-dsp/tests/it/no_alloc.rs index 5189e3177e..a62bd82a04 100644 --- a/crates/audio-dsp/tests/it/no_alloc.rs +++ b/crates/audio-dsp/tests/it/no_alloc.rs @@ -180,6 +180,50 @@ fn bitcrusher_does_not_allocate_while_processing() { assert!(l.iter().chain(&r).all(|v| v.is_finite())); } +/// The tremolo runs a voiced tone through 10,000 blocks of 480 frames, with its rate, depth and +/// shape changed between blocks, blocks that leave the second channel out, a NaN sample and a +/// reset, without one heap allocation. +#[test] +fn tremolo_does_not_allocate_while_processing() { + let Some(mut fx) = create_effect("tremolo", 48_000.0, 2) else { panic!("tremolo is not registered") }; + let tone: Vec = (0..480).map(|i| (0.4 * (std::f64::consts::TAU * 150.0 * i as f64 / 48_000.0).sin()) as f32).collect(); + let (mut l, mut r) = (tone.clone(), tone.clone()); + let info = allocation_counter::measure(|| { + for block in 0..10_000u32 { + match block % 500 { + 0 => { + fx.set_param("rate", 0.1 + (block / 500 % 10) as f32 * 2.0); + } + 100 => { + fx.set_param("shape", (block / 500 % 3) as f32); + } + 250 => { + fx.set_param("depth", 100.0); + } + 499 => { + fx.set_param("depth", 30.0); + } + _ => {} + } + if block == 7_777 { + fx.reset(); + } + l.copy_from_slice(&tone); + r.copy_from_slice(&tone); + if block == 5_000 { + l[100] = f32::NAN; + } + if (6_000..6_020).contains(&block) { + fx.process(&mut [&mut l]); + } else { + fx.process(&mut [&mut l, &mut r]); + } + } + }); + assert_eq!(info.count_total, 0, "{info:?}"); + assert!(l.iter().chain(&r).all(|v| v.is_finite())); +} + /// The ring modulator runs a voiced tone through 10,000 blocks of 480 frames, with its effect, /// modulation source, frequency and depth changed between blocks, blocks that leave the second /// channel out, a NaN sample and a reset, without one heap allocation. From 785a6fc0d40d4a6b33fd1cf790d821caf64f4768 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 14:02:48 -0800 Subject: [PATCH 12/33] audio-dsp: vibrato swings the pitch of a live voice with no latency vibrato is a new Modulation effect. It reads the input through a delay of swing * m samples, where the LFO value m runs at Rate (1 to 14 Hz, default 6) from 0 at the start of each cycle to 1 at its middle and back, as a sine or a triangle. The swing is set from Rate and Depth (0 to 100 cents, default 40) so that the pitch falls by Depth cents while the delay grows and rises by a little less while it shrinks. The delay is 0 at the start of each cycle. Rate takes effect from the next sample with the phase kept. A change of Rate, Depth or Shape glides the delay from its last value to the new curve, moving it by at most 1/32 sample per sample on top of the curve, so the output neither clicks nor jumps in pitch. The tail covers the new curve's swing plus the last delay. Non-finite samples are taken as silence, the read interpolates in f64 so that finite samples near the f32 limit stay finite, a channel a block leaves out is fed silence, and nothing allocates while processing. The effect joins the channel-cap test and the no-allocation tests. --- crates/audio-dsp/README.md | 4 +- crates/audio-dsp/src/effects.rs | 3 +- .../audio-dsp/src/effects/behavior_tests.rs | 1 + crates/audio-dsp/src/effects/character.rs | 347 ++++++++++++++++++ crates/audio-dsp/tests/it/no_alloc.rs | 44 +++ 5 files changed, 397 insertions(+), 2 deletions(-) diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index 5d801345e9..083b41bad3 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -21,7 +21,9 @@ and contains no `unsafe` code. voices (ring, frequency modulation, and positive or negative comb resonators, with the frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency, and neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits, - or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. + or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. A vibrato + that swings the pitch by up to 100 cents through a delay moved by a sine or triangle LFO adds + no latency either: the delay is 0 at the start of each cycle. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 680e5e4e4c..c5fa334c21 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -22,7 +22,7 @@ pub(crate) mod util; pub(crate) mod voice; pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing}; -pub use character::{Bitcrusher, RingMod, Tremolo}; +pub use character::{Bitcrusher, RingMod, Tremolo, Vibrato}; pub(crate) use declick::ClickRemover; pub use dither::Dither; pub use dynamics::{Compressor, Gate, Limiter, Maximizer}; @@ -152,6 +152,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("phaser", "Phaser", Modulation, Phaser), entry!("ring_mod", "Ring Modulator", Modulation, RingMod), entry!("tremolo", "Tremolo", Modulation, Tremolo), + entry!("vibrato", "Vibrato", Modulation, Vibrato), entry!("analog_delay", "Analog Delay", Time, AnalogDelay), entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay), entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index da460a06d6..3af9055c35 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -993,6 +993,7 @@ fn direct_constructors_cap_the_channel_count() { character::RingMod, character::Bitcrusher, character::Tremolo, + character::Vibrato, ); } diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index 74cd890775..aeb24430cf 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -20,6 +20,10 @@ //! //! The tremolo (`tremolo`) lowers the gain of every channel by up to `depth` once per cycle of a //! sine, triangle or square LFO at `rate`. +//! +//! The vibrato (`vibrato`) reads the input through a delay that grows from 0 and shrinks back once +//! per cycle of a sine or triangle LFO at `rate`, so the pitch swings by up to `depth` cents. The +//! delay is 0 at the start of each cycle. use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail, uni_sine, uni_tri}; use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; @@ -44,6 +48,13 @@ const MAX_FRACTION: f32 = 0.45; const TREMOLO_SHAPES: &[&str] = &["Sine", "Triangle", "Square"]; /// Length of each edge of the tremolo's square, in ms. const EDGE_MS: f64 = 2.0; +const VIBRATO_SHAPES: &[&str] = &["Sine", "Triangle"]; +/// Lowest rate of the vibrato, in Hz. +const VIBRATO_MIN_RATE: f32 = 1.0; +/// Greatest depth of the vibrato, in cents. +const VIBRATO_MAX_CENTS: f32 = 100.0; +/// Most the vibrato's glide moves the delay per sample on top of the curve. +const VIBRATO_GLIDE_SLOPE: f32 = 1.0 / 32.0; /// Ring modulation, frequency modulation and positive or negative comb resonators, with the /// frequency moved by an LFO, an envelope follower or a sample-and-hold source. @@ -436,6 +447,149 @@ impl AudioEffect for Tremolo { } } +/// Pitch modulation. The input is read through a delay of `swing * m` samples, where the LFO value +/// `m` runs from 0 at the start of each cycle to 1 at its middle and back, as a sine or a triangle. +/// The swing is set so that the pitch falls by `depth` cents while the delay grows, and rises by a +/// little less while it shrinks: the read moves at `1 -/+ d` samples per sample, with +/// `d = 1 - 2^(-depth / 1200)`. A sine reaches `d` at its steepest point, and a triangle holds it +/// for each half of the cycle. At the start of each cycle the delay is 0. Rate takes effect from +/// the next sample with the phase kept. A change of Rate, Depth or Shape glides the delay from its +/// last value to the new curve, moving it by at most 1/32 sample per sample on top of the curve, so +/// the output neither clicks nor jumps in pitch. +pub struct Vibrato { + pv: ParamValues, + sr: f32, + lines: Vec, + lfo: Lfo, + /// Shape the delay follows. + shape: usize, + /// Peak delay of the curve, in samples, for the settings of the last block. + swing: f32, + /// Delay of the last sample, in samples. + last: f32, + /// Difference between the last delay and the new curve at a change of the settings. It fades + /// to zero over `glide_len` samples. + glide: f32, + glide_left: usize, + glide_len: usize, +} + +impl Vibrato { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::log("rate", "Rate", VIBRATO_MIN_RATE, 14.0, 6.0, Unit::Hertz), + ParamSpec::new("depth", "Depth (cents)", 0.0, VIBRATO_MAX_CENTS, 40.0, Unit::None), + ParamSpec::choice("shape", "Shape", VIBRATO_SHAPES, 0), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + // The widest swing is the triangle's at the lowest rate and the greatest depth. A glide + // can add up to one more swing on top of the curve. + let widest_ms = (1000.0 * Self::slope(VIBRATO_MAX_CENTS) / (2.0 * f64::from(VIBRATO_MIN_RATE))) as f32; + let len = delay_line_len(2.0 * widest_ms + 1.0, sample_rate, ch); + let mut s = Vibrato { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + lines: vec![DelayLine::new(len); ch], + lfo: Lfo::default(), + shape: 0, + swing: 0.0, + last: 0.0, + glide: 0.0, + glide_left: 0, + glide_len: 1, + }; + s.shape = s.pv.idx("shape"); + s.swing = s.swing_len(); + s + } + + fn apply_params(&mut self, _snap: bool) {} + + /// Samples the read moves per sample, away from 1, at a depth of `cents`. + fn slope(cents: f32) -> f64 { + 1.0 - (-f64::from(cents) / 1200.0).exp2() + } + + /// Peak delay of the curve for the current settings, in samples. + fn swing_len(&self) -> f32 { + let (d, rate, sr) = (Self::slope(self.pv.v("depth")), f64::from(self.pv.v("rate")), f64::from(self.sr)); + // The sine's delay `swing * (1 - cos(2 pi p)) / 2` moves by at most `swing * pi * rate / sr` + // per sample, and the triangle's moves by `swing * 2 * rate / sr`. + let swing = if self.pv.idx("shape") == 1 { d * sr / (2.0 * rate) } else { d * sr / (std::f64::consts::PI * rate) }; + (swing as f32).min(self.max_delay()) + } + + fn max_delay(&self) -> f32 { + self.lines.first().map_or(0.0, DelayLine::max_delay) + } + + /// LFO value of `shape` at phase `p` (cycles). + fn shape_value(shape: usize, p: f64) -> f32 { + if shape == 1 { uni_tri(p) } else { uni_sine(p) } + } +} + +impl AudioEffect for Vibrato { + param_plumbing!("vibrato"); + /// The input sounds until the delay has passed it. The delay reaches at most the new curve's + /// swing plus the last delay, so the tail covers both. + fn tail_samples(&self) -> usize { + (self.swing_len() + self.last).min(self.max_delay()).ceil() as usize + 1 + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(DelayLine::reset); + self.lfo.reset(); + self.shape = self.pv.idx("shape"); + self.swing = self.swing_len(); + self.last = 0.0; + self.glide = 0.0; + self.glide_left = 0; + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + let nch = channels.len().min(self.lines.len()); + let rate = self.pv.v("rate"); + let shape = self.pv.idx("shape"); + let swing = self.swing_len(); + if shape != self.shape || swing != self.swing { + self.glide = self.last - swing * Self::shape_value(shape, self.lfo.phase(0.0)); + self.glide_len = ((self.glide.abs() / VIBRATO_GLIDE_SLOPE).ceil() as usize).max(1); + self.glide_left = if self.glide == 0.0 { 0 } else { self.glide_len }; + self.shape = shape; + self.swing = swing; + } + let max = self.max_delay(); + for i in 0..n { + let mut d = swing * Self::shape_value(shape, self.lfo.phase(0.0)); + if self.glide_left > 0 { + d = (d + self.glide * self.glide_left as f32 / self.glide_len as f32).clamp(0.0, max); + self.glide_left -= 1; + } + self.last = d; + self.lfo.advance(rate, self.sr); + // The read interpolates in f64, so neighboring samples near the f32 limit with opposite + // signs do not overflow. + let d = if d.is_nan() { 0.0 } else { d.clamp(0.0, max) }; + let (di, frac) = (d.floor() as usize, f64::from(d - d.floor())); + for (ch, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is taken as silence. A channel the block leaves out is fed + // silence, so it holds none of its earlier audio when it comes back. + let dry = match channels.get(ch).filter(|_| ch < nch) { + Some(c) if c[i].is_finite() => c[i], + _ => 0.0, + }; + line.push(dry); + if ch < nch { + let (a, b) = (f64::from(line.tap(di)), f64::from(line.tap(di + 1))); + channels[ch][i] = (a + (b - a) * frac) as f32; + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -890,4 +1044,197 @@ mod tests { } } } + + fn vibrato(params: &[(&str, f32)], channels: usize) -> Vibrato { + let mut v = Vibrato::new(SR, channels); + for (id, x) in params { + assert!(v.set_param(id, *x), "{id}"); + } + v.reset(); + v + } + + /// Slope of the ramp the delay tests feed in, per sample. + const RAMP: f32 = 1e-3; + /// Most the delay moves per sample during a glide at a depth of 100 cents: the curve's + /// steepest slope plus the glide's, with room for the rounding of the ramp. + const GLIDE_STEP: f32 = 0.0562 + 1.0 / 32.0 + 0.002; + + /// The delay of a vibrato over `n` samples, read from a ramp that starts at `start` samples. + fn delays(v: &mut Vibrato, start: usize, n: usize) -> Vec { + let x: Vec = (start..start + n).map(|i| i as f32 * RAMP).collect(); + let mut y = x.clone(); + v.process(&mut [&mut y]); + x.iter().zip(&y).map(|(a, b)| (a - b) / RAMP).collect() + } + + /// Largest change of the delay between neighboring samples, averaged over 2 * `k` samples to + /// smooth out the rounding of the ramp. + fn steepest(d: &[f32], k: usize) -> f32 { + (k..d.len() - k).map(|i| (d[i + k] - d[i - k]).abs() / (2 * k) as f32).fold(0.0, f32::max) + } + + /// The delay is 0 at the start of each cycle and follows the sine or the triangle, and its + /// steepest slope lowers the pitch by the depth: 100 cents at a depth of 100 for both shapes. + #[test] + fn vibrato_delay_follows_the_shape_and_the_depth() { + let d_max = 1.0 - 2f32.powf(-100.0 / 1200.0); + for (shape, rate) in [(0, 6.0f32), (1, 6.0), (0, 1.0), (1, 14.0)] { + let mut v = vibrato(&[("rate", rate), ("depth", 100.0), ("shape", shape as f32)], 1); + let period = (SR / rate) as usize; + let swing = v.swing; + let d = delays(&mut v, 0, 2 * period); + for (i, got) in d.iter().enumerate() { + let p = (i as f64 * f64::from(rate) / f64::from(SR)).fract(); + let want = swing * if shape == 1 { uni_tri(p) } else { uni_sine(p) }; + assert!((got - want).abs() < 0.05, "shape {shape} at {rate} Hz, sample {i}: {got}, want {want}"); + } + assert!(d[0].abs() < 0.05 && d[period].abs() < 0.05, "shape {shape}: {} {}", d[0], d[period]); + let slope = steepest(&d, 40); + let cents = 1200.0 * (1.0 - slope).log2(); + assert!((cents + 100.0).abs() < 2.0, "shape {shape} at {rate} Hz: the pitch falls by {cents} cents"); + assert!((slope - d_max).abs() < 0.002, "shape {shape} at {rate} Hz: slope {slope}"); + } + } + + /// A lower depth set at the middle of the cycle, where the delay is longest, glides the delay + /// down to the new curve without jumping, and afterward the output matches a vibrato that had + /// the new depth from the start. + #[test] + fn vibrato_depth_change_glides_to_the_new_curve() { + let half = 4000; + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0)], 1); + let mut w = vibrato(&[("rate", 6.0), ("depth", 10.0)], 1); + let a = delays(&mut v, 0, half); + delays(&mut w, 0, half); + assert!(v.set_param("depth", 10.0)); + let b = delays(&mut v, half, 16_000); + let want = delays(&mut w, half, 16_000); + // The new curve moves by up to 0.0058 per sample, and the glide by 1/32 more. + let step = (b[0] - a[half - 1]).abs(); + assert!(step < 0.04, "the delay jumped by {step}"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < 0.04), "the glide moved too fast"); + assert!(b[100] > want[100] + 100.0, "{} {}", b[100], want[100]); + let glide = v.glide_len; + assert!(glide < b.len() / 2, "the glide has not ended: {glide}"); + assert_eq!(b[glide..], want[glide..]); + } + + /// A new rate takes effect from the next sample with the phase kept, the delay glides to the + /// new curve without jumping, and afterward follows it. + #[test] + fn vibrato_rate_change_keeps_the_phase_and_glides() { + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0)], 1); + // A quarter of a cycle at 6 Hz. + let a = delays(&mut v, 0, 2000); + assert!(v.set_param("rate", 3.0)); + let swing = v.swing_len(); + let b = delays(&mut v, 2000, 12000); + let step = (b[0] - a[1999]).abs(); + assert!(step < GLIDE_STEP, "the delay jumped by {step}"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < GLIDE_STEP), "the glide moved too fast"); + let glide = v.glide_len; + assert!(glide < b.len() / 2, "the glide has not ended: {glide}"); + for (k, got) in b.iter().enumerate().skip(glide) { + let p = (0.25 + k as f64 * 3.0 / f64::from(SR)).fract(); + let want = swing * uni_sine(p); + assert!((got - want).abs() < 0.05, "sample {k}: {got}, want {want}"); + } + } + + /// A change of shape glides from the last delay to the new curve without jumping. + #[test] + fn vibrato_shape_change_glides() { + for (from, to) in [(0.0, 1.0), (1.0, 0.0)] { + for start in [600, 2000, 4000, 7000] { + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0), ("shape", from)], 1); + let a = delays(&mut v, 0, start); + assert!(v.set_param("shape", to)); + let b = delays(&mut v, start, 8000); + assert!((b[0] - a[start - 1]).abs() < GLIDE_STEP, "{from} to {to} at {start}: jumped"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < GLIDE_STEP), "{from} to {to} at {start}: the glide moved too fast"); + assert!(b.iter().all(|d| *d > -0.05), "{from} to {to} at {start}: the delay went below 0"); + } + } + } + + /// After the input ends, the output falls silent within the reported tail, for every shape and + /// for a depth lowered just before the end, while the delay is still gliding down. + #[test] + fn vibrato_tail_covers_the_delay() { + for (rate, depth, shape, lower) in + [(1.0f32, 100.0f32, 1.0f32, false), (14.0, 50.0, 0.0, false), (1.0, 100.0, 1.0, true), (2.0, 100.0, 0.0, true)] + { + for len in [5000usize, 12000, 24000] { + let mut v = vibrato(&[("rate", rate), ("depth", depth), ("shape", shape)], 1); + let mut x = vec![0.5f32; len]; + v.process(&mut [&mut x]); + if lower { + assert!(v.set_param("depth", 0.0)); + } + let tail = v.tail_samples(); + let mut z = vec![0.0f32; 96_000]; + v.process(&mut [&mut z]); + let last = z.iter().rposition(|s| *s != 0.0).map_or(0, |i| i + 1); + assert!(last <= tail, "{rate} Hz {depth} ct shape {shape} lower {lower} len {len}: sound until {last} after a tail of {tail}"); + } + } + } + + /// At zero depth the input passes unchanged, a non-finite sample comes out as silence, and a + /// channel past the configured count is left alone. + #[test] + fn vibrato_depth_zero_non_finite_and_extra_channels() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut v = vibrato(&[("depth", 0.0), ("shape", 1.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + v.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut v = vibrato(&[("depth", 0.0)], 1); + let (mut l, mut r) = (x.clone(), x.clone()); + l[99] = f32::NAN; + l[200] = f32::INFINITY; + v.process(&mut [&mut l, &mut r]); + assert!(l[99] == 0.0 && l[200] == 0.0 && l.iter().all(|s| s.is_finite())); + assert_eq!(r, x); + let mut v = vibrato(&[("depth", 100.0)], 1); + let mut l = x.clone(); + l[99] = f32::NAN; + v.process(&mut [&mut l]); + assert!(l.iter().all(|s| s.is_finite())); + // Neighboring samples at the f32 limit with opposite signs stay finite. + let edge: Vec = (0..4800).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + for depth in [0.0, 100.0] { + let mut v = vibrato(&[("depth", depth)], 1); + let mut l = edge.clone(); + v.process(&mut [&mut l]); + assert!(l.iter().all(|s| s.is_finite()), "depth {depth}"); + if depth == 0.0 { + assert_eq!(l, edge); + } + } + } + + /// A block that leaves a channel out feeds it silence, so the channel holds none of its earlier + /// audio when it comes back. + #[test] + fn vibrato_feeds_channels_a_block_leaves_out_silence() { + let p = [("rate", 1.0), ("depth", 100.0), ("shape", 1.0)]; + let (mut left_out, mut silent) = (vibrato(&p, 2), vibrato(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 12_000, 0.0); + for v in [&mut left_out, &mut silent] { + let (mut l, mut r) = (x.clone(), x.clone()); + v.process(&mut [&mut l, &mut r]); + } + let mut l = x[..2000].to_vec(); + left_out.process(&mut [&mut l]); + let (mut l, mut r) = (x[..2000].to_vec(), vec![0.0f32; 2000]); + silent.process(&mut [&mut l, &mut r]); + let (mut la, mut ra) = (x[..4800].to_vec(), x[..4800].to_vec()); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (x[..4800].to_vec(), x[..4800].to_vec()); + silent.process(&mut [&mut lb, &mut rb]); + assert_eq!(ra, rb); + assert_eq!(la, lb); + } } diff --git a/crates/audio-dsp/tests/it/no_alloc.rs b/crates/audio-dsp/tests/it/no_alloc.rs index a62bd82a04..06ccbccd68 100644 --- a/crates/audio-dsp/tests/it/no_alloc.rs +++ b/crates/audio-dsp/tests/it/no_alloc.rs @@ -180,6 +180,50 @@ fn bitcrusher_does_not_allocate_while_processing() { assert!(l.iter().chain(&r).all(|v| v.is_finite())); } +/// The vibrato runs a voiced tone through 10,000 blocks of 480 frames, with its rate, depth and +/// shape changed between blocks, blocks that leave the second channel out, a NaN sample and a +/// reset, without one heap allocation. +#[test] +fn vibrato_does_not_allocate_while_processing() { + let Some(mut fx) = create_effect("vibrato", 48_000.0, 2) else { panic!("vibrato is not registered") }; + let tone: Vec = (0..480).map(|i| (0.4 * (std::f64::consts::TAU * 150.0 * i as f64 / 48_000.0).sin()) as f32).collect(); + let (mut l, mut r) = (tone.clone(), tone.clone()); + let info = allocation_counter::measure(|| { + for block in 0..10_000u32 { + match block % 500 { + 0 => { + fx.set_param("rate", 1.0 + (block / 500 % 10) as f32 * 1.4); + } + 100 => { + fx.set_param("shape", (block / 500 % 2) as f32); + } + 250 => { + fx.set_param("depth", 100.0); + } + 499 => { + fx.set_param("depth", 30.0); + } + _ => {} + } + if block == 7_777 { + fx.reset(); + } + l.copy_from_slice(&tone); + r.copy_from_slice(&tone); + if block == 5_000 { + l[100] = f32::NAN; + } + if (6_000..6_020).contains(&block) { + fx.process(&mut [&mut l]); + } else { + fx.process(&mut [&mut l, &mut r]); + } + } + }); + assert_eq!(info.count_total, 0, "{info:?}"); + assert!(l.iter().chain(&r).all(|v| v.is_finite())); +} + /// The tremolo runs a voiced tone through 10,000 blocks of 480 frames, with its rate, depth and /// shape changed between blocks, blocks that leave the second channel out, a NaN sample and a /// reset, without one heap allocation. From 37bba89716baeeedfc4c740a86a23007b4a0a7e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:37:15 -0800 Subject: [PATCH 13/33] audio-dsp: voice effects keep their state on empty blocks and stay finite at the f32 limit - Ring mod, tremolo and vibrato return early on an empty block, so a setting changed and restored before the next sample neither resets the resonator lines nor starts a glide. - Frequency Mod interpolates its delay read in f64, and the ring mod mix runs in f64, so neighboring samples near the f32 limit with opposite signs stay finite. - The vibrato docs say the delay is 0 at each cycle start only while no glide is in progress. - Noise suppression keeps frames that hold a sample of a mute shorter than a frame (down to one hop of zeros) out of the noise estimate. - The bitcrusher hold tests compare the whole sequence of hold starts, and the allocation tests assert each set_param result. --- crates/audio-dsp/README.md | 3 +- crates/audio-dsp/src/effects/character.rs | 139 +++++++++++++++++++--- crates/audio-dsp/src/effects/suppress.rs | 116 ++++++++++++++++-- crates/audio-dsp/tests/it/no_alloc.rs | 54 ++++----- 4 files changed, 257 insertions(+), 55 deletions(-) diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index 083b41bad3..6cf8520be3 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -23,7 +23,8 @@ and contains no `unsafe` code. neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits, or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. A vibrato that swings the pitch by up to 100 cents through a delay moved by a sine or triangle LFO adds - no latency either: the delay is 0 at the start of each cycle. + no latency either: the delay is 0 at the start of each cycle, except while it glides to new + settings. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index aeb24430cf..29b80076e3 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -22,8 +22,8 @@ //! sine, triangle or square LFO at `rate`. //! //! The vibrato (`vibrato`) reads the input through a delay that grows from 0 and shrinks back once -//! per cycle of a sine or triangle LFO at `rate`, so the pitch swings by up to `depth` cents. The -//! delay is 0 at the start of each cycle. +//! per cycle of a sine or triangle LFO at `rate`, so the pitch swings by up to `depth` cents. While +//! no glide to new settings is in progress, the delay is 0 at the start of each cycle. use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail, uni_sine, uni_tri}; use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; @@ -169,6 +169,10 @@ impl AudioEffect for RingMod { } fn process(&mut self, channels: &mut [&mut [f32]]) { let n = block_len(channels); + if n == 0 { + // No sample uses the new settings, so the lines keep their state. + return; + } let nch = channels.len().min(self.lines.len()); let effect = self.pv.idx("effect"); if effect != self.effect { @@ -217,7 +221,12 @@ impl AudioEffect for RingMod { let wet = match effect { 1 => { line.push(dry); - line.read(FM_BASE + swing * (1.0 + carrier)) + // The read interpolates in f64, as Vibrato's does, so neighboring samples + // near the f32 limit with opposite signs do not overflow. + let d = (FM_BASE + swing * (1.0 + carrier)).clamp(0.0, line.max_delay()); + let (di, frac) = (d.floor() as usize, f64::from(d - d.floor())); + let (a, b) = (f64::from(line.tap(di)), f64::from(line.tap(di + 1))); + (a + (b - a) * frac) as f32 } 2 | 3 => { let y = flush32(dry + sign * fb * line.read(back)); @@ -227,7 +236,9 @@ impl AudioEffect for RingMod { _ => dry * carrier, }; if ch < nch { - channels[ch][i] = dry + mix * (wet - dry); + // The mix runs in f64, so finite samples near the f32 limit stay finite. + let (dry, wet) = (f64::from(dry), f64::from(wet)); + channels[ch][i] = (dry + f64::from(mix) * (wet - dry)) as f32; } } } @@ -420,6 +431,10 @@ impl AudioEffect for Tremolo { } fn process(&mut self, channels: &mut [&mut [f32]]) { let n = block_len(channels); + if n == 0 { + // No sample uses the new settings, so no glide starts. + return; + } let nch = channels.len().min(self.channels); let rate = self.pv.v("rate"); let edge = self.edge_len(); @@ -452,10 +467,11 @@ impl AudioEffect for Tremolo { /// The swing is set so that the pitch falls by `depth` cents while the delay grows, and rises by a /// little less while it shrinks: the read moves at `1 -/+ d` samples per sample, with /// `d = 1 - 2^(-depth / 1200)`. A sine reaches `d` at its steepest point, and a triangle holds it -/// for each half of the cycle. At the start of each cycle the delay is 0. Rate takes effect from -/// the next sample with the phase kept. A change of Rate, Depth or Shape glides the delay from its -/// last value to the new curve, moving it by at most 1/32 sample per sample on top of the curve, so -/// the output neither clicks nor jumps in pitch. +/// for each half of the cycle. While no glide is in progress, the delay is 0 at the start of each +/// cycle. Rate takes effect from the next sample with the phase kept. A change of Rate, Depth or +/// Shape glides the delay from its last value to the new curve, moving it by at most 1/32 sample +/// per sample on top of the curve, so the output neither clicks nor jumps in pitch. A glide can run +/// past the start of a cycle, and the delay there stays above 0 until the glide ends. pub struct Vibrato { pv: ParamValues, sr: f32, @@ -549,6 +565,10 @@ impl AudioEffect for Vibrato { } fn process(&mut self, channels: &mut [&mut [f32]]) { let n = block_len(channels); + if n == 0 { + // No sample uses the new settings, so no glide starts. + return; + } let nch = channels.len().min(self.lines.len()); let rate = self.pv.v("rate"); let shape = self.pv.idx("shape"); @@ -764,6 +784,54 @@ mod tests { } } + /// An empty block does not take up a change of effect, so a resonator switched away from and + /// back before the next sample keeps its ring. + #[test] + fn an_empty_block_keeps_the_resonator_ring() { + let p = [("effect", 2.0), ("frequency", 500.0), ("resonance", 80.0)]; + let (mut r, mut still) = (ring(&p, 1), ring(&p, 1)); + for f in [&mut r, &mut still] { + let mut x = vec![0.0f32; 50]; + x[10] = 1.0; + f.process(&mut [&mut x]); + } + assert!(r.set_param("effect", 0.0)); + let mut empty: [f32; 0] = []; + r.process(&mut [&mut empty[..]]); + r.process(&mut []); + assert!(r.set_param("effect", 2.0)); + let (mut a, mut b) = (vec![0.0f32; 500], vec![0.0f32; 500]); + r.process(&mut [&mut a]); + still.process(&mut [&mut b]); + assert!(rms(&b) > 1e-3, "the ring has already died out"); + assert_eq!(a, b); + } + + /// Neighboring samples at the f32 limit with opposite signs come out finite from every effect + /// at every mix, through Frequency Mod's fractional and whole-sample reads, and a mix of 0 + /// passes them through unchanged. + #[test] + fn samples_at_the_f32_limit_stay_finite() { + let edge: Vec = (0..4800).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + for effect in 0..4 { + for mix in [0.0, 50.0, 100.0] { + let mut r = ring(&[("effect", effect as f32), ("frequency", 5000.0), ("mix", mix)], 1); + let mut y = edge.clone(); + r.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite()), "effect {effect}, mix {mix}"); + if mix == 0.0 { + assert_eq!(y, edge, "effect {effect}"); + } + } + } + // At 48 kHz Frequency Mod's first read is 50 samples back, a whole number, and the next + // ones fall between samples. + let mut r = ring(&[("effect", 1.0)], 1); + let mut y = edge.clone(); + r.process(&mut [&mut y]); + assert!(y[60..].iter().any(|v| v.abs() > 1e30 && v.abs() < f32::MAX), "no fractional read near the limit"); + } + fn crush(params: &[(&str, f32)], channels: usize) -> Bitcrusher { let mut c = Bitcrusher::new(SR, channels); for (id, v) in params { @@ -807,11 +875,16 @@ mod tests { let mut c = crush(&[("bits", 16.0), ("rate_divide", divide)], 1); let mut y = x.clone(); c.process(&mut [&mut y]); - let at = changes(&y); - for (k, w) in at.windows(2).enumerate() { - assert_eq!(w[1] - w[0], want[k % want.len()], "divide {divide}: hold {k}"); + let mut expected = vec![0usize]; + while let Some(&last) = expected.last() { + let next = last + want[(expected.len() - 1) % want.len()]; + if next >= x.len() { + break; + } + expected.push(next); } - assert!(at.iter().all(|&i| y[i] == x[i]), "divide {divide}: a hold does not start with the input"); + assert_eq!(changes(&y), expected, "divide {divide}"); + assert!(expected.iter().all(|&i| y[i] == x[i]), "divide {divide}: a hold does not start with the input"); } } @@ -823,11 +896,13 @@ mod tests { let mut a: Vec = (0..10).map(|i| (i + 1) as f32 / 1024.0).collect(); c.process(&mut [&mut a]); assert!(c.set_param("rate_divide", 2.0)); - let mut b: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + let input: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + let mut b = input.clone(); c.process(&mut [&mut b]); - let at = changes(&b); - assert_eq!(at[0], 0); - assert!(at.windows(2).all(|w| w[1] - w[0] == 2), "holds after the change: {at:?}"); + // `changes` counts the first sample whatever it holds, so the capture is checked apart. + assert_eq!(b[0], input[0], "the hold in progress was not cut short"); + assert_eq!(changes(&b), (0..30).step_by(2).collect::>()); + assert!((0..30).step_by(2).all(|i| b[i] == input[i])); } /// A held sample sounds for no longer than the tail reports after the input ends. @@ -1045,6 +1120,22 @@ mod tests { } } + /// An empty block does not take up a change of shape, so a shape changed and restored before + /// the next sample starts no glide. + #[test] + fn tremolo_empty_block_starts_no_glide() { + let p = [("rate", 5.0), ("depth", 100.0), ("shape", 0.0)]; + let (mut t, mut still) = (tremolo(&p, 1), tremolo(&p, 1)); + gains(&mut t, 1000); + gains(&mut still, 1000); + assert!(t.set_param("shape", 1.0)); + let mut empty: [f32; 0] = []; + t.process(&mut [&mut empty[..]]); + t.process(&mut []); + assert!(t.set_param("shape", 0.0)); + assert_eq!(gains(&mut t, 2000), gains(&mut still, 2000)); + } + fn vibrato(params: &[(&str, f32)], channels: usize) -> Vibrato { let mut v = Vibrato::new(SR, channels); for (id, x) in params { @@ -1158,6 +1249,22 @@ mod tests { } } + /// An empty block does not take up a change of depth, so a depth changed and restored before + /// the next sample starts no glide. + #[test] + fn vibrato_empty_block_starts_no_glide() { + let p = [("rate", 6.0), ("depth", 100.0)]; + let (mut v, mut still) = (vibrato(&p, 1), vibrato(&p, 1)); + delays(&mut v, 0, 1000); + delays(&mut still, 0, 1000); + assert!(v.set_param("depth", 10.0)); + let mut empty: [f32; 0] = []; + v.process(&mut [&mut empty[..]]); + v.process(&mut []); + assert!(v.set_param("depth", 100.0)); + assert_eq!(delays(&mut v, 1000, 4000), delays(&mut still, 1000, 4000)); + } + /// After the input ends, the output falls silent within the reported tail, for every shape and /// for a depth lowered just before the end, while the delay is still gliding down. #[test] diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs index e39b914807..8ade5ec475 100644 --- a/crates/audio-dsp/src/effects/suppress.rs +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -13,6 +13,8 @@ //! digital silence (a mute or a gate) drops the frames still waiting, and the four frames after //! it do not enter either, so no frame that shares a sample with the silence lowers the estimate //! and lets the noise pass when the sound resumes, wherever between two hops the silence ends. +//! A mute too short to fill a frame keeps every frame that holds a sample of it out too, down to +//! a run of zeros one hop long (64 samples at 48 kHz); a shorter run of zeros counts as sound. //! Nor does a frame more than 15 dB below the estimate, until such frames have lasted a whole //! search window without digital silence between them (the floor has really fallen). //! The noise power the gains are computed from falls at once and rises by at most 10 dB a @@ -22,7 +24,7 @@ //! so a voice that starts at once is not taken for the noise. use super::stft::{Pairing, Plan, Spectral, StftChannel, stream}; -use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, db_to_gain, flush32, param_plumbing}; +use crate::{AudioEffect, MAX_CHANNELS, ParamSpec, ParamValues, Unit, block_len, db_to_gain, flush32, param_plumbing}; /// Length of the minimum-statistics search, and the number of sub-windows it rotates through. const SEARCH_S: f32 = 1.5; @@ -107,6 +109,13 @@ struct Bins { since_zero: usize, /// Quiet frames in a row since the last frame of digital silence, up to a search window. quiet_run: usize, + /// Zero samples in a row up to the last sample, up to a hop. + zero_run: usize, + /// Samples since the last sample of a mute (a run of at least a hop of zeros), or `usize::MAX` + /// when there has been none since the last reset. + since_mute: usize, + /// Samples since the last frame. + since_frame: usize, } impl Bins { @@ -130,6 +139,9 @@ impl Bins { heard: 0, since_zero: 1, quiet_run: 0, + zero_run: 0, + since_mute: usize::MAX, + since_frame: 0, } } @@ -149,6 +161,30 @@ impl Bins { self.heard = 0; self.since_zero = 1; self.quiet_run = 0; + self.zero_run = 0; + self.since_mute = usize::MAX; + self.since_frame = 0; + } + + /// Takes one input sample before the STFT does, to find mutes too short to give a frame of + /// digital silence. Once `hop` zeros run in a row, the frame still waiting that holds the first + /// of them leaves the queue, and so does every later frame that holds a sample of the run. + fn sample(&mut self, x: f32, hop: usize) { + self.since_frame += 1; + self.zero_run = if x == 0.0 { (self.zero_run + 1).min(hop) } else { 0 }; + if self.zero_run < hop { + self.since_mute = self.since_mute.saturating_add(1); + return; + } + if self.since_mute != 0 { + // The run has just reached a hop. It started `hop - 1` samples ago, so of the frames + // waiting only the newest can hold it: when it ended less than a hop ago. + if self.queued > 0 && self.since_frame < hop { + self.queue_ok[(self.head + self.queued - 1) % OVERLAP] = false; + } + self.quiet_run = 0; + } + self.since_mute = 0; } /// Noise power of bin `k` for the frame last processed: the smallest smoothed power of the @@ -198,6 +234,7 @@ impl Bins { /// state as it is and repeats the last gains. fn frame(&mut self, re: &[f32], im: &[f32], c: &Coefs, out: &mut [f32]) { let bins = self.power.len(); + self.since_frame = 0; let finite = re.iter().zip(im).fold(true, |ok, (a, b)| ok & (a * a + b * b).is_finite()); if finite { for k in 0..bins { @@ -221,7 +258,8 @@ impl Bins { self.queue[at * bins + k] = re[k] * re[k] + im[k] * im[k]; } self.queue_total[at] = total; - self.queue_ok[at] = self.since_zero > OVERLAP; + // A frame holds the last STFT size of samples, `2 * (bins - 1)`. + self.queue_ok[at] = self.since_zero > OVERLAP && self.since_mute >= 2 * (bins - 1); self.queued += 1; } // The floor moves from 1 to `c.floor` (in dB) over the first search window of sound. @@ -262,6 +300,8 @@ pub struct NoiseSuppression { smoothed: Vec, coefs: Coefs, sample_rate: f32, + /// Samples since the last frame, the same in every channel. + pos: usize, } impl NoiseSuppression { @@ -282,6 +322,7 @@ impl NoiseSuppression { smoothed: vec![1.0; bins], coefs: Coefs { floor: 1.0, smooth: 0.0, priori: 0.0, sub_frames: 1, window: SUBWINDOWS, rise: 1.0 }, sample_rate, + pos: 0, }; s.apply_params(true); s @@ -313,6 +354,7 @@ impl AudioEffect for NoiseSuppression { fn reset(&mut self) { self.stft.iter_mut().for_each(StftChannel::reset); self.bins.iter_mut().for_each(Bins::reset); + self.pos = 0; } fn process(&mut self, channels: &mut [&mut [f32]]) { let len = block_len(channels); @@ -322,22 +364,38 @@ impl AudioEffect for NoiseSuppression { c[..len].iter_mut().for_each(|v| *v = flush32(*v)); } let (n, hop, coefs) = (self.n, self.hop, self.coefs); - let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); let scale = 1.0 / (n as f32 * 2.0); let plan = Plan { hop, scale, pairing: Pairing::SynthesisOnly }; - stream(&mut self.stft, &mut self.spec, channels, len, plan, &mut |ch, _, re, im| { - bins[ch].frame(re, im, &coefs, smoothed); - for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { - *r *= g; - *i *= g; + // The block runs in pieces that end at the next frame, so each channel's noise estimate + // takes every sample of a frame before the STFT frames it. + let mut start = 0; + while start < len { + let end = len.min(start + hop - self.pos); + for (b, c) in self.bins.iter_mut().zip(channels.iter()).take(nch) { + c[start..end].iter().for_each(|&x| b.sample(x, hop)); } - }); + let mut piece: [&mut [f32]; MAX_CHANNELS] = std::array::from_fn(|_| <&mut [f32]>::default()); + for (p, c) in piece.iter_mut().zip(channels.iter_mut()).take(nch) { + *p = &mut c[start..end]; + } + let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); + stream(&mut self.stft, &mut self.spec, &mut piece[..nch], end - start, plan, &mut |ch, _, re, im| { + bins[ch].frame(re, im, &coefs, smoothed); + for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { + *r *= g; + *i *= g; + } + }); + self.pos = (self.pos + end - start) % hop; + start = end; + } // A channel the block leaves out is fed silence, so it holds none of its earlier audio // when it comes back. let half = n / 2 + 1; - let spec = &mut self.spec; - for (st, b) in self.stft.iter_mut().zip(bins.iter_mut()).skip(nch) { + let (spec, smoothed) = (&mut self.spec, &mut self.smoothed); + for (st, b) in self.stft.iter_mut().zip(self.bins.iter_mut()).skip(nch) { for _ in 0..len { + b.sample(0.0, hop); st.tick(0.0, hop, &mut |input, out| { spec.analyze(input); b.frame(&spec.re[..half], &spec.im[..half], &coefs, smoothed); @@ -616,6 +674,42 @@ mod tests { } } + /// A mute too short to fill a frame, from one hop long up, keeps the frames that hold a sample + /// of it out of the estimate too, wherever it starts and ends between two hops. + #[test] + fn frames_that_touch_a_short_mute_stay_out_of_the_estimate() { + for offset in [0usize, 17, 40, 63] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut x = white(31, SR as usize / 2, 0.05); + let mutes = [(192 + offset, 256 + offset), (6000 + offset, 6100 + offset), (12_000 + offset, 12_200 + offset)]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + // One hop per block, so each block ends with a frame. A frame enters the estimate when + // the frame `OVERLAP` after it arrives, which is when `heard` grows. + let mut entered = Vec::new(); + for (k, chunk) in x.chunks(hop).enumerate() { + let heard = s.bins[0].heard; + let mut y = chunk.to_vec(); + s.process(&mut [&mut y]); + if s.bins[0].heard > heard { + entered.push(k + 1 - OVERLAP); + } + } + let frames = x.len() / hop; + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < s.coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), s.bins[0].heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(s.bins[0].heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", s.bins[0].heard); + } + } + /// Quiet stretches that a mute separates do not add up to a search window: the estimate stays /// at the noise before them, and falls only after a whole search window of quiet in a row. #[test] diff --git a/crates/audio-dsp/tests/it/no_alloc.rs b/crates/audio-dsp/tests/it/no_alloc.rs index 06ccbccd68..2b59810a6f 100644 --- a/crates/audio-dsp/tests/it/no_alloc.rs +++ b/crates/audio-dsp/tests/it/no_alloc.rs @@ -14,20 +14,20 @@ fn voice_pitch_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("semitones", (block / 500 % 7) as f32 * 4.0 - 12.0); + assert!(fx.set_param("semitones", (block / 500 % 7) as f32 * 4.0 - 12.0)); } 100 => { - fx.set_param("formant_follow", 1.0); + assert!(fx.set_param("formant_follow", 1.0)); } 250 => { - fx.set_param("cents", -35.0); + assert!(fx.set_param("cents", -35.0)); } 400 => { - fx.set_param("formant_follow", 0.0); + assert!(fx.set_param("formant_follow", 0.0)); } 499 => { - fx.set_param("semitones", 0.0); - fx.set_param("cents", 0.0); + assert!(fx.set_param("semitones", 0.0)); + assert!(fx.set_param("cents", 0.0)); } _ => {} } @@ -60,10 +60,10 @@ fn voice_formant_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("semitones", (block / 500 % 7) as f32 * 4.0 - 12.0); + assert!(fx.set_param("semitones", (block / 500 % 7) as f32 * 4.0 - 12.0)); } 499 => { - fx.set_param("semitones", 0.0); + assert!(fx.set_param("semitones", 0.0)); } _ => {} } @@ -105,10 +105,10 @@ fn noise_suppression_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("reduction", (block / 500 % 5) as f32 * 10.0); + assert!(fx.set_param("reduction", (block / 500 % 5) as f32 * 10.0)); } 499 => { - fx.set_param("reduction", 0.0); + assert!(fx.set_param("reduction", 0.0)); } _ => {} } @@ -148,16 +148,16 @@ fn bitcrusher_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("bits", 1.0 + (block / 500 % 16) as f32); + assert!(fx.set_param("bits", 1.0 + (block / 500 % 16) as f32)); } 100 => { - fx.set_param("rate_divide", 1.0 + (block / 500 % 7) as f32 * 7.5); + assert!(fx.set_param("rate_divide", 1.0 + (block / 500 % 7) as f32 * 7.5)); } 250 => { - fx.set_param("mix", 40.0); + assert!(fx.set_param("mix", 40.0)); } 499 => { - fx.set_param("mix", 100.0); + assert!(fx.set_param("mix", 100.0)); } _ => {} } @@ -192,16 +192,16 @@ fn vibrato_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("rate", 1.0 + (block / 500 % 10) as f32 * 1.4); + assert!(fx.set_param("rate", 1.0 + (block / 500 % 10) as f32 * 1.4)); } 100 => { - fx.set_param("shape", (block / 500 % 2) as f32); + assert!(fx.set_param("shape", (block / 500 % 2) as f32)); } 250 => { - fx.set_param("depth", 100.0); + assert!(fx.set_param("depth", 100.0)); } 499 => { - fx.set_param("depth", 30.0); + assert!(fx.set_param("depth", 30.0)); } _ => {} } @@ -236,16 +236,16 @@ fn tremolo_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("rate", 0.1 + (block / 500 % 10) as f32 * 2.0); + assert!(fx.set_param("rate", 0.1 + (block / 500 % 10) as f32 * 2.0)); } 100 => { - fx.set_param("shape", (block / 500 % 3) as f32); + assert!(fx.set_param("shape", (block / 500 % 3) as f32)); } 250 => { - fx.set_param("depth", 100.0); + assert!(fx.set_param("depth", 100.0)); } 499 => { - fx.set_param("depth", 30.0); + assert!(fx.set_param("depth", 30.0)); } _ => {} } @@ -280,17 +280,17 @@ fn ring_mod_does_not_allocate_while_processing() { for block in 0..10_000u32 { match block % 500 { 0 => { - fx.set_param("effect", (block / 500 % 4) as f32); + assert!(fx.set_param("effect", (block / 500 % 4) as f32)); } 100 => { - fx.set_param("mod_source", (block / 500 % 3) as f32); + assert!(fx.set_param("mod_source", (block / 500 % 3) as f32)); } 250 => { - fx.set_param("frequency", 30.0 + (block / 500 % 5) as f32 * 400.0); - fx.set_param("mod_depth", 60.0); + assert!(fx.set_param("frequency", 30.0 + (block / 500 % 5) as f32 * 400.0)); + assert!(fx.set_param("mod_depth", 60.0)); } 499 => { - fx.set_param("mod_depth", 0.0); + assert!(fx.set_param("mod_depth", 0.0)); } _ => {} } From 3837c89fe4bfc7933f901d278854b50e649bcc66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:49:20 -0800 Subject: [PATCH 14/33] audio-dsp: tremolo, noise_suppression and voice_pitch handle review edge cases - tremolo: an empty block returns before it looks at the shape, so a shape that no sample used does not restart a glide in progress. - noise_suppression: digital silence is a run of at least one hop of zero samples (64 at 48 kHz). Every frame that shares a sample with such a run stays out of the noise estimate, also when the run is shorter than a frame and no frame holds only zeros. - voice_pitch: a channel the block leaves out runs through the pitch delay and the Keep Formants stage as if the block held silence for it, so a short omission gives the same output as a block of zeros. - The bitcrusher's shorter-hold test compares the output with the expected two-sample holds instead of only the distances between changes. --- crates/audio-dsp/src/effects/character.rs | 32 +++++- crates/audio-dsp/src/effects/stft.rs | 4 + crates/audio-dsp/src/effects/suppress.rs | 126 ++++++++++++++++------ crates/audio-dsp/src/effects/voice.rs | 39 ++++++- 4 files changed, 159 insertions(+), 42 deletions(-) diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index 6b323a2c14..6644517fc2 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -412,6 +412,10 @@ impl AudioEffect for Tremolo { } fn process(&mut self, channels: &mut [&mut [f32]]) { let n = block_len(channels); + if n == 0 { + // No sample used the current settings, so a glide in progress goes on unchanged. + return; + } let nch = channels.len().min(self.channels); let rate = self.pv.v("rate"); let edge = self.edge_len(); @@ -732,11 +736,12 @@ mod tests { let mut a: Vec = (0..10).map(|i| (i + 1) as f32 / 1024.0).collect(); c.process(&mut [&mut a]); assert!(c.set_param("rate_divide", 2.0)); - let mut b: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + let x: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + let mut b = x.clone(); c.process(&mut [&mut b]); - let at = changes(&b); - assert_eq!(at[0], 0); - assert!(at.windows(2).all(|w| w[1] - w[0] == 2), "holds after the change: {at:?}"); + // The first sample after the change is captured, and each capture is held for two. + let want: Vec = (0..x.len()).map(|i| x[i - i % 2]).collect(); + assert_eq!(b, want); } /// A held sample sounds for no longer than the tail reports after the input ends. @@ -905,6 +910,25 @@ mod tests { assert!((b[0] - want[0]).abs() > 0.2, "{} {}", b[0], want[0]); } + /// A shape that only an empty block saw does not restart a glide in progress: the glide goes + /// on as if the shape had not changed. + #[test] + fn tremolo_empty_block_keeps_the_glide() { + let glide = (0.02 * SR) as usize; + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + let mut s = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + for fx in [&mut t, &mut s] { + gains(fx, 2000); + assert!(fx.set_param("shape", 2.0)); + gains(fx, 100); + } + assert!(t.set_param("shape", 1.0)); + let mut empty: [f32; 0] = []; + t.process(&mut [&mut empty[..]]); + assert!(t.set_param("shape", 2.0)); + assert_eq!(gains(&mut t, 2 * glide), gains(&mut s, 2 * glide)); + } + /// A new rate moves the square's edges to a new share of the cycle. Changed just before an /// edge, from 0.1 Hz (where the edge is still ahead) to 20 Hz (where the phase is inside it), /// the gain glides instead of jumping. diff --git a/crates/audio-dsp/src/effects/stft.rs b/crates/audio-dsp/src/effects/stft.rs index 2d5e949d05..f82e268956 100644 --- a/crates/audio-dsp/src/effects/stft.rs +++ b/crates/audio-dsp/src/effects/stft.rs @@ -20,6 +20,10 @@ impl StftChannel { self.output.iter_mut().for_each(|v| *v = 0.0); self.pos = 0; } + /// Samples taken since the last frame: the next frame comes `hop - pos()` samples on. + pub(crate) fn pos(&self) -> usize { + self.pos + } /// Push one sample and pop one output sample. Every `hop` samples `frame` is called with the /// last `n` input samples and must write an `n`-sample (windowed) frame that is overlap-added. #[inline] diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs index fe9236291d..a09db363c2 100644 --- a/crates/audio-dsp/src/effects/suppress.rs +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -9,10 +9,12 @@ //! 1984), held at or above the floor that `reduction` sets, and averaged with its neighbors. At a //! reduction of 0 every gain is 1 and the effect is a plain delay. //! -//! A frame enters the noise estimate only after the next four frames have arrived. A frame of -//! digital silence (a mute or a gate) drops the frames still waiting, and the four frames after -//! it do not enter either, so no frame that shares a sample with the silence lowers the estimate -//! and lets the noise pass when the sound resumes, wherever between two hops the silence ends. +//! A frame enters the noise estimate only after the next four frames have arrived. Digital +//! silence (a mute or a gate) is a run of at least one hop of zero samples, 64 at 48 kHz +//! (1.3 ms). A frame that shares a sample with it drops the frames still waiting and does not +//! enter either, so no frame that shares a sample with the silence lowers the estimate and lets +//! the noise pass when the sound resumes, wherever between two hops the silence starts and ends. +//! A run of zeros shorter than a hop is taken as sound. //! Nor does a frame more than 15 dB below the estimate, until such frames have lasted a whole //! search window without digital silence between them (the floor has really fallen). //! The noise power the gains are computed from falls at once and rises by at most 10 dB a @@ -112,6 +114,12 @@ struct Bins { /// Frames with sound since the last frame of digital silence, up to `OVERLAP + 1`. It starts /// at 1: the zeros the STFT starts with end on a hop boundary, so `OVERLAP` frames clear them. since_zero: usize, + /// Zero input samples in a row, up to the last sample taken. + zero_run: usize, + /// Input samples since the last one in a run of at least a hop of zeros. + since_mute: usize, + /// Whether the next frame shares a sample with a run of at least a hop of zeros. + mute: bool, /// Quiet frames in a row since the last frame of digital silence, up to a search window. quiet_run: usize, /// Whether `noise` has been set from a first estimate since the last reset. @@ -140,12 +148,23 @@ impl Bins { started: false, heard: 0, since_zero: 1, + zero_run: 0, + since_mute: usize::MAX, + mute: false, quiet_run: 0, seeded: false, scratch: vec![0.0; bins], } } + /// Takes one input sample, and returns whether a frame that ends on it shares a sample with a + /// run of at least `hop` zeros. A frame holds the last `n` samples. + fn take(&mut self, x: f32, hop: usize) -> bool { + self.zero_run = if x == 0.0 { self.zero_run.saturating_add(1) } else { 0 }; + self.since_mute = if self.zero_run >= hop { 0 } else { self.since_mute.saturating_add(1) }; + self.since_mute < 2 * (self.power.len() - 1) + } + fn reset(&mut self) { self.power.fill(0.0); self.min.fill(f32::INFINITY); @@ -161,6 +180,9 @@ impl Bins { self.started = false; self.heard = 0; self.since_zero = 1; + self.zero_run = 0; + self.since_mute = usize::MAX; + self.mute = false; self.quiet_run = 0; self.seeded = false; } @@ -218,12 +240,15 @@ impl Bins { self.est[k] = (0..SUBWINDOWS).fold(self.min[k], |m, u| m.min(self.ring[u * bins + k])); } let total = (0..bins).map(|k| re[k] * re[k] + im[k] * im[k]).sum::(); - if total == 0.0 { - // Digital silence: the frames still waiting share a sample with it, and so do the - // next `OVERLAP - 1` frames, or the next `OVERLAP` when the silence ends between + if self.mute || total == 0.0 { + // Digital silence: the frames still waiting may share a sample with it. `take` + // marks every later frame that shares a sample with a run of zeros, so the first + // unmarked frame after it holds none of the run. A frame of zeros that `take` did + // not mark (the zeros the STFT starts with, or power below the f32 range) shares + // a sample with the next `OVERLAP - 1` frames, or `OVERLAP` when it ends between // two hops. A quiet run ends here too. self.queued = 0; - self.since_zero = 0; + self.since_zero = if self.mute { OVERLAP } else { 0 }; self.quiet_run = 0; } else { self.since_zero = (self.since_zero + 1).min(OVERLAP + 1); @@ -347,32 +372,55 @@ impl AudioEffect for NoiseSuppression { c[..len].iter_mut().for_each(|v| *v = flush32(*v)); } let (n, hop, coefs) = (self.n, self.hop, self.coefs); - let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); let scale = 1.0 / (n as f32 * 2.0); let plan = Plan { hop, scale, pairing: Pairing::SynthesisOnly }; - stream(&mut self.stft, &mut self.spec, channels, len, plan, &mut |ch, _, re, im| { - bins[ch].frame(re, im, &coefs, smoothed); - for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { - *r *= g; - *i *= g; - } - }); - // A channel the block leaves out is fed silence, so it holds none of its earlier audio - // when it comes back. let half = n / 2 + 1; - let spec = &mut self.spec; - for (st, b) in self.stft.iter_mut().zip(bins.iter_mut()).skip(nch) { - for _ in 0..len { - st.tick(0.0, hop, &mut |input, out| { - spec.analyze(input); - b.frame(&spec.re[..half], &spec.im[..half], &coefs, smoothed); - for k in 0..half { - spec.re[k] *= smoothed[k]; - spec.im[k] *= smoothed[k]; + // Every channel takes a frame on the same samples, at most one in `hop` samples. The block + // runs in pieces of up to `hop` samples, and the input samples of each piece are taken + // before the STFT replaces them with output, marking the frame that ends on one of them. + let mut start = 0; + while start < len { + let end = (start + hop).min(len); + // The STFT takes its next frame `hop - pos` samples on. + let at = start + hop - 1 - self.stft[0].pos(); + for (c, b) in self.bins.iter_mut().enumerate() { + for i in start..end { + // A channel the block leaves out is fed silence. + let mute = b.take(if c < nch { channels[c][i] } else { 0.0 }, hop); + if i == at { + b.mute = mute; } - spec.synthesize_add(out, scale); - }); + } } + let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); + let mut piece: [&mut [f32]; crate::MAX_CHANNELS] = std::array::from_fn(|_| <&mut [f32]>::default()); + for (p, c) in piece.iter_mut().zip(channels.iter_mut()).take(nch) { + *p = &mut c[start..end]; + } + stream(&mut self.stft, &mut self.spec, &mut piece[..nch], end - start, plan, &mut |ch, _, re, im| { + bins[ch].frame(re, im, &coefs, smoothed); + for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { + *r *= g; + *i *= g; + } + }); + // A channel the block leaves out is fed silence, so it holds none of its earlier audio + // when it comes back. + let spec = &mut self.spec; + for (st, b) in self.stft.iter_mut().zip(bins.iter_mut()).skip(nch) { + for _ in start..end { + st.tick(0.0, hop, &mut |input, out| { + spec.analyze(input); + b.frame(&spec.re[..half], &spec.im[..half], &coefs, smoothed); + for k in 0..half { + spec.re[k] *= smoothed[k]; + spec.im[k] *= smoothed[k]; + } + spec.synthesize_add(out, scale); + }); + } + } + start = end; } // A huge finite input can overflow the inverse FFT. for c in channels.iter_mut().take(nch) { @@ -594,8 +642,8 @@ mod tests { /// No frame that shares a sample with digital silence enters the noise estimate: not the /// frames that run into a mute, nor those that run out of it, whether or not the mute starts - /// or ends on a frame boundary. At most two frames per mute that hold no silence are dropped - /// with them. + /// or ends on a frame boundary, and also for a mute shorter than a frame. At most `OVERLAP` + /// frames per mute that hold no silence are dropped with them. #[test] fn frames_that_touch_a_mute_stay_out_of_the_estimate() { let s = suppressor(24.0); @@ -608,7 +656,15 @@ mod tests { let mut lane = StftChannel::new(n); let len = SR as usize; let mut x = white(29, len, 0.05); - let mutes = [(SR as usize * 3 / 10 + offset, SR as usize * 4 / 10 + offset), (SR as usize * 7 / 10 + offset, SR as usize * 8 / 10)]; + // The last mute is half a frame long and starts one sample after a hop, so no frame + // holds only zeros. + let short = SR as usize / 2 + 1; + let mutes = [ + (SR as usize * 3 / 10 + offset, SR as usize * 4 / 10 + offset), + (SR as usize * 7 / 10 + offset, SR as usize * 8 / 10), + (short, short + n / 2), + ]; + assert_eq!(short % hop, 1); for &(a, b) in &mutes { x[a..b].fill(0.0); } @@ -618,8 +674,12 @@ mod tests { // `heard` grows. let mut entered = Vec::new(); for &v in &x { + // As `NoiseSuppression::process` does, the sample is taken before the frame that + // ends on it. + let mute = bins.take(v, hop); lane.tick(v, hop, &mut |input, _| { spec.analyze(input); + bins.mute = mute; let heard = bins.heard; bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); frames += 1; @@ -637,7 +697,7 @@ mod tests { for &j in &entered { assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); } - assert!(bins.heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", bins.heard); + assert!(bins.heard + OVERLAP * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", bins.heard); } } diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs index 311fdf362a..01016a8592 100644 --- a/crates/audio-dsp/src/effects/voice.rs +++ b/crates/audio-dsp/src/effects/voice.rs @@ -478,7 +478,10 @@ impl AudioEffect for VoicePitch { // While Keep Formants is off and faded out, the stage's frames copy the shifted voice, // so switching it on crossfades from a delayed copy instead of from silence. let warp = if mix > 0.0 { back } else { 1.0 }; - for (c, (line, io)) in self.lines.iter().zip(channels.iter_mut()).enumerate() { + // A channel the block leaves out runs as if the block held silence for it, so the + // formant stage takes the same input as from a block of zeros; only its output is + // not written. + for (c, line) in self.lines.iter().enumerate() { let dry = line[(self.pos + dry_at) & self.mask] as f64; let y = if t.wet == 0.0 { dry @@ -492,10 +495,9 @@ impl AudioEffect for VoicePitch { // The stage's output is `n` samples later than `y`, so a switch fades one out // before the other comes in instead of mixing them. let out = if mix < 0.5 { (1.0 - 2.0 * mix) * y } else { (2.0 * mix - 1.0) * z as f64 }; - io[i] = out.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; - } - for c in ch..self.lines.len() { - self.follow.tick(c, 0.0, warp); + if let Some(io) = channels.get_mut(c) { + io[i] = out.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + } } self.pos = (self.pos + 1) & self.mask; } @@ -1217,6 +1219,33 @@ mod tests { } } + /// A block that leaves a channel out gives the same output, once the channel is back, as a + /// block that holds silence for it: with Keep Formants on, an impulse just before the block + /// still sounds afterward. + #[test] + fn a_channel_left_out_of_a_block_runs_as_silence() { + let mut out = Vec::new(); + for omit in [false, true] { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("formant_follow", 1.0)); + p.reset(); + let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]); + r[479] = 1.0; + p.process(&mut [&mut l, &mut r]); + let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]); + if omit { + p.process(&mut [&mut l]); + } else { + p.process(&mut [&mut l, &mut r]); + } + let (mut l, mut r) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + p.process(&mut [&mut l, &mut r]); + assert!(r.iter().any(|v| *v != 0.0), "omit {omit}: the impulse did not sound"); + out.push((l, r)); + } + assert!(out[0] == out[1], "leaving the channel out changed the output"); + } + /// The tracker finds a voice's period down to 70 Hz and reports nothing for silence. #[test] fn the_tracker_reaches_70_hz() { From f825dd1b3f158a79485c7899710f75a46de34349 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:27:25 -0800 Subject: [PATCH 15/33] craft-testkit: font tests join the crate's one test binary tests/fonts.rs moves to tests/it/fonts.rs and tests/it/main.rs adds it as a module, so craft-testkit keeps a single integration test binary. --- crates/testkit/tests/{ => it}/fonts.rs | 0 crates/testkit/tests/it/main.rs | 1 + 2 files changed, 1 insertion(+) rename crates/testkit/tests/{ => it}/fonts.rs (100%) diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/it/fonts.rs similarity index 100% rename from crates/testkit/tests/fonts.rs rename to crates/testkit/tests/it/fonts.rs diff --git a/crates/testkit/tests/it/main.rs b/crates/testkit/tests/it/main.rs index f686c5c39d..6d0f5f8080 100644 --- a/crates/testkit/tests/it/main.rs +++ b/crates/testkit/tests/it/main.rs @@ -1,4 +1,5 @@ //! The crate's integration tests, linked into one test binary. +mod fonts; mod guards; mod source_limits; From 3a4427a57ffdfda382b3493faa186e6de84bd757 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:07:39 -0800 Subject: [PATCH 16/33] craft-testkit: close waits for the rest of the MCP child's stderr after it exits close waited for the stderr thread only as long as close_grace, so with a short or zero grace the bytes still in the pipe when the child exited could be missing from CloseOutcome::stderr. It now waits up to 5 s after the child exits, and only a process that keeps the child's stderr open waits that long. --- crates/testkit/README.md | 2 +- crates/testkit/src/mcp.rs | 11 +++++++++-- crates/testkit/tests/mcp_child/child.rs | 19 ++++++++++++++++++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index c2a22b83ab..e09f4db570 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -251,7 +251,7 @@ The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The | `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. | | `notify(method, params)` | Sends a notification, which has no id and gets no reply. | | `take_notifications()` | Returns the notifications kept so far without waiting. | -| `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. | +| `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. After the child exits, it waits up to 5 s for the rest of stderr to be read. | While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error, close the connection and stop the child; later calls return `Closed`. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics. diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index de13650cdc..b9418818ce 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -41,6 +41,10 @@ const READ_QUEUE: usize = 4; const WRITE_QUEUE: usize = 64; /// How often [`McpChild::close`] checks whether the child has exited. const EXIT_POLL: Duration = Duration::from_millis(10); +/// How long [`McpChild::close`] waits, after the child has exited, for the stderr thread to read to +/// the end of stderr. Only a process that keeps the child's stderr open after the child exits makes +/// it wait this long. +const STDERR_DRAIN: Duration = Duration::from_secs(5); /// Bytes of an unreadable stdout line quoted in a protocol error. const PREVIEW: usize = 80; /// The JSON-RPC error code for a method the client does not offer. @@ -250,7 +254,10 @@ pub struct CloseOutcome { /// The child was stopped because it did not exit within [`McpLimits::close_grace`], or an /// earlier failure stopped it. pub forced: bool, - /// The last [`McpLimits::stderr_tail_bytes`] bytes the child wrote on stderr. + /// The last [`McpLimits::stderr_tail_bytes`] bytes the child wrote on stderr. After the child + /// exits, [`McpChild::close`] waits up to 5 s for the rest of stderr to be read, whatever + /// [`McpLimits::close_grace`] is. A process the child started that keeps stderr open past that + /// leaves the bytes read so far. pub stderr: Vec, } @@ -666,7 +673,7 @@ impl McpChild { }; let stderr = match &self.stderr { Some(tail) => { - let _ = tail.done.recv_timeout(grace); + let _ = tail.done.recv_timeout(STDERR_DRAIN); tail.copy() } None => Vec::new(), diff --git a/crates/testkit/tests/mcp_child/child.rs b/crates/testkit/tests/mcp_child/child.rs index 254488c3e7..c600e47a10 100644 --- a/crates/testkit/tests/mcp_child/child.rs +++ b/crates/testkit/tests/mcp_child/child.rs @@ -20,6 +20,7 @@ const TESTS: &[(&str, Test)] = &[ ("child_exits_before_initialize", child_exits_before_initialize), ("stderr_flood_does_not_block", stderr_flood_does_not_block), ("close_forces_and_reaps_unresponsive_child", close_forces_and_reaps_unresponsive_child), + ("close_keeps_stderr_written_before_exit", close_keeps_stderr_written_before_exit), ]; pub fn run() -> ExitCode { @@ -53,11 +54,17 @@ pub fn run() -> ExitCode { /// Runs as the child: `server` answers `initialize` with the version asked for and every tool call /// with `ECHO_VAR`, and exits when its stdin closes; `flood` also writes `FLOOD` bytes and `END` on /// stderr before each reply; `silent` reads and never answers; `stubborn` answers but does not -/// exit when its stdin closes; `exit` exits at once with code 3. +/// exit when its stdin closes; `exit` exits at once with code 3; `goodbye` writes `FLOOD` bytes and +/// `BYE` on stderr and exits without reading. fn serve(mode: &str) -> ExitCode { if mode == "exit" { return ExitCode::from(3); } + if mode == "goodbye" { + let mut err = std::io::stderr(); + let written = err.write_all(&vec![b'e'; FLOOD]).and_then(|()| err.write_all(b"BYE")); + return if written.is_ok() { ExitCode::SUCCESS } else { ExitCode::FAILURE }; + } let stdin = std::io::stdin(); let mut out = std::io::stdout(); for line in stdin.lock().lines() { @@ -159,3 +166,13 @@ fn close_forces_and_reaps_unresponsive_child() -> Result<(), String> { let out = c.close().map_err(|e| e.to_string())?; check(out.forced && out.status.is_some_and(|s| !s.success()), || format!("close: {out:?}")) } + +fn close_keeps_stderr_written_before_exit() -> Result<(), String> { + let limits = McpLimits { stderr_tail_bytes: 4096, close_grace: Duration::ZERO, ..McpLimits::default() }; + let mut c = start("goodbye", limits)?; + // The child's stdout ends when it exits, after its stderr is written. + let err = c.initialize(PROTOCOL_VERSION).err(); + check(matches!(err, Some(McpError::Ended | McpError::Io { .. })), || format!("initialize: {err:?}"))?; + let out = c.close().map_err(|e| e.to_string())?; + check(out.stderr.len() == 4096 && out.stderr.ends_with(b"eeeBYE"), || format!("kept {} bytes of stderr", out.stderr.len())) +} From 6db18d908969c39d9fcc179b774eb1861bec9030 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:13:19 -0800 Subject: [PATCH 17/33] craft-testkit: connect and close docs say when the MCP reading thread stops --- crates/testkit/README.md | 2 +- crates/testkit/src/mcp.rs | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index e09f4db570..89d5e782cb 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -241,7 +241,7 @@ Changes from `craft-media-testkit`'s `hammer`: The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The module is built on every target except `wasm32`, and it opens no network connection. -`McpChild::spawn(path, args, env)` starts an MCP server program with its stdin and stdout piped. The variables in `env` are set for the child only; the test process's environment is not changed. `McpChild::connect(reader, writer, limits)` talks to a server that runs in the test process. Each message is one line of JSON-RPC 2.0, as the [MCP stdio transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) describes. +`McpChild::spawn(path, args, env)` starts an MCP server program with its stdin and stdout piped. The variables in `env` are set for the child only; the test process's environment is not changed. `McpChild::connect(reader, writer, limits)` talks to a server that runs in the test process; its reading thread stops when the server drops its end of `reader`, or at the next line the server writes after `close()`. Each message is one line of JSON-RPC 2.0, as the [MCP stdio transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) describes. | Call | What it does | |---|---| diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index b9418818ce..8021914dc4 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -466,7 +466,9 @@ impl McpChild { } /// Connects to a server that reads `writer` and writes `reader`, such as one running on a - /// thread of the test. [`McpLimits::stderr_tail_bytes`] is not used. + /// thread of the test. [`McpLimits::stderr_tail_bytes`] is not used. A thread reads `reader` + /// until it ends, so the server must drop its end of `reader` for that thread to stop; after + /// [`McpChild::close`] or a drop, the thread also stops at the next line the server writes. pub fn connect(reader: impl Read + Send + 'static, writer: impl Write + Send + 'static, limits: McpLimits) -> Result { limits.validate()?; Self::start(reader, writer, limits) @@ -656,7 +658,8 @@ impl McpChild { /// it, and returns its exit status. For a connection made with [`McpChild::connect`], it ends /// the writer thread, which drops the writer once the lines already queued are written, and /// returns no status without waiting for that thread. A writer blocked on a server that has - /// stopped reading stays with the thread until the server drops its reading end. + /// stopped reading stays with the thread until the server drops its reading end, and the thread + /// reading `reader` stays blocked until the server drops its writing end or writes a line. pub fn close(mut self) -> Result { self.writer = None; let grace = self.limits.close_grace; From 0265dd5f52bd4a84ce3e74aad18d73d175b51e29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:15:05 -0800 Subject: [PATCH 18/33] Testkit: an empty table inside name or head no longer fails rename_family The overlap check treated a table of length 0 whose offset points inside the name or head table as sharing bytes, so rename_family returned MalformedFont for a valid face. An overlap now needs at least one shared byte. Nonempty overlapping tables are still refused. --- crates/testkit/src/fonts.rs | 5 +++-- crates/testkit/tests/it/fonts.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs index cfc3096a0c..6c7ab56bca 100644 --- a/crates/testkit/src/fonts.rs +++ b/crates/testkit/src/fonts.rs @@ -201,10 +201,11 @@ fn table_count(face: &[u8]) -> Result { Ok(usize::from(u16_at(face, 4)?)) } -/// Whether `table` shares bytes with the table directory or with another table of the face. +/// Whether `table` shares bytes with the table directory or with another table of the face. Another +/// table of length 0 shares no bytes, wherever its offset points. fn shares_bytes(tables: &[Table], table: &Table) -> bool { let end = table.offset + table.length; - let overlaps = |start: usize, other_end: usize| start < end && table.offset < other_end; + let overlaps = |start: usize, other_end: usize| start < other_end && start < end && table.offset < other_end; overlaps(0, SFNT_HEADER + tables.len() * TABLE_RECORD) || tables.iter().any(|other| other.record != table.record && overlaps(other.offset, other.offset + other.length)) } diff --git a/crates/testkit/tests/it/fonts.rs b/crates/testkit/tests/it/fonts.rs index 56e20b79ac..b3eb2ff5bc 100644 --- a/crates/testkit/tests/it/fonts.rs +++ b/crates/testkit/tests/it/fonts.rs @@ -420,6 +420,20 @@ fn rename_rejects_name_table_sharing_bytes() { assert_eq!(rename_family(&under_head, FROM, TO), Err(FontError::MalformedFont), "checkSumAdjustment would land in zzzz"); } +#[test] +fn rename_accepts_an_empty_table_inside_name_or_head() { + let font = face(&[(b"head", head()), (b"name", names(&[win(1, FROM)])), (b"zzzz", vec![7; 8])]); + let (record, _, _) = table(&font, b"zzzz"); + let (_, name_at, _) = table(&font, b"name"); + let (_, head_at, _) = table(&font, b"head"); + for inside in [name_at + 18, head_at + 8] { + let mut empty = font.clone(); + set32(&mut empty, record + 8, inside as u32); + set32(&mut empty, record + 12, 0); + assert!(rename_family(&empty, FROM, TO).is_ok(), "an empty table at {inside} shares no bytes"); + } +} + #[test] fn rename_rejects_unknown_name_format() { let font = family_face(&[win(1, FROM)]); From b7fa315333c8380777aa99d180ae227339f6e991 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:09:23 -0800 Subject: [PATCH 19/33] craft-xtask: drop the redundant png_info link target in ico::read docs rustdoc -D warnings rejects the explicit super::png_info target because png_info is imported into the module. --- crates/xtask/src/icon/ico.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xtask/src/icon/ico.rs b/crates/xtask/src/icon/ico.rs index d45264b001..d6cdffbbf4 100644 --- a/crates/xtask/src/icon/ico.rs +++ b/crates/xtask/src/icon/ico.rs @@ -73,7 +73,7 @@ pub struct Entry { /// size against [`Limits::max_total_bytes`], and for each entry: a PNG of at most /// [`Limits::max_png_bytes`], square dimensions, palette size 0, reserved 0, 1 plane and 32 bits per /// pixel, as [`pack`] writes them, a size no other entry has, and an 8-bit RGBA PNG that -/// [`png_info`](super::png_info) accepts, of the size the entry states, lying wholly after the +/// [`png_info`] accepts, of the size the entry states, lying wholly after the /// directory and inside the file. The PNGs together hold at most [`Limits::max_total_bytes`]. pub fn read(ico: &[u8], limits: &Limits) -> Result, Error> { let bad = Error::InvalidIcon; From f4a967f263fbba1d8bf64808a4ab7a6d43a0c089 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:20:01 -0800 Subject: [PATCH 20/33] Audio DSP: keep the wet sample at full mix, order the quiet-run reset, track pitch over all channels Bitcrusher and Frequency Mod blend dry and wet as a weighted sum, so a mix of 100% returns the wet sample even beside a dry sample of far larger magnitude. Noise Suppression ends the quiet run when the frame after a short mute reaches the estimate, so quiet frames queued before the mute still count first. Voice Pitch divides the tracker input by the configured channel count, so leaving a silent channel out of a block no longer changes the tracked period. The suppressor's shadow run feeds the mixed samples to the mute detector. --- crates/audio-dsp/src/effects/character.rs | 19 +++++++- crates/audio-dsp/src/effects/suppress.rs | 55 ++++++++++++++++++++++- crates/audio-dsp/src/effects/voice.rs | 27 ++++++++++- 3 files changed, 97 insertions(+), 4 deletions(-) diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs index 888d3bd8ea..ca92dda84f 100644 --- a/crates/audio-dsp/src/effects/character.rs +++ b/crates/audio-dsp/src/effects/character.rs @@ -29,6 +29,12 @@ use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tai use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; use std::f64::consts::TAU; +/// Weighted sum of a dry and a wet sample. A mix of 0 gives the dry sample and a mix of 1 gives the +/// wet one exactly, however far apart their magnitudes are. +fn blend(dry: f64, wet: f64, mix: f64) -> f64 { + (1.0 - mix) * dry + mix * wet +} + /// Smoothing time of the frequency, resonance, depth and mix, in ms. const SM: f32 = 20.0; const RING_EFFECTS: &[&str] = &["Ring", "Frequency Mod", "Resonator +", "Resonator -"]; @@ -239,7 +245,7 @@ impl AudioEffect for RingMod { if ch < nch { // In f64, so the difference of two large samples of opposite sign stays finite. let (dry, wet) = (dry as f64, wet as f64); - channels[ch][i] = (dry + mix as f64 * (wet - dry)) as f32; + channels[ch][i] = blend(dry, wet, f64::from(mix)) as f32; } } } @@ -335,7 +341,7 @@ impl AudioEffect for Bitcrusher { // The held input is rounded at the current step, so a change of Bits also // applies to the hold in progress. let crushed = ((f64::from(*held) / step).round() * step).clamp(-limit, limit); - channels[ch][i] = (dry + mix * (crushed - dry)) as f32; + channels[ch][i] = blend(dry, crushed, mix) as f32; } } } @@ -783,6 +789,15 @@ mod tests { } } + /// At a mix of 100% the output is the wet sample even when the dry sample is far larger. + #[test] + fn full_mix_keeps_a_small_wet_sample_beside_a_huge_dry_one() { + let mut c = crush(&[("mix", 100.0), ("bits", 16.0), ("rate_divide", 4.0)], 1); + let mut y = vec![0.5, f32::MAX, f32::MAX, f32::MAX, 0.25]; + c.process(&mut [&mut y]); + assert_eq!(y[1], 0.5, "the held sample was lost at full mix: {y:?}"); + } + /// Raising the sample-and-hold rate takes effect within one new hold, instead of after the /// value already held at the slow rate runs out. #[test] diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs index c4bd01534d..1630586c34 100644 --- a/crates/audio-dsp/src/effects/suppress.rs +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -105,6 +105,11 @@ struct Bins { /// Total power of each waiting frame, and whether it may enter the estimate. queue_total: [f32; OVERLAP], queue_ok: [bool; OVERLAP], + /// Whether a mute began between a waiting frame and the one before it, so the quiet run ends + /// when the frame reaches the estimate. + queue_cut: [bool; OVERLAP], + /// Whether a mute began since the last frame was queued. + cut_pending: bool, head: usize, queued: usize, /// Whether a frame has entered the estimate since the last reset. @@ -144,6 +149,8 @@ impl Bins { queue: vec![0.0; bins * OVERLAP], queue_total: [0.0; OVERLAP], queue_ok: [false; OVERLAP], + queue_cut: [false; OVERLAP], + cut_pending: false, head: 0, queued: 0, started: false, @@ -170,6 +177,7 @@ impl Bins { self.frames = 0; self.head = 0; self.queued = 0; + self.cut_pending = false; self.started = false; self.heard = 0; self.since_zero = 1; @@ -196,7 +204,8 @@ impl Bins { if self.queued > 0 && self.since_frame < hop { self.queue_ok[(self.head + self.queued - 1) % OVERLAP] = false; } - self.quiet_run = 0; + // The frames already waiting come before the mute, so the quiet run ends after them. + self.cut_pending = true; } self.since_mute = 0; } @@ -214,6 +223,9 @@ impl Bins { let at = self.head; self.head = (at + 1) % OVERLAP; self.queued -= 1; + if self.queue_cut[at] { + self.quiet_run = 0; + } if !self.queue_ok[at] { return; } @@ -260,6 +272,7 @@ impl Bins { // next `OVERLAP - 1` frames, or the next `OVERLAP` when the silence ends between // two hops. A quiet run ends here too. self.queued = 0; + self.cut_pending = false; self.since_zero = 0; self.quiet_run = 0; } else { @@ -272,6 +285,7 @@ impl Bins { self.queue[at * bins + k] = re[k] * re[k] + im[k] * im[k]; } self.queue_total[at] = total; + self.queue_cut[at] = std::mem::take(&mut self.cut_pending); // A frame holds the last STFT size of samples, `2 * (bins - 1)`. self.queue_ok[at] = self.since_zero > OVERLAP && self.since_mute >= 2 * (bins - 1); self.queued += 1; @@ -497,6 +511,7 @@ mod tests { let mut out = [vec![0.0f32; speech.len()], vec![0.0f32; speech.len()], vec![0.0f32; speech.len()]]; for i in 0..speech.len() { let x = [speech[i] + noise[i], speech[i], noise[i]]; + bins.sample(x[0], hop); for (lane, (st, o)) in lanes.iter_mut().zip(out.iter_mut()).enumerate() { o[i] = st.tick(x[lane], hop, &mut |input, frame_out| { spec.analyze(input); @@ -775,6 +790,44 @@ mod tests { assert!(fell < -20.0, "after a search window of quiet the estimate fell by only {:.1} dB", -fell); } + /// A mute of one hop, which leaves no frame of digital silence, ends the quiet run where it + /// falls in the stream: the quiet frames waiting before it still count, and only the frames + /// after the mute that may enter the estimate start the next run. + #[test] + fn a_short_mute_ends_the_quiet_run_in_queue_order() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let im = vec![0.0f32; half]; + let (loud, quiet) = (vec![1.0f32; half], vec![0.001f32; half]); + let mut step = |bins: &mut Bins, sample: f32, spectrum: &[f32]| { + for _ in 0..hop { + bins.sample(sample, hop); + } + bins.frame(spectrum, &im, &coefs, &mut gains); + }; + for _ in 0..40 { + step(&mut bins, 0.1, &loud); + } + for _ in 0..OVERLAP + 3 { + step(&mut bins, 0.001, &quiet); + } + assert!(bins.quiet_run > 0, "the quiet frames before the mute did not count"); + step(&mut bins, 0.0, &quiet); + let mut eligible = 0; + for _ in 0..2 * n / hop { + step(&mut bins, 0.001, &quiet); + let newest = (bins.head + bins.queued - 1) % OVERLAP; + eligible += usize::from(bins.queue_ok[newest]); + } + let waiting = (0..bins.queued).filter(|j| bins.queue_ok[(bins.head + j) % OVERLAP]).count(); + assert_eq!(waiting, bins.queued, "a frame waiting after the mute may not enter the estimate"); + assert!(eligible + 3 < coefs.window, "the test needs the run below its cap"); + assert_eq!(bins.quiet_run, eligible - waiting, "frames from before the mute counted in the new run"); + } + /// A voice that starts with the stream keeps its level within 3 dB over its first 0.25 s and /// its first 1.5 s, while the suppressor has no noise estimate yet. One of the voices starts on /// its first sample with a vowel held for 0.25 s. diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs index 4499e659f4..20c969f274 100644 --- a/crates/audio-dsp/src/effects/voice.rs +++ b/crates/audio-dsp/src/effects/voice.rs @@ -450,7 +450,8 @@ impl AudioEffect for VoicePitch { } fn process(&mut self, channels: &mut [&mut [f32]]) { let len = block_len(channels); - let ch = channels.len().min(self.lines.len()); + // The mean runs over every configured channel, so a channel left out counts as silence. + let ch = self.lines.len(); let dry_at = self.mask + 1 - self.latency; let follow_target = self.follow_target(); // The formant stage moves the envelope by the inverse of the pitch ratio. @@ -1272,6 +1273,30 @@ mod tests { assert!(out[0] == out[1], "leaving the channel out changed the output"); } + /// Leaving a silent third channel out of a block does not change the pitch the tracker finds, + /// so a shifted voice comes out the same on the channels that remain. + #[test] + fn a_silent_channel_left_out_keeps_the_tracked_pitch() { + let n = SR as usize; + let (low, high) = (sine(187.5, 0.2, SR as f64, n, 0.0), sine(375.0, 0.24, SR as f64, n, 0.0)); + let left: Vec = low.iter().zip(&high).map(|(a, b)| a + b).collect(); + let right: Vec = low.iter().zip(&high).map(|(a, b)| -a + b).collect(); + let mut out = Vec::new(); + for omit in [false, true] { + let mut p = VoicePitch::new(SR, 3); + assert!(p.set_param("semitones", 5.0)); + p.reset(); + let (mut l, mut r, mut s) = (left.clone(), right.clone(), vec![0.0f32; n]); + if omit { + p.process(&mut [&mut l, &mut r]); + } else { + p.process(&mut [&mut l, &mut r, &mut s]); + } + out.push((l, r)); + } + assert!(out[0] == out[1], "leaving a silent channel out changed the tracked pitch"); + } + /// The tracker finds a voice's period down to 70 Hz and reports nothing for silence. #[test] fn the_tracker_reaches_70_hz() { From 8cd9ec9a51e71126f568fefc156ba7cac461764d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:05:33 -0800 Subject: [PATCH 21/33] audio-dsp: reset quiet runs in mute queue order --- crates/audio-dsp/src/effects/suppress.rs | 38 +++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs index c4bd01534d..b87065103e 100644 --- a/crates/audio-dsp/src/effects/suppress.rs +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -105,6 +105,10 @@ struct Bins { /// Total power of each waiting frame, and whether it may enter the estimate. queue_total: [f32; OVERLAP], queue_ok: [bool; OVERLAP], + /// Whether a mute began between a waiting frame and the one before it. + queue_cut: [bool; OVERLAP], + /// Whether a mute began since the last frame was queued. + cut_pending: bool, head: usize, queued: usize, /// Whether a frame has entered the estimate since the last reset. @@ -144,6 +148,8 @@ impl Bins { queue: vec![0.0; bins * OVERLAP], queue_total: [0.0; OVERLAP], queue_ok: [false; OVERLAP], + queue_cut: [false; OVERLAP], + cut_pending: false, head: 0, queued: 0, started: false, @@ -170,6 +176,7 @@ impl Bins { self.frames = 0; self.head = 0; self.queued = 0; + self.cut_pending = false; self.started = false; self.heard = 0; self.since_zero = 1; @@ -196,7 +203,7 @@ impl Bins { if self.queued > 0 && self.since_frame < hop { self.queue_ok[(self.head + self.queued - 1) % OVERLAP] = false; } - self.quiet_run = 0; + self.cut_pending = true; } self.since_mute = 0; } @@ -214,6 +221,9 @@ impl Bins { let at = self.head; self.head = (at + 1) % OVERLAP; self.queued -= 1; + if self.queue_cut[at] { + self.quiet_run = 0; + } if !self.queue_ok[at] { return; } @@ -260,6 +270,7 @@ impl Bins { // next `OVERLAP - 1` frames, or the next `OVERLAP` when the silence ends between // two hops. A quiet run ends here too. self.queued = 0; + self.cut_pending = false; self.since_zero = 0; self.quiet_run = 0; } else { @@ -272,6 +283,7 @@ impl Bins { self.queue[at * bins + k] = re[k] * re[k] + im[k] * im[k]; } self.queue_total[at] = total; + self.queue_cut[at] = std::mem::take(&mut self.cut_pending); // A frame holds the last STFT size of samples, `2 * (bins - 1)`. self.queue_ok[at] = self.since_zero > OVERLAP && self.since_mute >= 2 * (bins - 1); self.queued += 1; @@ -497,6 +509,7 @@ mod tests { let mut out = [vec![0.0f32; speech.len()], vec![0.0f32; speech.len()], vec![0.0f32; speech.len()]]; for i in 0..speech.len() { let x = [speech[i] + noise[i], speech[i], noise[i]]; + bins.sample(x[0], hop); for (lane, (st, o)) in lanes.iter_mut().zip(out.iter_mut()).enumerate() { o[i] = st.tick(x[lane], hop, &mut |input, frame_out| { spec.analyze(input); @@ -775,6 +788,29 @@ mod tests { assert!(fell < -20.0, "after a search window of quiet the estimate fell by only {:.1} dB", -fell); } + #[test] + fn a_short_mute_ends_the_queued_quiet_run() { + for offset in [0, 17] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut loud = white(47, SR as usize * 2, 0.05); + s.process(&mut [&mut loud]); + let mut quiet = white(51, 20 * hop + offset, 0.0005); + s.process(&mut [&mut quiet]); + assert!(s.bins[0].quiet_run > 0); + let mute_end = loud.len() + quiet.len() + hop; + let first_clean_frame = (mute_end + n).div_ceil(hop); + let commit_end = (first_clean_frame + OVERLAP) * hop; + let mut after = white(53, commit_end - loud.len() - quiet.len(), 0.0005); + after[..hop].fill(0.0); + let before_mute = s.bins[0].quiet_run; + s.process(&mut [&mut after[..hop]]); + assert_eq!(s.bins[0].quiet_run, before_mute + 1, "offset {offset}: queued pre-mute frames lost their quiet run"); + s.process(&mut [&mut after[hop..]]); + assert_eq!(s.bins[0].quiet_run, 1, "offset {offset}: pre-mute quiet frames contributed to the new run"); + } + } + /// A voice that starts with the stream keeps its level within 3 dB over its first 0.25 s and /// its first 1.5 s, while the suppressor has no noise estimate yet. One of the voices starts on /// its first sample with a vowel held for 0.25 s. From ce2f746e4c516178eed4046111e0ebb88af15e98 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:22:47 -0800 Subject: [PATCH 22/33] testkit: validate MCP replies and stop failed queued writes --- crates/testkit/README.md | 2 +- crates/testkit/src/mcp.rs | 106 +++++++++++++++++++++--- crates/testkit/tests/mcp.rs | 51 +++++++++++- crates/testkit/tests/mcp_child/child.rs | 43 +++++++++- 4 files changed, 186 insertions(+), 16 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 89d5e782cb..81b0a18dc6 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -275,7 +275,7 @@ use craft_testkit::mcp::{McpChild, PROTOCOL_VERSION}; let mut mcp = McpChild::spawn(env!("CARGO_BIN_EXE_my-cli"), ["mcp"], [("MYCRAFT_CONFIG_DIR", dir.path())])?; mcp.initialize(PROTOCOL_VERSION)?; let result = mcp.call_tool("doc.new", serde_json::json!({}))?; -assert_eq!(result["isError"], false); +assert!(!result["isError"].as_bool().unwrap_or(false)); assert!(mcp.close()?.status.is_some_and(|s| s.success())); ``` diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index 8021914dc4..715b421ff3 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -8,15 +8,18 @@ //! call does not hang. //! //! After a deadline, a protocol error, an over-long line or the end of the child's output, the -//! connection is closed: the child is stopped and reaped, and later calls return -//! [`McpError::Closed`]. A JSON-RPC error reply returns [`McpError::Rpc`] and the connection stays -//! usable. A tool result with `isError: true` is a successful reply and is returned unchanged. +//! connection is closed, and later calls return [`McpError::Closed`]. A child is stopped and +//! reaped on failure, except that an I/O error or the end of stdout leaves it for +//! [`McpChild::close`] or a drop to reap. A JSON-RPC error reply returns [`McpError::Rpc`] and the +//! connection stays usable. A tool result with `isError: true` is a successful reply and is +//! returned unchanged. use std::collections::VecDeque; use std::ffi::{OsStr, OsString}; use std::fmt; use std::io::{self, BufRead, BufReader, Read, Write}; use std::process::{Child, ChildStderr, Command, ExitStatus, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, TryRecvError, TrySendError, sync_channel}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::{Duration, Instant}; @@ -369,6 +372,7 @@ pub struct McpChild { /// Lines for the writer thread. `None` once the connection is closed, which ends the thread /// and closes the child's stdin. writer: Option>>, + failed: Arc, rx: Receiver, next_id: u64, limits: McpLimits, @@ -494,9 +498,14 @@ impl McpChild { } })?; let (wtx, wrx) = sync_channel::>(WRITE_QUEUE); + let failed = Arc::new(AtomicBool::new(false)); + let write_stopped = Arc::clone(&failed); start_thread("craft-testkit-mcp-write", move || { let mut w = writer; for line in wrx { + if write_stopped.load(Ordering::Acquire) { + return; + } if let Err(e) = w.write_all(&line).and_then(|()| w.flush()) { // Wakes a request waiting for its reply. Ends when the client is dropped. let _ = write_failed.send(Incoming::WriteFailed(e)); @@ -504,7 +513,18 @@ impl McpChild { } } })?; - Ok(Self { writer: Some(wtx), rx, next_id: 1, limits, child: None, exit: None, closed: None, notifications: VecDeque::new(), stderr: None }) + Ok(Self { + writer: Some(wtx), + failed, + rx, + next_id: 1, + limits, + child: None, + exit: None, + closed: None, + notifications: VecDeque::new(), + stderr: None, + }) } /// The message of the failure that closed the connection, or `None` while it is usable. @@ -535,6 +555,15 @@ impl McpChild { if returned != version { return Err(self.fail(McpError::UnsupportedVersion { requested: version.to_string(), returned })); } + if !result.get("capabilities").is_some_and(Value::is_object) { + return Err(self.fail(McpError::Protocol("the `initialize` result has no `capabilities` object".into()))); + } + let valid_info = result.get("serverInfo").is_some_and(|info| { + info.is_object() && info.get("name").is_some_and(Value::is_string) && info.get("version").is_some_and(Value::is_string) + }); + if !valid_info { + return Err(self.fail(McpError::Protocol("the `initialize` result has no valid `serverInfo` name and version".into()))); + } self.notify("notifications/initialized", Value::Null)?; Ok(result) } @@ -729,6 +758,10 @@ impl McpChild { } match (v.get("method"), v.get("id")) { (Some(Value::String(method)), Some(id)) => { + let integer = id.as_i64().is_some() || id.as_u64().is_some(); + if !id.is_string() && !integer { + return Err(self.fail(McpError::Protocol("a request has an `id` that is not a string or an integer".into()))); + } let reply = if method == "ping" { json!({"jsonrpc": "2.0", "id": id, "result": {}}) } else { @@ -774,20 +807,21 @@ impl McpChild { } } - /// Closes the connection with `err`: ends the writer, which closes the child's stdin, and stops - /// and reaps the child. A child that closed its output or input gets - /// [`McpLimits::close_grace`] to exit first. + /// Closes the connection with `err` and discards queued writes and unread messages. A write + /// already in progress may finish. After an I/O error or the end of stdout, `close` or a drop + /// reaps the child; other failures stop and reap it without a grace period. fn fail(&mut self, err: McpError) -> McpError { if self.closed.is_none() { self.closed = Some(err.to_string()); } + self.failed.store(true, Ordering::Release); self.writer = None; + self.rx = sync_channel(0).1; + if matches!(err, McpError::Ended | McpError::Io { .. }) { + return err; + } if let Some(mut child) = self.child.take() { - let grace = match err { - McpError::Ended | McpError::Io { .. } => self.limits.close_grace, - _ => Duration::ZERO, - }; - match reap(&mut child, grace) { + match reap(&mut child, Duration::ZERO) { Ok(exit) => self.exit = Some(exit), Err(_) => { let _ = child.kill(); @@ -858,6 +892,54 @@ fn reap(child: &mut Child, grace: Duration) -> io::Result<(ExitStatus, bool)> { mod tests { use super::*; + #[test] + fn queued_writes_stop_on_failure_but_drain_on_close() { + struct GateWriter { + started: Option>, + resume: Receiver<()>, + lines: Vec>, + done: SyncSender>>, + } + impl Write for GateWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if let Some(started) = self.started.take() { + started.send(()).unwrap(); + self.resume.recv().unwrap(); + } + self.lines.push(bytes.to_vec()); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + impl Drop for GateWriter { + fn drop(&mut self) { + self.done.send(std::mem::take(&mut self.lines)).unwrap(); + } + } + for failure in [false, true] { + let (started_tx, started) = sync_channel(1); + let (resume, resume_rx) = sync_channel(1); + let (done_tx, done) = sync_channel(1); + let writer = GateWriter { started: Some(started_tx), resume: resume_rx, lines: Vec::new(), done: done_tx }; + let mut client = McpChild::connect(io::empty(), writer, McpLimits::default()).unwrap(); + client.notify("first", Value::Null).unwrap(); + started.recv().unwrap(); + client.notify("queued", Value::Null).unwrap(); + if failure { + client.fail(McpError::Protocol("bad reply".into())); + } else { + client.close().unwrap(); + } + resume.send(()).unwrap(); + let lines = done.recv().unwrap(); + let methods: Vec = + lines.iter().map(|line| serde_json::from_slice::(line).unwrap()["method"].as_str().unwrap().to_string()).collect(); + assert_eq!(methods, if failure { vec!["first"] } else { vec!["first", "queued"] }); + } + } + #[test] fn capped_line_reader() { let mut r = io::Cursor::new(b"abc\nabcdefgh\nxy".to_vec()); diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs index 408f9ece55..097f6b6947 100644 --- a/crates/testkit/tests/mcp.rs +++ b/crates/testkit/tests/mcp.rs @@ -57,7 +57,10 @@ fn handshake_list_and_call() { let initialized = Arc::new(AtomicBool::new(false)); let seen = initialized.clone(); let mut c = fake(move |m, req| match m { - "initialize" => Some(vec![result(req, json!({"protocolVersion": req["params"]["protocolVersion"]}))]), + "initialize" => Some(vec![result( + req, + json!({"protocolVersion": req["params"]["protocolVersion"], "capabilities": {}, "serverInfo": {"name": "fake", "version": "0"}}), + )]), "notifications/initialized" => { assert!(req.get("id").is_none(), "a notification has no id"); seen.store(true, Ordering::SeqCst); @@ -77,6 +80,52 @@ fn handshake_list_and_call() { assert_eq!(r["content"][0]["text"], "doc.new"); } +#[test] +fn initialize_requires_capabilities_and_server_info() { + for fields in [ + json!({}), + json!({"capabilities": []}), + json!({"capabilities": {}}), + json!({"capabilities": {}, "serverInfo": []}), + json!({"capabilities": {}, "serverInfo": {}}), + json!({"capabilities": {}, "serverInfo": {"name": "fake"}}), + json!({"capabilities": {}, "serverInfo": {"name": 1, "version": "0"}}), + json!({"capabilities": {}, "serverInfo": {"name": "fake", "version": 1}}), + ] { + let mut c = fake(move |_, req| { + let mut reply = fields.clone(); + reply["protocolVersion"] = json!(PROTOCOL_VERSION); + Some(vec![result(req, reply)]) + }); + assert!(matches!(c.initialize(PROTOCOL_VERSION), Err(McpError::Protocol(_)))); + assert!(c.closed().is_some()); + } +} + +#[test] +fn server_requests_require_string_or_integer_ids() { + for id in [Value::Null, json!(1.5), json!(1.0), json!(1e2)] { + let mut c = fake(move |method, req| match method { + "x" => Some(vec![json!({"jsonrpc": "2.0", "id": id, "method": "ping"}).to_string(), result(req, json!(true))]), + _ => None, + }); + assert!(matches!(c.request("x", Value::Null), Err(McpError::Protocol(_)))); + assert!(c.closed().is_some()); + } + for id in [json!("server"), json!(-1), json!(u64::MAX)] { + let expected = id.clone(); + let mut c = fake(move |method, req| match method { + "x" => Some(vec![json!({"jsonrpc": "2.0", "id": id, "method": "ping"}).to_string()]), + "" => { + assert_eq!(req["id"], expected); + Some(vec![json!({"jsonrpc": "2.0", "id": 1, "result": true}).to_string()]) + } + _ => None, + }); + assert_eq!(c.request("x", Value::Null).unwrap(), json!(true)); + } +} + #[test] fn pages_are_followed() { let mut c = fake(|m, req| match m { diff --git a/crates/testkit/tests/mcp_child/child.rs b/crates/testkit/tests/mcp_child/child.rs index c600e47a10..e3eb5318bb 100644 --- a/crates/testkit/tests/mcp_child/child.rs +++ b/crates/testkit/tests/mcp_child/child.rs @@ -21,6 +21,7 @@ const TESTS: &[(&str, Test)] = &[ ("stderr_flood_does_not_block", stderr_flood_does_not_block), ("close_forces_and_reaps_unresponsive_child", close_forces_and_reaps_unresponsive_child), ("close_keeps_stderr_written_before_exit", close_keeps_stderr_written_before_exit), + ("skip_filters_exclude_tests_from_the_child_runner", skip_filters_exclude_tests_from_the_child_runner), ]; pub fn run() -> ExitCode { @@ -28,8 +29,28 @@ pub fn run() -> ExitCode { return serve(&mode.to_string_lossy()); } let args: Vec = std::env::args().skip(1).collect(); - let filters: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect(); - let chosen: Vec<&(&str, Test)> = TESTS.iter().filter(|(name, _)| filters.iter().all(|f| name.contains(f.as_str()))).collect(); + let mut filters = Vec::new(); + let mut skipped = Vec::new(); + let mut options = args.iter(); + while let Some(arg) = options.next() { + if arg == "--skip" { + let Some(filter) = options.next().filter(|value| !value.is_empty() && !value.starts_with('-')) else { + eprintln!("--skip requires a test name"); + return ExitCode::FAILURE; + }; + skipped.push(filter.as_str()); + } else if let Some(filter) = arg.strip_prefix("--skip=") { + if filter.is_empty() || filter.starts_with('-') { + eprintln!("--skip requires a test name"); + return ExitCode::FAILURE; + } + skipped.push(filter); + } else if !arg.starts_with('-') { + filters.push(arg.as_str()); + } + } + let chosen: Vec<&(&str, Test)> = + TESTS.iter().filter(|(name, _)| filters.iter().all(|f| name.contains(*f)) && !skipped.iter().any(|f| name.contains(*f))).collect(); if args.iter().any(|a| a == "--list") { for (name, _) in chosen { println!("{name}: test"); @@ -109,6 +130,24 @@ fn start(mode: &str, limits: McpLimits) -> Result { .map_err(|e| format!("spawn {mode}: {e}")) } +fn skip_filters_exclude_tests_from_the_child_runner() -> Result<(), String> { + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + for args in [vec!["--list", "--skip", "stderr_flood_does_not_block"], vec!["--list", "--skip=stderr_flood_does_not_block"]] { + let output = std::process::Command::new(&exe).args(args).output().map_err(|e| e.to_string())?; + check(output.status.success(), || String::from_utf8_lossy(&output.stderr).into_owned())?; + let listed = String::from_utf8_lossy(&output.stdout); + check(!listed.contains("stderr_flood_does_not_block"), || format!("the skipped test was selected: {listed}"))?; + check(listed.lines().count() == TESTS.len() - 1, || format!("other tests were filtered out: {listed}"))?; + } + for args in + [vec!["--list", "--skip"], vec!["--skip", "--list"], vec!["--list", "--skip", ""], vec!["--list", "--skip="], vec!["--list", "--skip=--list"]] + { + let output = std::process::Command::new(&exe).args(&args).output().map_err(|e| e.to_string())?; + check(!output.status.success(), || format!("an invalid skip filter was accepted: {args:?}"))?; + } + Ok(()) +} + fn check(ok: bool, what: impl FnOnce() -> String) -> Result<(), String> { if ok { Ok(()) } else { Err(what()) } } From 284c3a994188ee2f4d18577877786928fdf497c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:26:09 -0800 Subject: [PATCH 23/33] testkit: document initialization and failure cleanup --- crates/testkit/README.md | 4 ++-- crates/testkit/src/mcp.rs | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 81b0a18dc6..15b3562bd4 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -245,7 +245,7 @@ The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The | Call | What it does | |---|---| -| `initialize(version)` | Sends `initialize` with `version` (`mcp::PROTOCOL_VERSION` is `2025-06-18`), waits for the reply, then sends `notifications/initialized`. A reply with another version returns `UnsupportedVersion` and closes the connection. | +| `initialize(version)` | Sends `initialize` with `version` (`mcp::PROTOCOL_VERSION` is `2025-06-18`), validates the reply, then sends `notifications/initialized`. The result must contain `capabilities` and `serverInfo` objects, with string `serverInfo.name` and `serverInfo.version` fields. Invalid fields return `Protocol` and close the connection. A reply with another version returns `UnsupportedVersion` and closes the connection. | | `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Well-formed replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. | | `call_tool(name, args)`, `call_tool_within(.., timeout)` | Sends `tools/call` and returns the tool result unchanged, `content` and `isError` included. | | `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. | @@ -253,7 +253,7 @@ The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The | `take_notifications()` | Returns the notifications kept so far without waiting. | | `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. After the child exits, it waits up to 5 s for the rest of stderr to be read. | -While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error, close the connection and stop the child; later calls return `Closed`. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics. +While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. Server requests require string or integer IDs. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error and close the connection; later calls return `Closed`. A terminal failure discards queued writes and unread messages. A write already in progress may finish. After the end of stdout or an I/O error, `close()` or dropping the connection reaps the child. Other terminal failures stop and reap it immediately. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics. `McpLimits` holds the limits. These defaults are the crate's own values: diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index 715b421ff3..f169478be2 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -541,6 +541,9 @@ impl McpChild { /// this crate's client info, waits up to [`McpLimits::initialize_timeout`] for the reply, then /// sends `notifications/initialized`. Returns the reply's result. A reply with another protocol /// version returns [`McpError::UnsupportedVersion`] and closes the connection. + /// The result must contain a `capabilities` object and a `serverInfo` object with string + /// `name` and `version` fields. Missing or invalid fields return [`McpError::Protocol`] and + /// close the connection. pub fn initialize(&mut self, version: &str) -> Result { let params = json!({ "protocolVersion": version, From 48b9770c15b6707c34bd5a98704dce5e0d020317 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:41:25 -0800 Subject: [PATCH 24/33] testkit: bound retained notification bytes --- crates/testkit/README.md | 6 ++++-- crates/testkit/src/mcp.rs | 26 ++++++++++++++++++++------ crates/testkit/tests/mcp.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 15b3562bd4..8476141367 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -259,14 +259,16 @@ While a call waits, the client answers the child's `ping` with an empty result a | Field | Default | Range | |---|---|---| -| `max_line_bytes` | 64 MiB, for one stdout line and for the whole `list_tools` result | at least 1 | +| `max_line_bytes` | 64 MiB, for one stdout line, for the whole `list_tools` result, and for the total compact JSON bytes of retained notifications | at least 1 | | `request_timeout` | 30 s | more than zero, at most 1 hour | | `initialize_timeout` | 60 s | more than zero, at most 1 hour | | `close_grace` | 2 s | at most 1 hour | | `max_pages` | 64 | at least 1 | -| `max_notifications` | 0 (notifications are not kept); the oldest is dropped when the queue is full | at most 4096 | +| `max_notifications` | 0 (notifications are not kept); oldest entries are dropped to satisfy both this count and the `max_line_bytes` byte budget | at most 4096 | | `stderr_tail_bytes` | 0 (stderr goes to the null device); otherwise the last bytes written are kept | at most 16 MiB | +A notification whose compact JSON encoding exceeds `max_line_bytes` is discarded without removing previously retained notifications. + `McpLimits::timeouts_from_var(name)` sets both deadlines from a variable that holds a whole number of seconds from 1 to 3600; `mcp::TIMEOUT_VAR` (`CRAFT_TEST_MCP_TIMEOUT_SECS`) is the default name. Any other value returns an error. ```rust diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index f169478be2..49993cd5ea 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -58,7 +58,8 @@ const METHOD_NOT_FOUND: i64 = -32601; #[derive(Debug, Clone, PartialEq, Eq)] pub struct McpLimits { /// The longest stdout line read, without its newline, and the most bytes of JSON - /// [`McpChild::list_tools`] returns in all. Default 64 MiB; must be at least 1. + /// [`McpChild::list_tools`] returns in all. This also caps the total compact JSON bytes of + /// retained notifications. Default 64 MiB; must be at least 1. pub max_line_bytes: usize, /// How long [`McpChild::request`], [`McpChild::call_tool`] and each page of /// [`McpChild::list_tools`] wait for the reply. Default 30 s; from 1 ns to [`MAX_TIMEOUT`]. @@ -72,6 +73,8 @@ pub struct McpLimits { pub max_pages: usize, /// The most notifications kept for [`McpChild::take_notifications`]; when the queue is full, /// the oldest is dropped. Default 0, which keeps none; at most [`MAX_NOTIFICATIONS`]. + /// Oldest entries are also dropped to keep their total compact JSON size within + /// [`McpLimits::max_line_bytes`]. A single notification larger than that budget is discarded. pub max_notifications: usize, /// The most bytes of the child's stderr kept, the last ones written. Default 0, which sends /// stderr to the null device; at most [`MAX_STDERR_TAIL`]. Not used by [`McpChild::connect`]. @@ -380,7 +383,8 @@ pub struct McpChild { /// The exit status of a child already reaped, and whether it was stopped. exit: Option<(ExitStatus, bool)>, closed: Option, - notifications: VecDeque, + notifications: VecDeque<(Value, usize)>, + notification_bytes: usize, stderr: Option, } @@ -523,6 +527,7 @@ impl McpChild { exit: None, closed: None, notifications: VecDeque::new(), + notification_bytes: 0, stderr: None, }) } @@ -683,7 +688,8 @@ impl McpChild { break; } } - self.notifications.drain(..).collect() + self.notification_bytes = 0; + self.notifications.drain(..).map(|(value, _)| value).collect() } /// Closes the child's stdin, waits up to [`McpLimits::close_grace`] for it to exit, then stops @@ -775,10 +781,18 @@ impl McpChild { } (Some(Value::String(_)), None) => { if self.limits.max_notifications > 0 { - if self.notifications.len() >= self.limits.max_notifications { - self.notifications.pop_front(); + let mut count = ByteCount(0); + serde_json::to_writer(&mut count, &v).map_err(|error| self.fail(McpError::Protocol(error.to_string())))?; + if count.0 > self.limits.max_line_bytes { + return Ok(None); } - self.notifications.push_back(v); + while self.notifications.len() >= self.limits.max_notifications || self.notification_bytes > self.limits.max_line_bytes - count.0 + { + let Some((_, removed)) = self.notifications.pop_front() else { break }; + self.notification_bytes = self.notification_bytes.saturating_sub(removed); + } + self.notification_bytes += count.0; + self.notifications.push_back((v, count.0)); } Ok(None) } diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs index 097f6b6947..c89e2c5cdd 100644 --- a/crates/testkit/tests/mcp.rs +++ b/crates/testkit/tests/mcp.rs @@ -137,6 +137,34 @@ fn pages_are_followed() { assert_eq!(names, vec!["a", "b"]); } +#[test] +fn notifications_are_bounded_by_total_json_bytes() { + let notes: Vec = (0..3) + .map(|index| json!({"jsonrpc": "2.0", "method": "notifications/message", "params": {"index": index, "data": "x".repeat(96)}})) + .collect(); + let limits = McpLimits { max_notifications: 4, max_line_bytes: notes[0].to_string().len() * 3 / 2, ..McpLimits::default() }; + let sent = notes.clone(); + let mut c = fake_with(limits, move |_, req| { + let mut lines: Vec = sent.iter().map(Value::to_string).collect(); + lines.push(result(req, json!(true))); + Some(lines) + }); + assert_eq!(c.request("x", Value::Null).unwrap(), json!(true)); + assert_eq!(c.take_notifications(), vec![notes[2].clone()]); + assert!(c.take_notifications().is_empty()); +} + +#[test] +fn a_notification_larger_than_the_capture_budget_keeps_earlier_messages() { + let oversized = r#"{"jsonrpc":"2.0","method":"n","params":{"n":1e1}}"#; + let kept = json!({"jsonrpc": "2.0", "method": "n", "params": {}}); + let limits = McpLimits { max_notifications: 4, max_line_bytes: oversized.len(), ..McpLimits::default() }; + let first = kept.to_string(); + let mut c = fake_with(limits, move |_, req| Some(vec![first.clone(), oversized.to_string(), result(req, json!(true))])); + assert_eq!(c.request("x", Value::Null).unwrap(), json!(true)); + assert_eq!(c.take_notifications(), vec![kept]); +} + #[test] fn notifications_log_lines_and_stale_replies_are_skipped() { // A log line on stdout is a protocol error (`non_json_stdout_is_protocol_error`); a From 565513eab9ffc415b8b36a9dae5f0c3448a00b09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:57:19 -0800 Subject: [PATCH 25/33] Validate MCP tool results and drain output during shutdown --- crates/testkit/README.md | 6 +++ crates/testkit/src/mcp.rs | 70 +++++++++++++++++-------- crates/testkit/tests/mcp.rs | 48 ++++++++++++++++- crates/testkit/tests/mcp_child/child.rs | 50 +++++++++++++++++- 4 files changed, 150 insertions(+), 24 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 8476141367..b1d7b94805 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -253,6 +253,12 @@ The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The | `take_notifications()` | Returns the notifications kept so far without waiting. | | `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. After the child exits, it waits up to 5 s for the rest of stderr to be read. | +Tool results require a `content` array. Optional `isError` must be a boolean, and optional +`structuredContent` and `_meta` must be objects. Both tool helpers reject a malformed envelope +with `Protocol` and close the connection. Requests and notifications from the server require +object-valued `params` when that field is present. `close()` drains and discards stdout while +waiting for the child; incoming output does not extend the grace period. + While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. Server requests require string or integer IDs. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error and close the connection; later calls return `Closed`. A terminal failure discards queued writes and unread messages. A write already in progress may finish. After the end of stdout or an I/O error, `close()` or dropping the connection reaps the child. Other terminal failures stop and reap it immediately. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics. `McpLimits` holds the limits. These defaults are the crate's own values: diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index 49993cd5ea..d9f17fcd06 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -485,22 +485,6 @@ impl McpChild { fn start(reader: impl Read + Send + 'static, writer: impl Write + Send + 'static, limits: McpLimits) -> Result { let (tx, rx) = sync_channel(READ_QUEUE); let write_failed = tx.clone(); - let cap = limits.max_line_bytes; - start_thread("craft-testkit-mcp-read", move || { - let mut r = BufReader::new(reader); - loop { - let incoming = match read_line_capped(&mut r, cap) { - Ok(None) => Incoming::Ended, - Ok(Some(line)) => parse_line(&line), - Err(LineError::TooLong) => Incoming::TooLong, - Err(LineError::Io(e)) => Incoming::ReadFailed(e), - }; - let last = !matches!(incoming, Incoming::Message(_)); - if tx.send(incoming).is_err() || last { - return; - } - } - })?; let (wtx, wrx) = sync_channel::>(WRITE_QUEUE); let failed = Arc::new(AtomicBool::new(false)); let write_stopped = Arc::clone(&failed); @@ -517,6 +501,22 @@ impl McpChild { } } })?; + let cap = limits.max_line_bytes; + start_thread("craft-testkit-mcp-read", move || { + let mut r = BufReader::new(reader); + loop { + let incoming = match read_line_capped(&mut r, cap) { + Ok(None) => Incoming::Ended, + Ok(Some(line)) => parse_line(&line), + Err(LineError::TooLong) => Incoming::TooLong, + Err(LineError::Io(e)) => Incoming::ReadFailed(e), + }; + let last = !matches!(incoming, Incoming::Message(_)); + if tx.send(incoming).is_err() || last { + return; + } + } + })?; Ok(Self { writer: Some(wtx), failed, @@ -622,13 +622,27 @@ impl McpChild { /// Calls the tool `name` with `arguments` (`tools/call`) and returns its result unchanged, /// `content` and `isError` included. + /// The result requires a `content` array. Optional `isError` must be a boolean, and optional + /// `structuredContent` and `_meta` must be objects. + /// A malformed envelope returns [`McpError::Protocol`] and closes the connection. pub fn call_tool(&mut self, name: &str, arguments: Value) -> Result { - self.request("tools/call", json!({"name": name, "arguments": arguments})) + self.call_tool_within(name, arguments, self.limits.request_timeout) } /// [`McpChild::call_tool`] with its own deadline. pub fn call_tool_within(&mut self, name: &str, arguments: Value, timeout: Duration) -> Result { - self.request_within("tools/call", json!({"name": name, "arguments": arguments}), timeout) + let result = self.request_within("tools/call", json!({"name": name, "arguments": arguments}), timeout)?; + for (field, valid) in [ + ("content", result.get("content").is_some_and(Value::is_array)), + ("isError", result.get("isError").is_none_or(Value::is_boolean)), + ("structuredContent", result.get("structuredContent").is_none_or(Value::is_object)), + ("_meta", result.get("_meta").is_none_or(Value::is_object)), + ] { + if !valid { + return Err(self.fail(McpError::Protocol(format!("a `tools/call` result has an invalid `{field}` field")))); + } + } + Ok(result) } /// Every tool the child lists, following `nextCursor` for at most [`McpLimits::max_pages`] @@ -698,11 +712,13 @@ impl McpChild { /// returns no status without waiting for that thread. A writer blocked on a server that has /// stopped reading stays with the thread until the server drops its reading end, and the thread /// reading `reader` stays blocked until the server drops its writing end or writes a line. + /// While waiting for a child, this drains and discards stdout. Incoming output does not + /// extend the grace period. pub fn close(mut self) -> Result { self.writer = None; let grace = self.limits.close_grace; let (status, forced) = match self.child.take() { - Some(mut child) => match reap(&mut child, grace) { + Some(mut child) => match reap(&mut child, grace, Some(&self.rx)) { Ok((status, forced)) => (Some(status), forced), Err(source) => { let _ = child.kill(); @@ -762,6 +778,9 @@ impl McpChild { /// Handles one message: answers a request from the child, keeps a notification, skips a /// well-formed reply to another id, and returns the reply to `waiting`. fn route(&mut self, v: Value, waiting: Option) -> Result, McpError> { + if v.get("method").is_some() && v.get("params").is_some_and(|params| !params.is_object()) { + return Err(self.fail(McpError::Protocol("a message has `params` that is not an object".into()))); + } if v.get("id").is_some_and(|id| !matches!(id, Value::String(_) | Value::Number(_) | Value::Null)) { return Err(self.fail(McpError::Protocol("a message has an `id` that is not a string, a number or null".into()))); } @@ -838,7 +857,7 @@ impl McpChild { return err; } if let Some(mut child) = self.child.take() { - match reap(&mut child, Duration::ZERO) { + match reap(&mut child, Duration::ZERO, None) { Ok(exit) => self.exit = Some(exit), Err(_) => { let _ = child.kill(); @@ -887,7 +906,7 @@ fn message(method: &str, params: Value) -> Map { /// Waits up to `grace` for the child to exit, then stops it. Returns its status and whether it /// was stopped. -fn reap(child: &mut Child, grace: Duration) -> io::Result<(ExitStatus, bool)> { +fn reap(child: &mut Child, grace: Duration, drain: Option<&Receiver>) -> io::Result<(ExitStatus, bool)> { let deadline = Instant::now().checked_add(grace); loop { if let Some(status) = child.try_wait()? { @@ -895,7 +914,14 @@ fn reap(child: &mut Child, grace: Duration) -> io::Result<(ExitStatus, bool)> { } let left = deadline.and_then(|d| d.checked_duration_since(Instant::now())).filter(|left| !left.is_zero()); let Some(left) = left else { break }; - std::thread::sleep(left.min(EXIT_POLL)); + let wait = left.min(EXIT_POLL); + match drain { + Some(rx) => match rx.recv_timeout(wait) { + Ok(_) | Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => std::thread::sleep(wait), + }, + None => std::thread::sleep(wait), + } } match child.kill() { Ok(()) => {} diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs index c89e2c5cdd..2b0e8bb98f 100644 --- a/crates/testkit/tests/mcp.rs +++ b/crates/testkit/tests/mcp.rs @@ -130,13 +130,59 @@ fn server_requests_require_string_or_integer_ids() { fn pages_are_followed() { let mut c = fake(|m, req| match m { "tools/list" if req["params"]["cursor"].is_null() => Some(vec![result(req, json!({"tools": [{"name": "a"}], "nextCursor": "p2"}))]), - "tools/list" => Some(vec![result(req, json!({"tools": [{"name": "b"}]}))]), + "tools/list" if req["params"]["cursor"] == "p2" => Some(vec![result(req, json!({"tools": [{"name": "b"}]}))]), + "tools/list" => panic!("unexpected cursor: {}", req["params"]["cursor"]), _ => None, }); let names: Vec = c.list_tools().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect(); assert_eq!(names, vec!["a", "b"]); } +#[test] +fn tool_result_envelopes_are_required() { + for within in [false, true] { + for malformed in [ + json!(null), + json!({}), + json!({"content": true}), + json!({"content": [], "isError": 1}), + json!({"content": [], "structuredContent": []}), + json!({"content": [], "_meta": null}), + ] { + let mut client = fake(move |_, req| Some(vec![result(req, malformed.clone())])); + let reply = if within { client.call_tool_within("probe", json!({}), LONG) } else { client.call_tool("probe", json!({})) }; + assert!(matches!(reply, Err(McpError::Protocol(_))), "{reply:?}"); + assert!(client.closed().is_some()); + } + for valid in [ + json!({"content": []}), + json!({"content": [], "isError": true}), + json!({"content": [], "structuredContent": {"value": 1}, "_meta": {}, "extra": "kept"}), + ] { + let sent = valid.clone(); + let mut client = fake(move |_, req| Some(vec![result(req, sent.clone())])); + let reply = if within { client.call_tool_within("probe", json!({}), LONG) } else { client.call_tool("probe", json!({})) }; + assert_eq!(reply.unwrap(), valid); + } + } +} + +#[test] +fn server_request_params_are_objects() { + for params in [json!(true), json!(1), json!("bad"), json!(null), json!([])] { + let mut client = fake(move |method, req| { + (method == "probe") + .then(|| vec![json!({"jsonrpc": "2.0", "id": "server", "method": "ping", "params": params}).to_string(), result(req, json!("done"))]) + }); + assert!(matches!(client.request("probe", json!({})), Err(McpError::Protocol(_)))); + } + let mut client = fake(|method, req| { + (method == "probe") + .then(|| vec![json!({"jsonrpc": "2.0", "id": "server", "method": "ping", "params": {}}).to_string(), result(req, json!("done"))]) + }); + assert_eq!(client.request("probe", json!({})).unwrap(), "done"); +} + #[test] fn notifications_are_bounded_by_total_json_bytes() { let notes: Vec = (0..3) diff --git a/crates/testkit/tests/mcp_child/child.rs b/crates/testkit/tests/mcp_child/child.rs index e3eb5318bb..1316d8f580 100644 --- a/crates/testkit/tests/mcp_child/child.rs +++ b/crates/testkit/tests/mcp_child/child.rs @@ -22,6 +22,8 @@ const TESTS: &[(&str, Test)] = &[ ("close_forces_and_reaps_unresponsive_child", close_forces_and_reaps_unresponsive_child), ("close_keeps_stderr_written_before_exit", close_keeps_stderr_written_before_exit), ("skip_filters_exclude_tests_from_the_child_runner", skip_filters_exclude_tests_from_the_child_runner), + ("thread_count_options_preserve_child_test_selection", thread_count_options_preserve_child_test_selection), + ("close_drains_stdout_before_child_exit", close_drains_stdout_before_child_exit), ]; pub fn run() -> ExitCode { @@ -33,7 +35,17 @@ pub fn run() -> ExitCode { let mut skipped = Vec::new(); let mut options = args.iter(); while let Some(arg) = options.next() { - if arg == "--skip" { + if arg == "--test-threads" { + if !options.next().is_some_and(|value| value.parse::().is_ok_and(|count| count > 0)) { + eprintln!("--test-threads requires a positive integer"); + return ExitCode::FAILURE; + } + } else if let Some(value) = arg.strip_prefix("--test-threads=") { + if !value.parse::().is_ok_and(|count| count > 0) { + eprintln!("--test-threads requires a positive integer"); + return ExitCode::FAILURE; + } + } else if arg == "--skip" { let Some(filter) = options.next().filter(|value| !value.is_empty() && !value.starts_with('-')) else { eprintln!("--skip requires a test name"); return ExitCode::FAILURE; @@ -115,6 +127,14 @@ fn serve(mode: &str) -> ExitCode { return ExitCode::FAILURE; } } + if mode == "stdout-after-eof" { + let line = json!({"jsonrpc": "2.0", "method": "notifications/message", "params": {"data": "x".repeat(FLOOD)}}).to_string(); + for _ in 0..8 { + if writeln!(out, "{line}").is_err() { + return ExitCode::FAILURE; + } + } + } if mode == "stubborn" { // Waits without a stdin to read until the parent stops it; ends on its own after ten // minutes so a parent that fails to stop it leaves nothing running. @@ -148,6 +168,34 @@ fn skip_filters_exclude_tests_from_the_child_runner() -> Result<(), String> { Ok(()) } +fn thread_count_options_preserve_child_test_selection() -> Result<(), String> { + let exe = std::env::current_exe().map_err(|error| error.to_string())?; + for args in [vec!["--list", "--test-threads", "1"], vec!["--list", "--test-threads=2"]] { + let output = std::process::Command::new(&exe).args(args).output().map_err(|error| error.to_string())?; + check(output.status.success(), || String::from_utf8_lossy(&output.stderr).into_owned())?; + let listed = String::from_utf8_lossy(&output.stdout); + check(listed.lines().count() == TESTS.len(), || format!("thread count changed test selection: {listed}"))?; + } + for args in [ + vec!["--list", "--test-threads"], + vec!["--list", "--test-threads", "0"], + vec!["--list", "--test-threads="], + vec!["--list", "--test-threads=bad"], + vec!["--test-threads", "--list"], + ] { + let output = std::process::Command::new(&exe).args(&args).output().map_err(|error| error.to_string())?; + check(!output.status.success(), || format!("an invalid thread count was accepted: {args:?}"))?; + } + Ok(()) +} + +fn close_drains_stdout_before_child_exit() -> Result<(), String> { + let mut client = start("stdout-after-eof", McpLimits::default())?; + client.initialize(PROTOCOL_VERSION).map_err(|error| error.to_string())?; + let outcome = client.close().map_err(|error| error.to_string())?; + check(!outcome.forced && outcome.status.is_some_and(|status| status.success()), || format!("close: {outcome:?}")) +} + fn check(ok: bool, what: impl FnOnce() -> String) -> Result<(), String> { if ok { Ok(()) } else { Err(what()) } } From 19c3356e78ab3db1524a3013a0c325ca15caec17 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 13:53:41 -0800 Subject: [PATCH 26/33] craft-testkit: deadline limits only catch hangs; wait_until waits on a Signal with_deadline failed a body that returned or panicked after its limit, and hammer failed a case that finished after its per-case limit, so a slow runner could fail a test whose code was correct. Both now take whatever the body or case produced, however late it arrives, and fail on the limit only when nothing has arrived by then. wait_until polled its condition with sleeps against a clock and failed a true that came after the limit. It now takes a Signal: the condition is called at once and again each time another thread calls Signal::raise, and the limit only fails a wait that saw no raise in that time. A raise made while the condition runs is not lost. No crate in this workspace calls wait_until. The tests use an injected wait for the limit and an injected clock instead of real 50 ms limits, and new tests cover a value or panic that arrives after the limit, a case that finishes after its limit, and a raise during the condition. The tests of the removed behavior (a late result fails, the pause schedule of the polling loop) are replaced by these. --- crates/testkit/README.md | 49 ++-- crates/testkit/src/deadline.rs | 440 +++++++++++++++------------------ crates/testkit/src/hostile.rs | 133 +++++----- crates/testkit/src/lib.rs | 9 +- 4 files changed, 298 insertions(+), 333 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 3adaf23762..e6ac4481bb 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -103,21 +103,24 @@ fn no_std_instant_in_code_the_web_build_runs() { The `deadline` module is not built for `wasm32`. -`with_deadline(limit, label, f)` runs `f` on its own thread and returns its value. When `f` does not -finish within the limit, the test fails with a message that names `label`, the limit and the variable -that sets it. A panic in `f` is raised again in the test with its original payload. The limit counts -from the call, including the time spent starting the thread. When `f` returns or panics after the -limit has passed, the test fails with the label and the limit, and with the panic's message if it has -one. +The limits in this module guard against a hang. Elapsed time does not decide a result: a test fails on +a limit only when nothing has arrived by then. -`wait_until(limit, what, cond)` calls `cond` on the test's thread until it returns `true`. It calls -`cond` at once, then after pauses that start at 1 ms and double up to 50 ms, and does not call it -again once the limit has passed. When the limit passes first, or `cond` returns `true` only after the -limit has passed, the test fails with a message that names `what`. +`with_deadline(limit, label, f)` runs `f` on its own thread and returns its value. A panic in `f` is +raised again in the test with its original payload. A value or panic that arrives after the limit is +still the result. When `f` has neither returned nor panicked within the limit, the test fails with a +message that names `label`, the limit and the variable that sets it. The limit counts from the start +of the thread. + +`wait_until(limit, what, &signal, cond)` calls `cond` on the test's thread at once, and again each +time another thread calls `signal.raise()`, until `cond` returns `true`. The thread that changes the +state `cond` reads raises the `Signal` after each change. A raise that comes while `cond` runs makes +`wait_until` call `cond` again straight after. When the signal is not raised within the limit after a +call that returned `false`, the test fails with a message that names `what`. ```rust use std::time::Duration; -use craft_testkit::deadline::{DeadlineLimit, wait_until, with_deadline}; +use craft_testkit::deadline::{DeadlineLimit, Signal, wait_until, with_deadline}; // The default of 30 s; CRAFT_TEST_TIMEOUT_SECS replaces it. let pixels = with_deadline(Duration::from_secs(30), "decode seed 7", move || decode(&bytes)); @@ -126,7 +129,9 @@ let pixels = with_deadline(Duration::from_secs(30), "decode seed 7", move || dec let limit = DeadlineLimit::new(Duration::from_secs(30)).with_variable("FILMCRAFT_HOSTILE_TIMEOUT_SECS"); with_deadline(limit, "hostile input 12", move || parse(&input)); -wait_until(Duration::from_secs(10), "the export to finish", || job.is_done()); +// The export job calls `done.raise()` after it changes its state. +let done = Signal::new(); +wait_until(Duration::from_secs(10), "the export to finish", &done, || job.is_done()); ``` ### The limit variable @@ -150,12 +155,14 @@ calls this module's. ### Limits -- A body that runs past its limit fails the test, but its thread is left running until the test - process exits. A body that never returns can keep the test binary alive after its tests finish. -- `wait_until` checks its limit only between calls of `cond`. A `cond` that blocks is not interrupted, - so it must return promptly. -- Neither function returns elapsed time. Tests of this crate use channel handshakes, and the only time - bounds in them are the limits under test. +- When a body has no result within its limit, the test fails, but the body's thread is left running + until the test process exits. A body that never returns can keep the test binary alive after its + tests finish. +- A `cond` that blocks is not interrupted, so it must return promptly. +- A state change that nobody signals is not seen: when the signal is not raised, `wait_until` fails + at the limit even if `cond` would now return `true`. +- Neither function returns elapsed time. Tests of this crate use channel handshakes and an injected + wait in place of the limits. ## hostile @@ -169,8 +176,10 @@ yields no copies. `mutations` and `Rng` build for `wasm32`. `hammer(&config, seed, parse)` runs `parse` on the unmodified seed, on every truncation of it (lengths 0 to one less than its length), and on `mutations(seed, rounds)`. The cases run one after -another on one worker thread, and the test's thread fails the test when a case runs past its limit. -A case that finishes after its limit also fails the test. The test fails on the first case that +another on one worker thread, and the test's thread fails the test when a case is still running once +its limit has passed since it started. The limit guards against a hang: a case that finishes passes +or fails on what `parse` did, however long it took, and the number of cases depends only on the seed, +the rounds and the divisor. The test fails on the first case that panics or does not finish, with a message that names the config's label, the case (`the unmodified seed`, `truncation to N` or the edits), the input's length and the panic's message. `parse` must be `Fn(&[u8]) + Send + Sync + 'static`, since a case that does not finish keeps running diff --git a/crates/testkit/src/deadline.rs b/crates/testkit/src/deadline.rs index 918719e6bc..fa582b340a 100644 --- a/crates/testkit/src/deadline.rs +++ b/crates/testkit/src/deadline.rs @@ -1,11 +1,18 @@ //! Limits on how long a test waits. //! -//! [`with_deadline`] runs a test body on its own thread and returns its value. When the body does not -//! finish within the limit, the test fails with the call's label, the limit and the variable that sets -//! it. A panic in the body is raised again in the test with its original payload. +//! A limit here guards against a hang and does not decide a result. A value or panic that a body +//! produces is the call's result whenever it arrives, and a test fails on the limit only when nothing +//! has arrived by then. //! -//! [`wait_until`] calls a condition on the test's thread until it returns `true`, pausing between -//! calls, and fails the test with its description when the limit passes first. +//! [`with_deadline`] runs a test body on its own thread and returns its value. A panic in the body is +//! raised again in the test with its original payload. When the body has neither returned nor +//! panicked within the limit, the test fails with the call's label, the limit and the variable that +//! sets it. +//! +//! [`wait_until`] calls a condition on the test's thread, and calls it again each time another +//! thread raises the [`Signal`] the call waits on. It returns when the condition returns `true`, and +//! fails the test with its description when the signal is not raised within the limit after a call +//! that returned `false`. //! //! A limit is a default [`Duration`] and the name of a variable that replaces it. A plain `Duration` //! reads [`DEFAULT_VARIABLE`]; [`DeadlineLimit::with_variable`] names another one. The variable holds @@ -13,30 +20,23 @@ //! fractional, not Unicode, zero, or larger than a `u64` fails the test that reads it, as does a zero //! default and a limit past the latest time the platform's clock can represent. //! -//! Neither function can stop code that does not return. A body that runs past its limit fails the -//! test, and its thread is left running until the test process exits. A condition that blocks is -//! not interrupted: [`wait_until`] checks its limit only between calls, so a condition must return -//! promptly. +//! Neither function can stop code that does not return. When a body does not finish within its +//! limit, the test fails and the body's thread is left running until the test process exits. A +//! condition that blocks is not interrupted, so a condition must return promptly. use std::any::Any; use std::ffi::OsString; use std::fmt; use std::io; use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; -use std::sync::mpsc::{self, RecvTimeoutError, Sender}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::thread; use std::time::{Duration, Instant}; /// The variable a limit reads unless [`DeadlineLimit::with_variable`] names another. pub const DEFAULT_VARIABLE: &str = "CRAFT_TEST_TIMEOUT_SECS"; -/// The first pause of [`wait_until`] between two calls of its condition. -const FIRST_PAUSE: Duration = Duration::from_millis(1); - -/// The longest pause of [`wait_until`]: each pause doubles up to this. -const MAX_PAUSE: Duration = Duration::from_millis(50); - /// The name of the thread [`with_deadline`] runs a body on. const WORKER_NAME: &str = "craft-testkit deadline"; @@ -91,15 +91,50 @@ impl From for DeadlineLimit<'static> { } } -/// Runs `f` on its own thread and returns its value, failing the calling test when `f` does not -/// finish within `limit`. +/// A signal that [`wait_until`] waits on: the thread that changes the state a condition reads raises +/// it after each change, and every call waiting on it then calls its condition again. /// -/// The failure names `label`, the limit and the variable that sets it. A panic in `f` is raised -/// again here with its original payload. The limit is read and checked before `f` starts, and a -/// limit that is not valid fails the test without running `f`. The limit counts from the call, so -/// the time spent starting the thread counts against it. When `f` returns or panics after the limit -/// has passed, the test fails with the label and the limit, and with the panic's message if it has -/// one. When the limit passes, the thread running `f` is left running. +/// ``` +/// use craft_testkit::deadline::Signal; +/// +/// let signal = Signal::new(); +/// // A raise with no call waiting is kept: the next wait sees it and calls its condition again. +/// signal.raise(); +/// ``` +#[derive(Debug, Default)] +pub struct Signal { + /// How many times the signal has been raised, wrapping. + raised: Mutex, + changed: Condvar, +} + +impl Signal { + /// A signal that has not been raised. + pub fn new() -> Self { + Self::default() + } + + /// Wakes every [`wait_until`] call waiting on this signal, so that each calls its condition again. + pub fn raise(&self) { + let mut raised = self.lock(); + *raised = raised.wrapping_add(1); + self.changed.notify_all(); + } + + fn lock(&self) -> MutexGuard<'_, u64> { + self.raised.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +/// Runs `f` on its own thread and returns its value, failing the calling test when `f` has neither +/// returned nor panicked within `limit`. +/// +/// A panic in `f` is raised again here with its original payload. The limit guards against a hang: +/// a value or panic that `f` produces is the result whenever it arrives, and the test fails on the +/// limit only when `f` has produced neither by then. That failure names `label`, the limit and the +/// variable that sets it, and the thread running `f` is left running. The limit is read and checked +/// before `f` starts, and a limit that is not valid fails the test without running `f`. The limit +/// counts from the start of the thread running `f`. /// /// ``` /// use std::time::Duration; @@ -112,46 +147,49 @@ impl From for DeadlineLimit<'static> { #[allow(clippy::panic)] #[track_caller] pub fn with_deadline<'a, T: Send + 'static>(limit: impl Into>, label: &str, f: impl FnOnce() -> T + Send + 'static) -> T { - let start = Instant::now(); - match run_with_deadline(limit.into(), label, f, read_variable, spawn_worker, Arc::new(move || start.elapsed())) { + match run_with_deadline(limit.into(), label, f, read_variable, spawn_worker, |rx, limit| rx.recv_timeout(limit)) { Ok(value) => value, Err(Failure::Panic(payload)) => resume_unwind(payload), Err(Failure::Message(message)) => panic!("{message}"), } } -/// Calls `cond` on the calling thread until it returns `true`, failing the calling test when the -/// limit passes first. +/// Calls `cond` on the calling thread, and again each time `signal` is raised, until it returns +/// `true`, failing the calling test when `signal` is not raised within the limit after a call that +/// returned `false`. /// -/// `cond` is called at once, and then after pauses that grow from 1 ms to 50 ms, but not again once -/// the limit has passed. The failure names `what`, the limit and the variable that sets it. A `true` -/// that `cond` returns after the limit has passed also fails the test. A panic in `cond` reaches the -/// caller unchanged. `cond` runs on the calling thread and is not interrupted, so it must return -/// promptly. +/// `cond` is called at once. A raise that comes while `cond` runs is not lost: `cond` is called +/// again straight after. The limit guards against a hang and counts afresh from each call of `cond`, +/// so a condition that holds is never failed by it. The failure names `what`, the limit and the +/// variable that sets it. A panic in `cond` reaches the caller unchanged. `cond` runs on the calling +/// thread and is not interrupted, so it must return promptly. The threads that change what `cond` +/// reads raise `signal` after each change. /// /// ``` /// use std::sync::atomic::{AtomicBool, Ordering}; /// use std::time::Duration; -/// use craft_testkit::deadline::wait_until; +/// use craft_testkit::deadline::{Signal, wait_until}; /// /// let ready = AtomicBool::new(false); +/// let signal = Signal::new(); /// std::thread::scope(|s| { -/// s.spawn(|| ready.store(true, Ordering::SeqCst)); -/// wait_until(Duration::from_secs(30), "the worker to start", || ready.load(Ordering::SeqCst)); +/// s.spawn(|| { +/// ready.store(true, Ordering::SeqCst); +/// signal.raise(); +/// }); +/// wait_until(Duration::from_secs(30), "the worker to start", &signal, || ready.load(Ordering::SeqCst)); /// }); /// ``` // Failing the calling test is what this function is for. #[allow(clippy::panic)] #[track_caller] -pub fn wait_until<'a>(limit: impl Into>, what: &str, mut cond: impl FnMut() -> bool) { +pub fn wait_until<'a>(limit: impl Into>, what: &str, signal: &Signal, mut cond: impl FnMut() -> bool) { let limit = limit.into(); - let start = Instant::now(); - let resolved = match resolve(&limit, read_variable, start) { + let resolved = match resolve(&limit, read_variable, Instant::now()) { Ok(resolved) => resolved, Err(error) => panic!("waiting for {what}: {error}"), }; - let mut elapsed = || start.elapsed(); - if let Err(message) = poll_until(&resolved, what, &mut cond, &mut elapsed, &mut thread::sleep) { + if let Err(message) = wait_for_signal(&resolved, what, signal, &mut cond, wait_for_raise) { panic!("{message}"); } } @@ -265,8 +303,8 @@ fn spawn_worker(job: Job, done: Sender<()>) -> io::Result<()> { .map(drop) } -/// The body's result and the clock reading when it finished, filled in by the worker. -type Slot = Arc, Duration)>>>; +/// The body's result, filled in by the worker. +type Slot = Arc>>>; /// How a [`with_deadline`] call failed. enum Failure { @@ -276,52 +314,32 @@ enum Failure { Message(String), } -/// A clock that returns the time since a [`with_deadline`] call started. -type Clock = Arc Duration + Send + Sync>; - -/// The text of a panic payload that holds a message. -fn panic_text(payload: &(dyn Any + Send)) -> Option<&str> { - payload.downcast_ref::().map(String::as_str).or_else(|| payload.downcast_ref::<&str>().copied()) -} - -/// [`with_deadline`] with the variable lookup, the thread start and the clock passed in. Starting -/// the worker counts against the limit. The worker stores the body's result with the clock reading -/// when it finished, under a lock, and then sends on the channel `spawn` receives. When the wait -/// times out, the stored result is still used if it is there, so a body that finished in time passes -/// even when its thread sends late. +/// [`with_deadline`] with the variable lookup, the thread start and the wait for the worker passed +/// in. The worker stores the body's result under a lock and then sends on the channel `spawn` +/// receives. `wait` waits on that channel for at most the limit. Whatever `wait` returns, a stored +/// result is the call's result, so the limit fails the call only when the body has produced nothing. fn run_with_deadline( limit: DeadlineLimit<'_>, label: &str, f: impl FnOnce() -> T + Send + 'static, lookup: impl FnOnce(&str) -> Option, spawn: impl FnOnce(Job, Sender<()>) -> io::Result<()>, - clock: Clock, + wait: impl FnOnce(&Receiver<()>, Duration) -> Result<(), RecvTimeoutError>, ) -> Result { let resolved = resolve(&limit, lookup, Instant::now()).map_err(|error| Failure::Message(format!("{label}: {error}")))?; let (tx, rx) = mpsc::channel(); let slot: Slot = Arc::new(Mutex::new(None)); let worker_slot = Arc::clone(&slot); - let worker_clock = Arc::clone(&clock); let job: Job = Box::new(move || { let result = catch_unwind(AssertUnwindSafe(f)); - // The clock is read under the lock: once the caller finds the slot empty after its limit, - // any later reading is past the limit too. - let mut stored = worker_slot.lock().unwrap_or_else(PoisonError::into_inner); - *stored = Some((result, worker_clock())); + *worker_slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(result); }); spawn(job, tx).map_err(|error| Failure::Message(format!("{label}: could not start the worker thread: {error}")))?; - let waited = rx.recv_timeout(resolved.limit.saturating_sub(clock())); + let waited = wait(&rx, resolved.limit); let stored = slot.lock().unwrap_or_else(PoisonError::into_inner).take(); match (stored, waited) { - (Some((result, finished)), _) if finished > resolved.limit => { - let panicked = match &result { - Ok(_) => String::new(), - Err(payload) => format!(" (it panicked: {})", panic_text(payload.as_ref()).unwrap_or("a payload that is not a message")), - }; - Err(Failure::Message(format!("{label} finished only after its limit of {resolved}{panicked}"))) - } - (Some((Ok(value), _)), _) => Ok(value), - (Some((Err(payload), _)), _) => Err(Failure::Panic(payload)), + (Some(Ok(value)), _) => Ok(value), + (Some(Err(payload)), _) => Err(Failure::Panic(payload)), (None, Err(RecvTimeoutError::Timeout)) => { Err(Failure::Message(format!("{label} did not finish within {resolved}; its thread is left running"))) } @@ -329,44 +347,42 @@ fn run_with_deadline( } } -/// The loop of [`wait_until`], with the clock and the pause passed in. `elapsed` returns the time -/// since the wait started. -fn poll_until( +/// Waits on `changed` while `raised` still reads `seen`, for at most `limit`. Returns the guard and +/// whether the limit passed with no raise. +fn wait_for_raise<'g>(changed: &Condvar, raised: MutexGuard<'g, u64>, seen: u64, limit: Duration) -> (MutexGuard<'g, u64>, bool) { + let (raised, result) = changed.wait_timeout_while(raised, limit, |count| *count == seen).unwrap_or_else(PoisonError::into_inner); + (raised, result.timed_out()) +} + +/// The loop of [`wait_until`], with the wait for a raise passed in. The raise count is read before +/// each call of `cond`, so a raise during the call ends the next wait at once. +fn wait_for_signal( resolved: &Resolved<'_>, what: &str, + signal: &Signal, cond: &mut dyn FnMut() -> bool, - elapsed: &mut dyn FnMut() -> Duration, - pause: &mut dyn FnMut(Duration), + wait: impl for<'g> Fn(&Condvar, MutexGuard<'g, u64>, u64, Duration) -> (MutexGuard<'g, u64>, bool), ) -> Result<(), String> { - let mut next_pause = FIRST_PAUSE; - let mut first = true; + let mut seen = *signal.lock(); loop { - // After the first call, the condition is called only while the limit has not passed. - if !first && elapsed() >= resolved.limit { - return Err(format!("timed out waiting for {what} within {resolved}")); - } - first = false; - let held = cond(); - let spent = elapsed(); - if held && spent <= resolved.limit { + if cond() { return Ok(()); } - if held { - return Err(format!("timed out waiting for {what} within {resolved} (it held only after the limit had passed)")); + let (raised, timed_out) = wait(&signal.changed, signal.lock(), seen, resolved.limit); + if timed_out { + return Err(format!("timed out waiting for {what} within {resolved}: the signal was not raised after the last check")); } - if spent < resolved.limit { - pause(next_pause.min(resolved.limit - spent)); - } - next_pause = next_pause.saturating_mul(2).min(MAX_PAUSE); + seen = *raised; } } #[cfg(test)] mod tests { use super::*; + use std::cell::RefCell; use std::ffi::OsStr; use std::process::Command; - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::sync::atomic::{AtomicBool, Ordering}; /// A variable no test sets, so the environment cannot lengthen a test's short limit. const UNSET: &str = "CRAFT_TESTKIT_DEADLINE_UNSET_IN_TESTS"; @@ -400,6 +416,27 @@ mod tests { } } + /// A wait for the worker that returns at once, as when the limit passes with nothing received. + fn limit_passes(_: &Receiver<()>, _: Duration) -> Result<(), RecvTimeoutError> { + Err(RecvTimeoutError::Timeout) + } + + /// Runs `run_with_deadline` with its limit passing before the body has a result, and returns the + /// failure's message. The body runs on its own thread and blocks until the call has returned. + fn hung(limit: DeadlineLimit<'_>, label: &str, value: T) -> String { + let (gate, gate_rx) = mpsc::channel::<()>(); + let (done_tx, done) = mpsc::channel(); + let body = move || { + let _ = gate_rx.recv(); + done_tx.send(()).unwrap(); + value + }; + let result = run_with_deadline(limit, label, body, |_| None, spawn_worker, limit_passes); + drop(gate); + done.recv().unwrap(); + failure_message(result) + } + /// Runs `child_reads_its_variable` in a child process with `CHILD_VARIABLE` set to `value`, and /// returns what the child printed. The child must fail. fn run_child(value: &OsStr) -> String { @@ -442,21 +479,9 @@ mod tests { } #[test] - #[should_panic(expected = "seed 7 byte 3 did not finish within 50ms")] fn a_hang_fails_and_names_the_input() { - let (gate, gate_rx) = mpsc::channel::<()>(); - let (done_tx, done) = mpsc::channel(); - let result = catch_unwind(AssertUnwindSafe(|| { - with_deadline(short(), "seed 7 byte 3", move || { - let _ = gate_rx.recv(); - done_tx.send(()).unwrap(); - }) - })); - drop(gate); - done.recv().unwrap(); - if let Err(payload) = result { - resume_unwind(payload); - } + let text = hung(short(), "seed 7 byte 3", ()); + assert!(text.contains("seed 7 byte 3 did not finish within 50ms"), "{text}"); } #[test] @@ -467,14 +492,9 @@ mod tests { } #[test] - #[should_panic(expected = "did not finish within")] fn with_deadline_times_out() { - let (gate, gate_rx) = mpsc::channel::<()>(); - let result = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), "blocked body", move || gate_rx.recv().unwrap_or_default()))); - drop(gate); - if let Err(payload) = result { - resume_unwind(payload); - } + let text = hung(short(), "blocked body", 7u8); + assert!(text.contains("did not finish within") && text.contains("its thread is left running"), "{text}"); } #[test] @@ -492,14 +512,7 @@ mod tests { #[test] fn timeout_names_this_call_only() { - let call = |label: &'static str| { - thread::spawn(move || { - let (gate, gate_rx) = mpsc::channel::<()>(); - let result = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), label, move || gate_rx.recv().unwrap_or_default()))); - drop(gate); - message(result.unwrap_err()) - }) - }; + let call = |label: &'static str| thread::spawn(move || hung(short(), label, ())); let first = call("first call"); let second = call("second call"); let first = first.join().unwrap(); @@ -517,13 +530,10 @@ mod tests { 7 }) }); - let (gate, gate_rx) = mpsc::channel::<()>(); - let short_call = catch_unwind(AssertUnwindSafe(|| with_deadline(short(), "short call", move || gate_rx.recv().unwrap_or_default()))); - let text = message(short_call.unwrap_err()); + let text = hung(short(), "short call", ()); assert!(text.contains("short call") && text.contains("50ms") && !text.contains("long call"), "{text}"); release.send(()).unwrap(); assert_eq!(long_call.join().unwrap(), 7); - drop(gate); } #[test] @@ -533,7 +543,7 @@ mod tests { ran.store(true, Ordering::SeqCst); Err(io::Error::other("no threads left")) }; - let result = run_with_deadline(long(), "no thread", || (), |_| None, spawn, Arc::new(|| Duration::ZERO)); + let result = run_with_deadline(long(), "no thread", || (), |_| None, spawn, limit_passes); let text = failure_message(result); assert!(ran.load(Ordering::SeqCst)); assert!(text.contains("no thread: could not start the worker thread: no threads left"), "{text}"); @@ -579,10 +589,10 @@ mod tests { ran.store(true, Ordering::SeqCst); Ok(()) }; - let text = failure_message(run_with_deadline(huge, "huge", || (), |_| None, spawn, Arc::new(|| Duration::ZERO))); + let text = failure_message(run_with_deadline(huge, "huge", || (), |_| None, spawn, limit_passes)); assert!(text.contains("ends past the latest time"), "{text}"); assert!(!ran.load(Ordering::SeqCst), "the body started"); - let text = message(catch_unwind(|| wait_until(huge, "a huge limit", || true)).unwrap_err()); + let text = message(catch_unwind(|| wait_until(huge, "a huge limit", &Signal::new(), || true)).unwrap_err()); assert!(text.contains("waiting for a huge limit: the limit of") && text.contains("ends past the latest time"), "{text}"); } @@ -619,22 +629,20 @@ mod tests { #[test] fn wait_until_returns_on_condition() { let ready = &AtomicBool::new(false); + let signal = &Signal::new(); let (asked, asked_rx) = mpsc::channel(); - let (stored, stored_rx) = mpsc::channel(); thread::scope(|s| { s.spawn(move || { asked_rx.recv().unwrap(); ready.store(true, Ordering::SeqCst); - stored.send(()).unwrap(); + signal.raise(); }); let mut calls = 0; - wait_until(long(), "the flag", || { + wait_until(long(), "the flag", signal, || { calls += 1; if calls == 1 { - // The flag is set before this call returns, and it still answers false, so the - // condition is called a second time whatever order the threads run in. + // The other thread sets the flag only after this call has started. asked.send(()).unwrap(); - stored_rx.recv().unwrap(); return false; } ready.load(Ordering::SeqCst) @@ -644,145 +652,87 @@ mod tests { } #[test] - #[should_panic(expected = "timed out waiting for the export to finish within 50ms")] + fn a_raise_during_the_condition_ends_the_next_wait_at_once() { + let signal = Signal::new(); + let mut calls = 0; + let mut cond = || { + calls += 1; + if calls == 1 { + signal.raise(); + } + calls == 2 + }; + let result = wait_for_signal(&fake_resolved(Duration::from_secs(600)), "a raise", &signal, &mut cond, |_, raised, seen, _| { + assert_ne!(*raised, seen, "the raise made during the condition was lost"); + (raised, false) + }); + assert_eq!(result, Ok(())); + assert_eq!(calls, 2); + } + + #[test] fn wait_until_times_out_with_label() { - wait_until(short(), "the export to finish", || false); + let mut calls = 0; + let mut cond = || { + calls += 1; + false + }; + let resolved = fake_resolved(Duration::from_millis(50)); + let text = wait_for_signal(&resolved, "the export to finish", &Signal::new(), &mut cond, |_, raised, _, _| (raised, true)).unwrap_err(); + assert!(text.starts_with("timed out waiting for the export to finish within 50ms"), "{text}"); + assert!(text.ends_with("the signal was not raised after the last check"), "{text}"); + assert_eq!(calls, 1); } #[test] #[should_panic(expected = "condition boom")] fn wait_until_propagates_condition_panic() { - wait_until(long(), "a panicking condition", || panic!("condition boom")); + wait_until(long(), "a panicking condition", &Signal::new(), || panic!("condition boom")); } #[test] fn wait_until_keeps_a_typed_condition_payload() { #[derive(Debug, PartialEq)] struct Marker(u32); - let payload = catch_unwind(|| wait_until(long(), "a typed panic", || std::panic::panic_any(Marker(9)))).unwrap_err(); + let payload = catch_unwind(|| wait_until(long(), "a typed panic", &Signal::new(), || std::panic::panic_any(Marker(9)))).unwrap_err(); assert_eq!(payload.downcast_ref::(), Some(&Marker(9))); } - /// A default limit for the loop tests, which pass their own clock. + /// A limit for the loop tests, which pass their own wait. fn fake_resolved(limit: Duration) -> Resolved<'static> { Resolved { limit, variable: UNSET, from_variable: false } } - #[test] - fn wait_until_rejects_a_true_after_the_limit() { - let resolved = fake_resolved(Duration::from_millis(10)); - let mut now = Duration::ZERO; - let mut cond = || true; - // The condition took 11 ms to return. - let mut elapsed = || { - now += Duration::from_millis(11); - now - }; - let result = poll_until(&resolved, "a late flag", &mut cond, &mut elapsed, &mut |_| panic!("paused")); - let text = result.unwrap_err(); - assert!(text.contains("timed out waiting for a late flag") && text.contains("held only after the limit"), "{text}"); - } - - #[test] - fn wait_until_pauses_grow_and_stop_at_the_limit() { - let resolved = fake_resolved(Duration::from_millis(100)); - let now = std::cell::Cell::new(Duration::ZERO); - let mut pauses = Vec::new(); - let mut calls = 0; - let mut cond = || { - calls += 1; - false - }; - let mut elapsed = || now.get(); - let mut pause = |d: Duration| { - pauses.push(d); - now.set(now.get() + d); - }; - let result = poll_until(&resolved, "never", &mut cond, &mut elapsed, &mut pause); - assert!(result.is_err()); - let ms: Vec = pauses.iter().map(Duration::as_millis).collect(); - // 1 + 2 + 4 + 8 + 16 + 32 = 63, then the 37 ms left, after which the limit is reached. - assert_eq!(ms, [1, 2, 4, 8, 16, 32, 37]); - // One call before each pause, and none after the last one. - assert_eq!(calls, 7); - } - - #[test] - fn wait_until_stops_calling_after_an_overshooting_pause() { - let resolved = fake_resolved(Duration::from_millis(100)); - let now = std::cell::Cell::new(Duration::from_millis(99)); - let mut calls = 0; - let mut cond = || { - calls += 1; - false - }; - let mut elapsed = || now.get(); - // The thread wakes 50 ms late from the 1 ms pause. - let mut pause = |d: Duration| now.set(now.get() + d + Duration::from_millis(50)); - let result = poll_until(&resolved, "late wake", &mut cond, &mut elapsed, &mut pause); - assert!(result.unwrap_err().contains("timed out waiting for late wake")); - assert_eq!(calls, 1); - } - - /// Runs `run_with_deadline` with a 5 s limit on a fake clock. The worker runs on the calling - /// thread: the clock reads `start_secs` while the body runs and `received_secs` when the result - /// is received. When `sends` is false, the worker stores its result but does not send, as if its - /// thread stopped running between the two. - fn on_fake_clock( - f: impl FnOnce() -> T + Send + 'static, - start_secs: u64, - received_secs: u64, - sends: bool, - ) -> Result { - let now = Arc::new(AtomicU64::new(0)); - let clock_now = Arc::clone(&now); - let clock: Clock = Arc::new(move || Duration::from_secs(clock_now.load(Ordering::SeqCst))); - let unsent = std::cell::RefCell::new(None); + /// Runs `run_with_deadline` on `f` with the body's result arriving only after the limit has + /// passed: the body does not start until the wait for it, which runs it on the calling thread + /// and then reports that the limit passed. The worker never sends. + fn finishing_after_the_limit(f: impl FnOnce() -> T + Send + 'static) -> Result { + let held = RefCell::new(None); let spawn = |job: Job, done: Sender<()>| { - now.store(start_secs, Ordering::SeqCst); - job(); - now.store(received_secs, Ordering::SeqCst); - if sends { - let _ = done.send(()); - } else { - // Kept alive so that the wait times out instead of seeing a closed channel. - *unsent.borrow_mut() = Some(done); - } + *held.borrow_mut() = Some((job, done)); Ok(()) }; - let limit = DeadlineLimit::new(Duration::from_secs(5)).with_variable(UNSET); - run_with_deadline(limit, "fake clock", f, |_| None, spawn, clock) + let wait = |_: &Receiver<()>, _: Duration| { + if let Some((job, _done)) = held.borrow_mut().take() { + job(); + } + Err(RecvTimeoutError::Timeout) + }; + run_with_deadline(short(), "late body", f, |_| None, spawn, wait) } #[test] - fn a_value_returned_after_the_limit_fails() { - let text = failure_message(on_fake_clock(|| 1, 6, 6, true)); - assert!(text.contains("fake clock finished only after its limit of 5s"), "{text}"); + fn a_value_that_arrives_after_the_limit_is_returned() { + assert!(matches!(finishing_after_the_limit(|| 1), Ok(1))); } #[test] - fn a_value_finished_in_time_but_received_late_passes() { - assert!(matches!(on_fake_clock(|| 1, 1, 6, true), Ok(1))); - } - - #[test] - fn a_value_finished_in_time_but_sent_late_passes() { - assert!(matches!(on_fake_clock(|| 1, 1, 6, false), Ok(1))); - } - - #[test] - fn a_panic_finished_in_time_but_sent_late_keeps_its_payload() { - let payload = match on_fake_clock(|| -> u8 { panic!("early boom") }, 1, 6, false) { + fn a_panic_that_arrives_after_the_limit_keeps_its_payload() { + let payload = match finishing_after_the_limit(|| -> u8 { panic!("late boom") }) { Err(Failure::Panic(payload)) => payload, Ok(_) => panic!("the call did not fail"), Err(Failure::Message(text)) => panic!("the payload was replaced: {text}"), }; - assert_eq!(message(payload), "early boom"); - } - - #[test] - fn a_panic_after_the_limit_names_the_limit_and_the_panic() { - let text = failure_message(on_fake_clock(|| -> u8 { panic!("late boom") }, 6, 6, true)); - assert!(text.contains("fake clock finished only after its limit of 5s") && text.ends_with("(it panicked: late boom)"), "{text}"); + assert_eq!(message(payload), "late boom"); } } diff --git a/crates/testkit/src/hostile.rs b/crates/testkit/src/hostile.rs index 2b34819e6c..d2b919029c 100644 --- a/crates/testkit/src/hostile.rs +++ b/crates/testkit/src/hostile.rs @@ -389,7 +389,9 @@ fn read_variable(name: &str) -> Option { /// that panics or does not finish within the config's limit. /// /// The cases run one after another on one worker thread, while the calling thread fails the test -/// when a case runs past the config's limit. A case that finishes after the limit also fails it. A +/// when a case is still running once the config's limit has passed since it started. The limit +/// guards against a hang: a case that has finished, however long it took, passes or fails on what +/// `parse` did, and the number of cases depends only on the seed, the rounds and the divisor. A /// failure starts with the config's label and names the case (`the unmodified seed`, /// `truncation to N` or the mutation's edits), the input's length and the panic's message. A case /// that does not finish fails the test while the worker thread is left running, so `parse` must be @@ -436,7 +438,13 @@ where let start = Instant::now(); let limit = resolve(&config.timeout, &lookup, start).map(Limit::from).map_err(|error| format!("{label}: {error}"))?; let clock: Clock = Arc::new(move || start.elapsed()); - run_cases(label.to_owned(), limit, Arc::from(seed), rounds, divisor, parse, clock) + run_cases(label.to_owned(), limit, Arc::from(seed), rounds, divisor, parse, clock, wait_for_worker) +} + +/// Waits on `signal` for at most `wait`, or less when the wait wakes early. +#[cfg(not(target_arch = "wasm32"))] +fn wait_for_worker<'g>(signal: &Condvar, state: MutexGuard<'g, Progress>, wait: Duration) -> MutexGuard<'g, Progress> { + signal.wait_timeout(state, wait).unwrap_or_else(PoisonError::into_inner).0 } /// A clock that returns the time since a [`hammer`] call started. @@ -473,11 +481,11 @@ struct Progress { outcome: Option>, } -/// [`Progress`] under a lock, with a signal for when the worker stops. +/// [`Progress`] under a lock, with a signal for when a case starts and when the worker stops. #[cfg(not(target_arch = "wasm32"))] struct Watch { state: Mutex, - stopped: Condvar, + changed: Condvar, } #[cfg(not(target_arch = "wasm32"))] @@ -500,27 +508,30 @@ impl Drop for Report { fn drop(&mut self) { let mut state = self.watch.lock(); state.outcome = Some(std::mem::replace(&mut self.outcome, Ok(()))); - self.watch.stopped.notify_all(); + self.watch.changed.notify_all(); } } -/// Starts the worker that runs every case, then waits for it, failing when a case runs past the -/// limit. +/// Starts the worker that runs every case, then waits for it, failing when a case is still running +/// once the limit has passed since it started. `wait` waits on the watch's signal for at most the +/// given time. #[cfg(not(target_arch = "wasm32"))] -fn run_cases(label: String, limit: Limit, seed: Arc<[u8]>, rounds: usize, divisor: usize, parse: F, clock: Clock) -> Result<(), String> +#[allow(clippy::too_many_arguments)] +fn run_cases(label: String, limit: Limit, seed: Arc<[u8]>, rounds: usize, divisor: usize, parse: F, clock: Clock, wait: W) -> Result<(), String> where F: Fn(&[u8]) + Send + Sync + 'static, + W: for<'g> Fn(&Condvar, MutexGuard<'g, Progress>, Duration) -> MutexGuard<'g, Progress>, { // No case counts as running until the worker starts it, so a worker that starts late is not // reported as a case past its limit. let first = Progress { case: "the unmodified seed".to_owned(), len: seed.len(), started: clock(), running: false, outcome: None }; - let watch = Arc::new(Watch { state: Mutex::new(first), stopped: Condvar::new() }); - let (worker_watch, worker_clock, worker_label, worker_limit) = (Arc::clone(&watch), Arc::clone(&clock), label.clone(), limit.clone()); + let watch = Arc::new(Watch { state: Mutex::new(first), changed: Condvar::new() }); + let (worker_watch, worker_clock, worker_label) = (Arc::clone(&watch), Arc::clone(&clock), label.clone()); thread::Builder::new() .name(WORKER_NAME.to_owned()) .spawn(move || { let mut report = Report { watch: worker_watch, outcome: Err(format!("{worker_label}: the worker thread stopped without a result")) }; - report.outcome = run_all(&report.watch, &worker_clock, &worker_label, &worker_limit, &seed, rounds, divisor, &parse); + report.outcome = run_all(&report.watch, &worker_clock, &worker_label, &seed, rounds, divisor, &parse); }) .map_err(|error| format!("{label}: could not start the worker thread: {error}"))?; let mut state = watch.lock(); @@ -533,57 +544,43 @@ where if state.running && now >= deadline { return Err(format!("{label}: {} (len {}) did not finish within {}; its thread is left running", state.case, state.len, limit.text)); } - let wait = if state.running { deadline.saturating_sub(now) } else { limit.limit }; - state = watch.stopped.wait_timeout(state, wait).unwrap_or_else(PoisonError::into_inner).0; + let wait_for = if state.running { deadline.saturating_sub(now) } else { limit.limit }; + state = wait(&watch.changed, state, wait_for); } } /// Runs the unmodified seed, every `divisor`-th truncation and its mutations in order, stopping at /// the first failure. #[cfg(not(target_arch = "wasm32"))] -#[allow(clippy::too_many_arguments)] -fn run_all( - watch: &Watch, - clock: &Clock, - label: &str, - limit: &Limit, - seed: &[u8], - rounds: usize, - divisor: usize, - parse: &F, -) -> Result<(), String> { +fn run_all(watch: &Watch, clock: &Clock, label: &str, seed: &[u8], rounds: usize, divisor: usize, parse: &F) -> Result<(), String> { for n in std::iter::once(seed.len()).chain((0..seed.len()).step_by(divisor)) { let case = if n == seed.len() { "the unmodified seed".to_owned() } else { format!("truncation to {n}") }; - run_one(watch, clock, label, limit, case, seed.get(..n).unwrap_or_default(), parse)?; + run_one(watch, clock, label, case, seed.get(..n).unwrap_or_default(), parse)?; } for mutation in mutations(seed, rounds) { - run_one(watch, clock, label, limit, mutation.label, &mutation.bytes, parse)?; + run_one(watch, clock, label, mutation.label, &mutation.bytes, parse)?; } Ok(()) } /// Runs one case, recording it in `watch` while it runs, and returns the failure's message when it -/// panics or finishes after the limit. +/// panics. How long the case took does not change its result. #[cfg(not(target_arch = "wasm32"))] -fn run_one(watch: &Watch, clock: &Clock, label: &str, limit: &Limit, case: String, data: &[u8], parse: &F) -> Result<(), String> { +fn run_one(watch: &Watch, clock: &Clock, label: &str, case: String, data: &[u8], parse: &F) -> Result<(), String> { let started = clock(); { let mut state = watch.lock(); (state.case, state.len, state.started, state.running) = (case, data.len(), started, true); + // Wakes the calling thread so that it waits on this case's limit. + watch.changed.notify_all(); } let outcome = catch_unwind(AssertUnwindSafe(|| parse(data))); - let spent = clock().saturating_sub(started); // The payload is dropped before the lock is taken and while the case still counts as running, so // the watchdog still reports a payload whose drop does not return. let panicked = outcome.err().map(|payload| panic_text(payload.as_ref())); let mut state = watch.lock(); state.running = false; - let name = || format!("{label}: {} (len {})", state.case, state.len); - if spent > limit.limit { - let panicked = panicked.map_or_else(String::new, |text| format!(" (it panicked: {text})")); - return Err(format!("{} finished only after its limit of {}{panicked}", name(), limit.text)); - } - panicked.map_or(Ok(()), |text| Err(format!("{}: the parser panicked: {text}", name()))) + panicked.map_or(Ok(()), |text| Err(format!("{label}: {} (len {}): the parser panicked: {text}", state.case, state.len))) } /// The text of a panic payload. @@ -602,6 +599,7 @@ mod tests { use super::*; use std::collections::BTreeMap; use std::sync::Mutex; + use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc; /// A variable no test sets, so the environment cannot change a test's rounds or limits. @@ -641,36 +639,44 @@ mod tests { #[test] fn deadline_names_stuck_case() { - let (release, wait) = mpsc::channel::<()>(); - let wait = Mutex::new(wait); - let short = config("stuck demo", 0).with_timeout(DeadlineLimit::new(Duration::from_millis(50)).with_variable(UNSET)); - let result = hammer_with( - &short, - &[1, 2, 3], - move |d| { - if d.len() == 3 { - let _ = wait.lock().unwrap().recv(); - } - }, - unset, - ); + // The clock jumps an hour ahead the first time the calling thread waits while a case runs. + let now = Arc::new(AtomicU64::new(0)); + let clock_now = Arc::clone(&now); + let clock: Clock = Arc::new(move || Duration::from_secs(clock_now.load(Ordering::SeqCst))); + let (release, blocked) = mpsc::channel::<()>(); + let blocked = Mutex::new(blocked); + let parse = move |d: &[u8]| { + if d.len() == 3 { + let _ = blocked.lock().unwrap().recv(); + } + }; + let limit = Limit { limit: Duration::from_millis(50), text: "50ms".to_owned() }; + let result = run_cases("stuck demo".to_owned(), limit, Arc::from(&[1u8, 2, 3][..]), 0, 1, parse, clock, |signal, state, _| { + if state.running { + now.store(3600, Ordering::SeqCst); + state + } else { + signal.wait(state).unwrap_or_else(PoisonError::into_inner) + } + }); release.send(()).unwrap(); - let message = result.unwrap_err(); - assert!(message.contains("stuck demo: the unmodified seed (len 3) did not finish within 50ms"), "{message}"); + assert_eq!(result, Err("stuck demo: the unmodified seed (len 3) did not finish within 50ms; its thread is left running".to_owned())); } #[test] - fn a_case_that_finishes_after_the_limit_fails() { - let readings = Arc::new(Mutex::new(vec![Duration::from_secs(6), Duration::ZERO])); - let clock: Clock = Arc::new(move || readings.lock().unwrap().pop().unwrap_or(Duration::MAX)); - let watch = Watch { - state: Mutex::new(Progress { case: String::new(), len: 0, started: Duration::ZERO, running: true, outcome: None }), - stopped: Condvar::new(), - }; + fn a_case_that_finishes_after_the_limit_passes() { + // By the worker's clock the first case takes six seconds against a limit of five; the calling + // thread's clock stays at zero, so the watchdog does not fire. + let worker_readings = Mutex::new(vec![Duration::from_secs(6), Duration::ZERO]); + let clock: Clock = Arc::new(move || { + if thread::current().name() == Some(WORKER_NAME) { + worker_readings.lock().unwrap().pop().unwrap_or(Duration::from_secs(6)) + } else { + Duration::ZERO + } + }); let limit = Limit { limit: Duration::from_secs(5), text: "5s".to_owned() }; - let message = run_one(&watch, &clock, "late", &limit, "the unmodified seed".to_owned(), &[1], &|_: &[u8]| {}).unwrap_err(); - assert_eq!(message, "late: the unmodified seed (len 1) finished only after its limit of 5s"); - assert!(!watch.lock().running); + assert_eq!(run_cases("slow".to_owned(), limit, Arc::from(&[1u8][..]), 0, 1, |_: &[u8]| {}, clock, wait_for_worker), Ok(())); } /// A panic payload that records, when it is dropped, whether the progress lock was free and @@ -691,14 +697,13 @@ mod tests { fn a_panic_payload_is_dropped_outside_the_lock_while_the_case_runs() { let watch = Arc::new(Watch { state: Mutex::new(Progress { case: String::new(), len: 0, started: Duration::ZERO, running: false, outcome: None }), - stopped: Condvar::new(), + changed: Condvar::new(), }); let seen = Arc::new(Mutex::new(None)); let clock: Clock = Arc::new(|| Duration::ZERO); - let limit = Limit { limit: Duration::from_secs(5), text: "5s".to_owned() }; let probe = (Arc::clone(&watch), Arc::clone(&seen)); let parse = move |_: &[u8]| std::panic::panic_any(DropProbe { watch: Arc::clone(&probe.0), seen: Arc::clone(&probe.1) }); - let message = run_one(&watch, &clock, "probe", &limit, "the unmodified seed".to_owned(), &[1], &parse).unwrap_err(); + let message = run_one(&watch, &clock, "probe", "the unmodified seed".to_owned(), &[1], &parse).unwrap_err(); assert_eq!(message, "probe: the unmodified seed (len 1): the parser panicked: a payload that is not a message"); assert_eq!(*seen.lock().unwrap(), Some(Some(true)), "the payload was dropped with the lock held or the case stopped"); assert!(!watch.lock().running); @@ -725,7 +730,7 @@ mod tests { Duration::ZERO }); let limit = Limit { limit: Duration::from_secs(5), text: "5s".to_owned() }; - assert_eq!(run_cases("late start".to_owned(), limit, Arc::from(&[1u8][..]), 0, 1, |_: &[u8]| {}, clock), Ok(())); + assert_eq!(run_cases("late start".to_owned(), limit, Arc::from(&[1u8][..]), 0, 1, |_: &[u8]| {}, clock, wait_for_worker), Ok(())); } #[test] diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 3feb5129ca..397913bb00 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -17,9 +17,10 @@ //! [`rng`] holds two seeded generators for repeatable test input, [`rng::XorShift64`] and //! [`rng::XorShift64Star`], each with `next`, `below`, `byte` and `fill`. //! -//! On targets other than `wasm32`, [`deadline::with_deadline`] runs a test body on its own thread -//! and fails the test when the body does not finish within its limit, and [`deadline::wait_until`] -//! polls a condition until it holds and fails the test when the limit passes first. Both read an +//! On targets other than `wasm32`, `deadline::with_deadline` runs a test body on its own thread +//! and fails the test when the body has produced no result within its limit, and +//! `deadline::wait_until` calls a condition again each time a `deadline::Signal` is raised until +//! it holds, and fails the test when the signal is not raised within the limit. Both read an //! optional limit variable that the caller names, `CRAFT_TEST_TIMEOUT_SECS` by default. //! //! [`hostile::mutations`] yields a fixed sequence of damaged copies of a valid seed, on every @@ -52,7 +53,7 @@ pub mod sample_damage; pub mod serial; #[cfg(not(target_arch = "wasm32"))] -pub use deadline::{DeadlineLimit, wait_until, with_deadline}; +pub use deadline::{DeadlineLimit, Signal, wait_until, with_deadline}; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; #[cfg(not(target_arch = "wasm32"))] From 519a4a781674f7c3d44c37fa8a816b5e397c0de8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:13:35 -0800 Subject: [PATCH 27/33] automation: the control-channel tests wait on the server's signals instead of on time Seven tests let real time decide their result: a 400 ms authentication deadline with an elapsed-time bound, retry loops that waited up to 5 s and 10 s for a freed connection slot, 300 ms windows in which no request was to arrive, and polling loops with 5 ms sleeps. - AuthDeadlineStream::with_clock reads its deadline against a clock the caller passes; new keeps the real clock. A unit test moves a hand-set clock past the deadline and shows that a read fails with input waiting, and that input sent before the deadline does not move it. - server::serve_with (hidden, for tests) takes ServeOptions: the authentication deadline, its clock, and a sender that gets () each time a connection has ended, after its request sender is dropped and its place under MAX_CONNECTIONS is free. serve_with_deadline calls it. - The connection-limit tests wait for that signal and connect once. - The tests that check nothing reached the app stop the server, wait for its connections to end, and assert that the request receiver is disconnected. - The capture-client test blocks on each request and takes it through ControlChannel::next_request. - The client test blocks in a peek until the unasked line has arrived, then checks is_usable. Every assertion is kept. The remaining timeouts only stop a hung test. --- crates/automation/src/client_tests.rs | 6 +- crates/automation/src/security.rs | 28 ++++- crates/automation/src/security_tests.rs | 31 +++++ crates/automation/src/server.rs | 46 ++++++- crates/automation/tests/it/control.rs | 153 +++++++++++++----------- 5 files changed, 182 insertions(+), 82 deletions(-) diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index 46687dae3b..8a767ddd21 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -103,10 +103,8 @@ fn an_unasked_line_makes_the_connection_unusable_before_sending() { let mut client = ControlClient::connect(addr, TOKEN).unwrap(); assert!(client.is_usable(), "an idle connection with nothing pending is usable"); said.send(()).unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while client.is_usable() && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(5)); - } + // A blocking peek (under the client's read timeout) returns once the line has arrived. + assert!(client.stream.peek(&mut [0]).unwrap() > 0, "the unasked line arrived"); assert!(!client.is_usable(), "the unasked line makes the connection unusable"); assert_eq!(client.call("next", json!({})), Err("connection closed".to_string())); assert!(client.is_broken(), "the unusable connection is closed"); diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 8e75f07ecd..180a331752 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -487,20 +487,40 @@ pub fn configure_stream(stream: &std::net::TcpStream) -> std::io::Result<()> { stream.set_write_timeout(Some(IO_TIMEOUT)) } +/// The time an [`AuthDeadlineStream`] reads its deadline against: [`Instant::now`] in a server, or a time a test sets +/// by hand. +pub type DeadlineClock = std::sync::Arc Instant + Send + Sync>; + +/// The real clock, [`Instant::now`]. +pub fn real_clock() -> DeadlineClock { + std::sync::Arc::new(Instant::now) +} + /// A read wrapper that fails once [`AUTH_DEADLINE`] passes without [`Self::authenticated`] being /// called, whatever the client sends meanwhile; after that only [`IO_TIMEOUT`] applies. -#[derive(Debug)] pub struct AuthDeadlineStream { inner: std::net::TcpStream, deadline: Option, + clock: DeadlineClock, +} + +impl std::fmt::Debug for AuthDeadlineStream { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AuthDeadlineStream").field("inner", &self.inner).field("deadline", &self.deadline).finish_non_exhaustive() + } } impl AuthDeadlineStream { /// Wraps `inner`; reads fail once `auth_deadline` has passed unauthenticated. pub fn new(inner: std::net::TcpStream, auth_deadline: Duration) -> Self { + Self::with_clock(inner, auth_deadline, real_clock()) + } + + /// [`Self::new`] with the deadline read against `clock` instead of the real clock. + pub fn with_clock(inner: std::net::TcpStream, auth_deadline: Duration, clock: DeadlineClock) -> Self { // A limit too large to represent expires at once rather than never. - let now = Instant::now(); - Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)) } + let now = clock(); + Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)), clock } } /// The handshake succeeded: lift the deadline and restore the idle timeout. @@ -513,7 +533,7 @@ impl AuthDeadlineStream { impl std::io::Read for AuthDeadlineStream { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { if let Some(deadline) = self.deadline { - let left = deadline.saturating_duration_since(Instant::now()); + let left = deadline.saturating_duration_since((self.clock)()); if left.is_zero() { return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "not authenticated in time")); } diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index 2716fc24c2..2d3625c0a7 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -170,6 +170,37 @@ fn server_token_sources_and_validation() { ); } +// An unauthenticated connection's reads succeed while its deadline is ahead, however much it sends, and fail once the +// deadline has passed even with input waiting; after `authenticated` the deadline no longer applies. +#[trial] +fn the_authentication_deadline_holds_whatever_the_client_sends() { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (server, _) = listener.accept().unwrap(); + server.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let start = Instant::now(); + let at = std::sync::Arc::new(std::sync::Mutex::new(start)); + let read_at = std::sync::Arc::clone(&at); + let clock: DeadlineClock = std::sync::Arc::new(move || *read_at.lock().unwrap()); + let mut stream = AuthDeadlineStream::with_clock(server.try_clone().unwrap(), Duration::from_secs(10), clock); + let mut byte = [0]; + // Blank lines and partial frames, each read while the deadline is ahead. + for (step, sent) in [b"\n", b" ", b"{", b"\n"].into_iter().enumerate() { + *at.lock().unwrap() = start + Duration::from_secs(3 * step as u64); + client.write_all(sent).unwrap(); + assert_eq!(stream.read(&mut byte).unwrap(), 1, "read {step} is before the deadline"); + } + *at.lock().unwrap() = start + Duration::from_secs(10); + client.write_all(b"\n").unwrap(); + let late = stream.read(&mut byte).unwrap_err(); + assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "the input sent did not move the deadline: {late}"); + + stream.authenticated().unwrap(); + *at.lock().unwrap() = start + Duration::from_secs(60); + assert_eq!(stream.read(&mut byte).unwrap(), 1, "an authenticated connection reads past the deadline"); +} + // A token file create that runs out of time fails with its own error, even when it left a file at // the path: that file is not read as another process's. A create that another process beat to the // path reads that process's token. diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index c6808156d7..e913cf3b4c 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -16,8 +16,8 @@ use serde_json::{Value, json}; use crate::control::{ControlRequest, REPLY_DEADLINE}; use crate::protocol::write_reply; use crate::security::{ - AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream, - read_bounded_line, repeat_auth_reply, + AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, DeadlineClock, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, + configure_stream, read_bounded_line, real_clock, repeat_auth_reply, }; /// A running control server. Dropping it stops accepting connections and returns once the port is @@ -72,6 +72,36 @@ pub fn serve_with_deadline( host: WindowHost, auth_deadline: Duration, ) -> std::io::Result<(Receiver, Listening)> { + serve_with(listener, token, host, ServeOptions { auth_deadline, ..ServeOptions::default() }) +} + +/// What a test sets on a server [`serve_with`] starts. +#[doc(hidden)] +pub struct ServeOptions { + /// How long a connection has to authenticate ([`AUTH_DEADLINE`] in [`serve`]). + pub auth_deadline: Duration, + /// The clock the authentication deadline is read against. + pub clock: DeadlineClock, + /// Sent `()` each time a connection has ended: its request sender is dropped and its place under + /// [`MAX_CONNECTIONS`] is free again. + pub ended: Option>, +} + +impl Default for ServeOptions { + fn default() -> Self { + Self { auth_deadline: AUTH_DEADLINE, clock: real_clock(), ended: None } + } +} + +/// [`serve`] with the authentication deadline, its clock and a signal for each ended connection set by a test. +#[doc(hidden)] +pub fn serve_with( + listener: TcpListener, + token: String, + host: WindowHost, + options: ServeOptions, +) -> std::io::Result<(Receiver, Listening)> { + let ServeOptions { auth_deadline, clock, ended } = options; let (tx, rx) = channel::(); let addr = listener.local_addr()?; // `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept @@ -95,13 +125,19 @@ pub fn serve_with_deadline( let tx = tx.clone(); let host = host.clone(); let token = Arc::clone(&token); + let clock = Arc::clone(&clock); + let ended = ended.clone(); std::thread::spawn(move || { - serve_connection(stream, &token, &tx, &host, auth_deadline); + serve_connection(stream, &token, &tx, &host, auth_deadline, clock); + drop(tx); // What the last client held down would otherwise stay held with no one left to // release it; while another connection is live, its input is left alone. if permit.release() { host.end_injection(); } + if let Some(ended) = ended { + let _ = ended.send(()); + } }); } })?; @@ -110,12 +146,12 @@ pub fn serve_with_deadline( /// Serve one connection: it must authenticate ([`ServerHandshake`]) within `auth_deadline` of /// connecting, however much it sends meanwhile; after that only the idle timeout applies. -fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration) { +fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration, clock: DeadlineClock) { if configure_stream(&stream).is_err() { return; } let Ok(read) = stream.try_clone() else { return }; - let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline)); + let mut reader = BufReader::new(AuthDeadlineStream::with_clock(read, auth_deadline, clock)); let mut out = stream; let mut line = String::new(); let mut handshake = ServerHandshake::new(); diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index 913d02d16a..a17f3e1f12 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -2,14 +2,15 @@ use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; -use std::sync::mpsc::{Receiver, channel}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use craft_automation::client::ControlClient; use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error}; use craft_automation::protocol::MAX_RESPONSE_BYTES; use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; -use craft_automation::server; +use craft_automation::server::{self, ServeOptions}; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use craft_ui::testing::trial; @@ -101,26 +102,30 @@ fn host() -> WindowHost { /// sent is dispatched. #[trial] fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { - // A short deadline, so the test does not wait out the real one. - let deadline = Duration::from_millis(400); - let listener = TcpListener::bind("127.0.0.1:0").expect("bound"); - let (rx, server) = server::serve_with_deadline(listener, TOKEN.into(), host(), deadline).expect("started"); - // Blank lines and partial frames, one byte every 20 ms: each read succeeds long before the idle timeout. + let start = motion::now(); + let at = Arc::new(Mutex::new(start)); + let read_at = Arc::clone(&at); + let (ended, connection_ended) = channel(); + // Each read of the clock is announced, so the test moves it only after the connection has set its deadline. + let (read, clock_read) = channel(); + let clock = Arc::new(move || { + let now = *read_at.lock().expect("the clock"); + let _ = read.send(()); + now + }); + let options = ServeOptions { auth_deadline: Duration::from_secs(10), clock, ended: Some(ended) }; + let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); let mut stream = TcpStream::connect(server.addr).expect("connected"); - let started = motion::now(); - let mut closed = false; - for i in 0..1000 { - let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " }; - if stream.write_all(byte).is_err() { - closed = true; - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - let served = started.elapsed(); - assert!(closed, "the trickle did not keep the connection open"); - assert!(served < deadline + Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}"); - assert!(rx.try_recv().is_err(), "nothing was dispatched"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + clock_read.recv_timeout(Duration::from_secs(5)).expect("the connection set its deadline"); + // Blank lines and the start of a line, sent while the deadline is ahead: none is a frame the handshake refuses. + stream.write_all(b"\n \n ").expect("written"); + *at.lock().expect("the clock") = start + Duration::from_secs(10); + // The server may already have closed when this is written; if not, it wakes the server's read. + let _ = stream.write_all(b" "); + assert!(is_closed(&mut reader), "the input sent did not keep the connection open past the deadline"); + assert!(nothing_more_dispatched(&rx, server, &connection_ended, 1), "nothing was dispatched"); } /// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error. @@ -129,11 +134,31 @@ fn is_closed(reader: &mut impl BufRead) -> bool { matches!(reader.read_line(&mut line), Ok(0)) } +/// A server whose `ended` receiver gets `()` each time one of its connections has ended. Its clock stands still, so no +/// connection reaches the authentication deadline: only the client or a refusal ends one. +fn serve_counting_ends() -> (Receiver, server::Listening, Receiver<()>) { + let (ended, connection_ended) = channel(); + let start = motion::now(); + let options = ServeOptions { clock: Arc::new(move || start), ended: Some(ended), ..ServeOptions::default() }; + let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); + (rx, server, connection_ended) +} + +/// Stops `server` and waits for its `connections` connections to end, so the request receiver `rx` is disconnected +/// once every request that reached it has been taken: `rx` then answers whether anything more was dispatched. +fn nothing_more_dispatched(rx: &Receiver, server: server::Listening, ended: &Receiver<()>, connections: usize) -> bool { + drop(server); + for _ in 0..connections { + ended.recv_timeout(Duration::from_secs(5)).expect("a connection ended"); + } + rx.recv_timeout(Duration::from_secs(5)).err() == Some(RecvTimeoutError::Disconnected) +} + /// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of /// the open ones ends, its place serves a new connection. #[trial] fn connections_past_the_limit_are_refused_with_the_reason() { - let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (rx, server, ended) = serve_counting_ends(); let connect = || { let stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); @@ -150,20 +175,14 @@ fn connections_past_the_limit_are_refused_with_the_reason() { drop(open.pop()); // The server frees the place when it reads the close; a new connection is served once it has. - let started = motion::now(); - let served = loop { - let (mut stream, mut reader) = connect(); - writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); - let reply = read_json(&mut reader).expect("a reply"); - if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) { - break reply; - } - assert_eq!(reply["error"], "connection limit reached", "{reply}"); - std::thread::sleep(Duration::from_millis(20)); - }; + ended.recv_timeout(Duration::from_secs(5)).expect("the closed connection ended"); + let (mut stream, mut reader) = connect(); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); + let served = read_json(&mut reader).expect("a reply"); assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}"); - assert!(rx.try_recv().is_err(), "nothing was dispatched"); + drop((stream, reader)); drop(open); + assert!(nothing_more_dispatched(&rx, server, &ended, MAX_CONNECTIONS), "nothing was dispatched"); } /// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the @@ -191,9 +210,8 @@ fn a_refused_first_frame_closes_the_connection() { /// and the connection closed, so neither the body's `auth` nor a request after it reaches the app. #[trial] fn a_browser_post_never_reaches_the_app() { - // Far longer than the trial, so the close comes from the refusal, not the deadline. - let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) - .expect("started"); + // The server's clock stands still, so the close comes from the refusal, not the deadline. + let (rx, server, ended) = serve_counting_ends(); let mut stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); @@ -211,7 +229,8 @@ fn a_browser_post_never_reaches_the_app() { Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), }; assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}"); - assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app"); + drop((stream, reader)); + assert!(nothing_more_dispatched(&rx, server, &ended, 1), "nothing reached the app"); } /// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed. @@ -325,19 +344,19 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() { let mut client = ControlClient::connect(addr, TOKEN).expect("connected"); capture_state(&mut client, &client_doc, &client_doc["states"][0], "new") }); - let mut channel = ControlChannel::new(requests); + // Each request is waited for as it arrives and then taken through the channel, as the app's frame takes it. + let (forward, forwarded) = channel(); + let mut channel = ControlChannel::new(forwarded); let mut seen: Vec = Vec::new(); - let started = motion::now(); - while seen.len() < 4 && started.elapsed() < Duration::from_secs(10) { - while let Some(req) = channel.next_request() { - seen.push(format!("{} {}", req.method, req.params)); - let reply = match req.method.as_str() { - "ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))), - _ => Reply::from_result(Ok(Value::Null)), - }; - channel.settle(req, reply, None, 0.0); - } - std::thread::sleep(Duration::from_millis(5)); + while seen.len() < 4 { + forward.send(requests.recv_timeout(Duration::from_secs(10)).expect("a request")).expect("forwarded"); + let req = channel.next_request().expect("the forwarded request is dispatched"); + seen.push(format!("{} {}", req.method, req.params)); + let reply = match req.method.as_str() { + "ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))), + _ => Reply::from_result(Ok(Value::Null)), + }; + channel.settle(req, reply, None, 0.0); } let reply = client.join().expect("client ran").expect("the capture replied"); assert_eq!( @@ -440,12 +459,12 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() { /// and shut its end down) still reaches the app and is answered: a client cannot know it was dropped. #[trial] fn a_complete_json_request_at_eof_can_reach_the_app() { - let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (rx, server, ended) = serve_counting_ends(); let handler = std::thread::spawn(move || { let req = rx.recv_timeout(Duration::from_secs(5)).expect("the request reached the app"); assert_eq!(req.method, "test.once"); req.reply.send(json!({"ok": true, "result": "once"})).expect("replied"); - assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "it ran exactly once"); + rx }); let (mut stream, mut reader) = authenticated(server.addr); stream.write_all(json!({"id": 3, "method": "test.once"}).to_string().as_bytes()).expect("written"); @@ -454,7 +473,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() { assert_eq!((&reply["id"], &reply["result"]), (&json!(3), &json!("once"))); let mut rest = String::new(); assert_eq!(reader.read_line(&mut rest).expect("closed, not timed out"), 0, "closed after the last request: {rest:?}"); - handler.join().expect("handler ran"); + let rx = handler.join().expect("handler ran"); + assert!(nothing_more_dispatched(&rx, server, &ended, 1), "it ran exactly once"); } /// Ported from WordCraft (#7317). Connections that never authenticate cannot fill the server: past the limit a new @@ -462,9 +482,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() { #[trial] fn idle_unauthenticated_connections_are_limited() { use craft_automation::security::MAX_CONNECTIONS; - // Far longer than the trial, so only the limit refuses. - let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) - .expect("started"); + // The server's clock stands still, so only the limit refuses. + let (rx, server, ended) = serve_counting_ends(); let idle: Vec = (0..MAX_CONNECTIONS).map(|_| TcpStream::connect(server.addr).expect("connected")).collect(); // Admission is counted by the accept thread: it is done once the next connection is answered. let refused = |addr| { @@ -477,18 +496,14 @@ fn idle_unauthenticated_connections_are_limited() { assert!(reply["error"].as_str().is_some_and(|e| e.contains("limit")), "{reply}"); drop(idle); // The freed slots go back as the closed connections are noticed. - let started = motion::now(); - loop { - let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); - let mut reader = BufReader::new(stream.try_clone().expect("cloned")); - // A refused connection may already be closed when the request is written (Windows resets it). - let auth = json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}}); - if writeln!(stream, "{auth}").is_ok() && read_json(&mut reader).is_some_and(|r| r["ok"] == true) { - break; - } - assert!(started.elapsed() < Duration::from_secs(10), "no slot came back"); - std::thread::sleep(Duration::from_millis(50)); + for _ in 0..MAX_CONNECTIONS { + ended.recv_timeout(Duration::from_secs(5)).expect("a closed connection ended"); } - assert!(rx.try_recv().is_err()); + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written"); + assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true, "a freed slot is admitted again"); + drop((stream, reader)); + assert!(nothing_more_dispatched(&rx, server, &ended, 1)); } From 0d6990ac904075e75f72fcb2b32389efca3a6fc4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 19:50:55 -0800 Subject: [PATCH 28/33] automation: the frozen-clock test server keeps a 30-second socket wait The frozen clock in `serve_counting_ends` keeps the time left to the authentication deadline at 10 seconds, and the server's socket read timeout, which runs on real time, was set to that. A test that paused for more than 10 seconds would then see the server drop its waiting connections. The helper now sets a 60-second deadline, so each read waits for the 30-second idle timeout, as before. --- crates/automation/tests/it/control.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index a17f3e1f12..c0645eac0c 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -135,11 +135,14 @@ fn is_closed(reader: &mut impl BufRead) -> bool { } /// A server whose `ended` receiver gets `()` each time one of its connections has ended. Its clock stands still, so no -/// connection reaches the authentication deadline: only the client or a refusal ends one. +/// connection reaches the authentication deadline: only the client or a refusal ends one. The frozen clock does not +/// stop the socket's read timeout, which runs on real time and is the time left to the deadline capped at the idle +/// timeout. The deadline is a minute, so a waiting connection's read times out after the 30-second idle timeout +/// instead of after 10 seconds. fn serve_counting_ends() -> (Receiver, server::Listening, Receiver<()>) { let (ended, connection_ended) = channel(); let start = motion::now(); - let options = ServeOptions { clock: Arc::new(move || start), ended: Some(ended), ..ServeOptions::default() }; + let options = ServeOptions { auth_deadline: Duration::from_secs(60), clock: Arc::new(move || start), ended: Some(ended) }; let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); (rx, server, connection_ended) } From c85c5c553cdfd7f3a86c22bf336a8bd82dcfa0a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:13:28 -0800 Subject: [PATCH 29/33] automation: a reset connection counts as closed in the control tests When the server closes a connection with input still unread, the kernel sends a reset, and the client's read fails with ConnectionReset or ConnectionAborted instead of returning the end of the stream. is_closed returned false for that, so the deadline test could fail, mostly on Windows. is_closed now treats any read error other than a timeout as a close, as a_browser_post_never_reaches_the_app already did, and a new test checks the reset, abort and timeout cases. --- crates/automation/tests/it/control.rs | 28 +++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index c0645eac0c..6e1dc700fc 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -128,10 +128,34 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { assert!(nothing_more_dispatched(&rx, server, &connection_ended, 1), "nothing was dispatched"); } -/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error. +/// Whether the server closed the connection: the next read is the end of the stream, or an error other than a timeout. +/// A server that closes with input still unread makes the kernel send a reset, so the read fails with +/// `ConnectionReset` or `ConnectionAborted` instead of returning the end of the stream (mostly on Windows). fn is_closed(reader: &mut impl BufRead) -> bool { let mut line = String::new(); - matches!(reader.read_line(&mut line), Ok(0)) + match reader.read_line(&mut line) { + Ok(read) => read == 0, + Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), + } +} + +/// A reader whose every read fails with the given error kind. +struct Failing(std::io::ErrorKind); + +impl std::io::Read for Failing { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(self.0.into()) + } +} + +/// A reset or aborted connection counts as closed; a read timeout does not. +#[trial] +fn a_reset_connection_counts_as_closed() { + use std::io::ErrorKind::{ConnectionAborted, ConnectionReset, TimedOut, WouldBlock}; + assert!(is_closed(&mut BufReader::new(Failing(ConnectionReset))), "a reset is a close"); + assert!(is_closed(&mut BufReader::new(Failing(ConnectionAborted))), "an abort is a close"); + assert!(!is_closed(&mut BufReader::new(Failing(TimedOut))), "a timeout is not a close"); + assert!(!is_closed(&mut BufReader::new(Failing(WouldBlock))), "a timeout is not a close"); } /// A server whose `ended` receiver gets `()` each time one of its connections has ended. Its clock stands still, so no From f41b28a53ca6a65bf7e4f9b68344ff06057d60bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:15:25 -0800 Subject: [PATCH 30/33] craft-testkit: wait_until's limit counts from the start of the call The limit restarted after every call of the condition, so a thread that kept raising the signal while the condition stayed false held wait_until forever. The limit now counts from the start of the call, and each wait lasts at most the time left. The condition is still called before the limit is checked, so a condition that holds never fails. Two tests cover it: an injected clock with a wait that always reports a raise, and a real thread raising in a loop under with_deadline. Both fail without the change. --- crates/testkit/README.md | 5 +- crates/testkit/src/deadline.rs | 83 +++++++++++++++++++++++++++++----- crates/testkit/src/lib.rs | 2 +- 3 files changed, 75 insertions(+), 15 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 2db97d7ad2..e61d810c63 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -115,8 +115,9 @@ of the thread. `wait_until(limit, what, &signal, cond)` calls `cond` on the test's thread at once, and again each time another thread calls `signal.raise()`, until `cond` returns `true`. The thread that changes the state `cond` reads raises the `Signal` after each change. A raise that comes while `cond` runs makes -`wait_until` call `cond` again straight after. When the signal is not raised within the limit after a -call that returned `false`, the test fails with a message that names `what`. +`wait_until` call `cond` again straight after. The limit counts from the start of the call. When the +limit has passed and the latest call of `cond` returned `false`, the test fails with a message that +names `what`, even if the signal is still being raised. ```rust use std::time::Duration; diff --git a/crates/testkit/src/deadline.rs b/crates/testkit/src/deadline.rs index fa582b340a..9e00f9a606 100644 --- a/crates/testkit/src/deadline.rs +++ b/crates/testkit/src/deadline.rs @@ -11,8 +11,8 @@ //! //! [`wait_until`] calls a condition on the test's thread, and calls it again each time another //! thread raises the [`Signal`] the call waits on. It returns when the condition returns `true`, and -//! fails the test with its description when the signal is not raised within the limit after a call -//! that returned `false`. +//! fails the test with its description when the limit has passed since the call began and the latest +//! call of the condition returned `false`. //! //! A limit is a default [`Duration`] and the name of a variable that replaces it. A plain `Duration` //! reads [`DEFAULT_VARIABLE`]; [`DeadlineLimit::with_variable`] names another one. The variable holds @@ -155,12 +155,14 @@ pub fn with_deadline<'a, T: Send + 'static>(limit: impl Into>, } /// Calls `cond` on the calling thread, and again each time `signal` is raised, until it returns -/// `true`, failing the calling test when `signal` is not raised within the limit after a call that -/// returned `false`. +/// `true`, failing the calling test when the limit has passed since the call began and the latest +/// call of `cond` returned `false`. /// /// `cond` is called at once. A raise that comes while `cond` runs is not lost: `cond` is called -/// again straight after. The limit guards against a hang and counts afresh from each call of `cond`, -/// so a condition that holds is never failed by it. The failure names `what`, the limit and the +/// again straight after. The limit guards against a hang and counts from the start of the call, so +/// a signal that keeps being raised while `cond` stays `false` still fails the test. `cond` is +/// called before the limit is checked, so a condition that holds is never failed by it. The failure +/// names `what`, the limit and the /// variable that sets it. A panic in `cond` reaches the caller unchanged. `cond` runs on the calling /// thread and is not interrupted, so it must return promptly. The threads that change what `cond` /// reads raise `signal` after each change. @@ -189,7 +191,7 @@ pub fn wait_until<'a>(limit: impl Into>, what: &str, signal: & Ok(resolved) => resolved, Err(error) => panic!("waiting for {what}: {error}"), }; - if let Err(message) = wait_for_signal(&resolved, what, signal, &mut cond, wait_for_raise) { + if let Err(message) = wait_for_signal(&resolved, what, signal, &mut cond, Instant::now, wait_for_raise) { panic!("{message}"); } } @@ -354,21 +356,28 @@ fn wait_for_raise<'g>(changed: &Condvar, raised: MutexGuard<'g, u64>, seen: u64, (raised, result.timed_out()) } -/// The loop of [`wait_until`], with the wait for a raise passed in. The raise count is read before -/// each call of `cond`, so a raise during the call ends the next wait at once. +/// The loop of [`wait_until`], with the clock and the wait for a raise passed in. The raise count is +/// read before each call of `cond`, so a raise during the call ends the next wait at once. The limit +/// counts from the start of the loop, and each wait lasts at most the time left. fn wait_for_signal( resolved: &Resolved<'_>, what: &str, signal: &Signal, cond: &mut dyn FnMut() -> bool, + now: impl Fn() -> Instant, wait: impl for<'g> Fn(&Condvar, MutexGuard<'g, u64>, u64, Duration) -> (MutexGuard<'g, u64>, bool), ) -> Result<(), String> { + let start = now(); let mut seen = *signal.lock(); loop { if cond() { return Ok(()); } - let (raised, timed_out) = wait(&signal.changed, signal.lock(), seen, resolved.limit); + let remaining = resolved.limit.saturating_sub(now().saturating_duration_since(start)); + if remaining.is_zero() { + return Err(format!("timed out waiting for {what} within {resolved}: the condition still returned false at the limit")); + } + let (raised, timed_out) = wait(&signal.changed, signal.lock(), seen, remaining); if timed_out { return Err(format!("timed out waiting for {what} within {resolved}: the signal was not raised after the last check")); } @@ -662,7 +671,7 @@ mod tests { } calls == 2 }; - let result = wait_for_signal(&fake_resolved(Duration::from_secs(600)), "a raise", &signal, &mut cond, |_, raised, seen, _| { + let result = wait_for_signal(&fake_resolved(Duration::from_secs(600)), "a raise", &signal, &mut cond, Instant::now, |_, raised, seen, _| { assert_ne!(*raised, seen, "the raise made during the condition was lost"); (raised, false) }); @@ -678,12 +687,62 @@ mod tests { false }; let resolved = fake_resolved(Duration::from_millis(50)); - let text = wait_for_signal(&resolved, "the export to finish", &Signal::new(), &mut cond, |_, raised, _, _| (raised, true)).unwrap_err(); + let text = wait_for_signal(&resolved, "the export to finish", &Signal::new(), &mut cond, Instant::now, |_, raised, _, _| (raised, true)) + .unwrap_err(); assert!(text.starts_with("timed out waiting for the export to finish within 50ms"), "{text}"); assert!(text.ends_with("the signal was not raised after the last check"), "{text}"); assert_eq!(calls, 1); } + #[test] + fn raises_that_never_satisfy_the_condition_fail_at_the_limit() { + // A clock that moves 20 s on each reading, and a wait that always reports a raise. + let start = Instant::now(); + let readings = std::cell::Cell::new(0u32); + let now = || { + let n = readings.get(); + readings.set(n + 1); + start + Duration::from_secs(20) * n + }; + let mut calls = 0; + let mut cond = || { + calls += 1; + false + }; + let resolved = fake_resolved(Duration::from_secs(60)); + let text = wait_for_signal(&resolved, "a progress tick", &Signal::new(), &mut cond, now, |_, mut raised, _, _| { + *raised = raised.wrapping_add(1); + (raised, false) + }) + .unwrap_err(); + assert!(text.starts_with("timed out waiting for a progress tick within 60s"), "{text}"); + assert!(text.ends_with("the condition still returned false at the limit"), "{text}"); + assert_eq!(calls, 3); + } + + #[test] + fn a_thread_raising_in_a_loop_cannot_hold_wait_until_past_the_limit() { + let stop = Arc::new(AtomicBool::new(false)); + let signal = Arc::new(Signal::new()); + let raiser = { + let (stop, signal) = (Arc::clone(&stop), Arc::clone(&signal)); + thread::spawn(move || { + while !stop.load(Ordering::SeqCst) { + signal.raise(); + thread::yield_now(); + } + }) + }; + let waiter_signal = Arc::clone(&signal); + let guard = DeadlineLimit::new(Duration::from_secs(30)).with_variable(UNSET); + let outcome = with_deadline(guard, "wait_until under constant raises", move || { + catch_unwind(AssertUnwindSafe(|| wait_until(short(), "a condition that never holds", &waiter_signal, || false))).map_err(message) + }); + stop.store(true, Ordering::SeqCst); + raiser.join().unwrap(); + let text = outcome.unwrap_err(); + assert!(text.contains("timed out waiting for a condition that never holds within 50ms"), "{text}"); + } #[test] #[should_panic(expected = "condition boom")] fn wait_until_propagates_condition_panic() { diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 3d46f0c672..c019b8b696 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -20,7 +20,7 @@ //! On targets other than `wasm32`, `deadline::with_deadline` runs a test body on its own thread //! and fails the test when the body has produced no result within its limit, and //! `deadline::wait_until` calls a condition again each time a `deadline::Signal` is raised until -//! it holds, and fails the test when the signal is not raised within the limit. Both read an +//! it holds, and fails the test when it still does not hold at the limit. Both read an //! optional limit variable that the caller names, `CRAFT_TEST_TIMEOUT_SECS` by default. //! //! [`hostile::mutations`] yields a fixed sequence of damaged copies of a valid seed, on every From 92ab88d4415c03fd4b37f6db1ca2f48228f81b4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:17:04 -0800 Subject: [PATCH 31/33] craft-testkit: crate docs describe late results and shared rechecks with_deadline returns a result that arrives before the limit is checked, and wait_until checks its condition once for any number of raises that came during one call of it. --- crates/testkit/src/lib.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index c019b8b696..1e899b6420 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -18,10 +18,12 @@ //! [`rng::XorShift64Star`], each with `next`, `below`, `byte` and `fill`. //! //! On targets other than `wasm32`, `deadline::with_deadline` runs a test body on its own thread -//! and fails the test when the body has produced no result within its limit, and -//! `deadline::wait_until` calls a condition again each time a `deadline::Signal` is raised until -//! it holds, and fails the test when it still does not hold at the limit. Both read an -//! optional limit variable that the caller names, `CRAFT_TEST_TIMEOUT_SECS` by default. +//! and fails the test when the body still has no result once the limit has passed; a result that +//! arrives before that check is returned. `deadline::wait_until` calls a condition, and when a +//! `deadline::Signal` raise wakes it, checks the condition again until it holds; raises that come +//! during one call of the condition share one recheck. It fails the test when the condition still +//! does not hold at the limit. Both read an optional limit variable that the caller names, +//! `CRAFT_TEST_TIMEOUT_SECS` by default. //! //! [`hostile::mutations`] yields a fixed sequence of damaged copies of a valid seed, on every //! target. On targets other than `wasm32`, `hostile::hammer` runs a parser on the seed, every From e6eac94fbc5ff9c3c338f74f71bc84b95601116b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 28 Nov 2026 12:47:41 +0100 Subject: [PATCH 32/33] ui-contract: a timed repaint off the UI thread reads no pass state (photocraft#17279) `repaint::request_after` read the pass clock to note the wake in an open replay record, also on a thread with no running pass (the control server's `WindowHost::repaint_in`). The read moved the context's pass state to that thread for a moment, and a UI pass starting then ran on an empty default state, which was parked afterwards: no command sets, no app catalog, every command shown by its id until a restart. The clock is now read only while a record is open on this thread, the only case `note_wake` notes anything in. --- .../ui-contract/src/runtime/egui/repaint.rs | 2 +- crates/ui-contract/src/runtime/replay.rs | 9 ++++++++ .../ui-contract/src/testing/replay_trials.rs | 23 +++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/runtime/egui/repaint.rs b/crates/ui-contract/src/runtime/egui/repaint.rs index b8b5e9e1ca..7eba495107 100644 --- a/crates/ui-contract/src/runtime/egui/repaint.rs +++ b/crates/ui-contract/src/runtime/egui/repaint.rs @@ -18,7 +18,7 @@ pub(crate) fn request_of(ctx: &Context, viewport: egui::ViewportId) { /// Asks for one pass of `viewport` after `seconds`; the earliest request of a frame wins. pub(crate) fn request_after(ctx: &Context, viewport: egui::ViewportId, seconds: f64) { - crate::runtime::replay::note_wake(ctx, crate::runtime::frame::clock(ctx) + seconds); + crate::runtime::replay::note_wake_in(ctx, seconds); ctx.request_repaint_after_for(std::time::Duration::from_secs_f64(seconds.max(0.0)), viewport); } diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 2adadc14b6..5cd522991b 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -566,6 +566,15 @@ pub(crate) fn note_wake(ctx: &Context, at: f64) { with_open(ctx, |facts| facts.wake = min_wake(facts.wake, Some(at))); } +/// Notes that the running code asks to be shown again `seconds` from now on the pass clock. The clock is read only +/// while a record is open: a timed wake from a job's thread or the control server's reads no pass state, so it never +/// takes the state from a pass that starts meanwhile (which would run on an empty one). +pub(crate) fn note_wake_in(ctx: &Context, seconds: f64) { + if any_open() { + note_wake(ctx, frame::clock(ctx) + seconds); + } +} + /// Notes that the running code showed the overlay layer `layer` at the screen rect `rect`. Called by the journaled /// registration of the layer's `Area`, so a record that replays it notes it again in the records open around it. pub(crate) fn note_overlay(ctx: &Context, layer: Layer, rect: Rect) { diff --git a/crates/ui-contract/src/testing/replay_trials.rs b/crates/ui-contract/src/testing/replay_trials.rs index 222c7f5007..85872df2d4 100644 --- a/crates/ui-contract/src/testing/replay_trials.rs +++ b/crates/ui-contract/src/testing/replay_trials.rs @@ -27,6 +27,29 @@ fn a_repaint_from_a_job_thread_leaves_the_running_pass_s_records_alone() { assert_eq!(joined, Some(true), "the job thread's repaint request returns"); } +// The same for a timed wake (the control server's `WindowHost::repaint_in`): it reads no pass state either. Reading the +// pass clock there took the state from the UI thread, and a pass that started meanwhile ran on an empty one, with no +// command sets: every command showed its id as its label, and a tool rail lost its icons. +#[trial] +fn a_timed_repaint_from_a_job_thread_reads_no_pass_state() { + let mut frames = Frames::new(); + let mut unbound = None; + frames.frame(Vec::new(), |ui| { + let ctx = ui.ctx().clone(); + replay::open(&ctx); + let worker = ctx.clone(); + unbound = std::thread::spawn(move || { + let before = crate::runtime::pass_state::unbound_reads(); + repaint::request_after(&worker, egui::ViewportId::ROOT, 0.5); + crate::runtime::pass_state::unbound_reads() - before + }) + .join() + .ok(); + let _record = replay::close(&ctx, fixture::layer_of(ui)); + }); + assert_eq!(unbound, Some(0), "the job thread's timed repaint request returns and reads no pass state"); +} + /// Records one frame's run of `run` in `frames`. fn record(frames: &mut Frames, mut run: impl FnMut(&egui::Context)) -> replay::Record { let mut record = None; From 6b41fb681440d85daa15416550436e258a408d73 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 18:55:41 +0700 Subject: [PATCH 33/33] craft-xtask: compare canonical paths in the working-directory test On macOS the temp directory is under /var, a link to /private/var, so current_dir() reads back the /private/var path and the assert failed on main's macOS gate. --- crates/xtask/src/names.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs index c20337f604..e75ece461e 100644 --- a/crates/xtask/src/names.rs +++ b/crates/xtask/src/names.rs @@ -2857,7 +2857,9 @@ fn seven() { let _ = "seven"; } let policy = Policy { skip: change_directory, ..POLICY }; let found = scan(Path::new("."), &[Input::rust(Path::new("src"))], &policy).unwrap(); assert_eq!(hits(&found), [("src/a.rs".to_owned(), 1, "AzureKit")]); - assert_eq!(std::env::current_dir().unwrap(), PathBuf::from(root).join("switched")); + // Canonical on both sides: macOS temp paths run through the /var -> /private/var link. + let canonical = |p: PathBuf| p.canonicalize().unwrap(); + assert_eq!(canonical(std::env::current_dir().unwrap()), canonical(PathBuf::from(root).join("switched"))); return; } let dir = tempfile::tempdir().unwrap();