test(property): frame roundtrip, canonicalization, span, content-ref bytes, secret masking laws
f97b510237a713e75da10b58bac5046fd05885bd
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: b7c906b5935d
There are many coding harnesses - but this one is fast
f97b510237a713e75da10b58bac5046fd05885bd
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+550 / −2 text lines
+160 / −2 text lines
[[package]]name = "bit-set"version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"dependencies = [ "bit-vec",][[package]]name = "bit-vec"version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"[[package]]name = "proptest"version = "1.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"dependencies = [ "bit-set", "bit-vec", "bitflags", "num-traits", "rand", "rand_chacha", "rand_xorshift", "regex-syntax", "rusty-fork", "tempfile", "unarray",][[package]]name = "rand"version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"dependencies = [ "rand_chacha", "rand_core",][[package]]name = "rand_chacha"version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"dependencies = [ "ppv-lite86", "rand_core",][[package]]name = "rand_core"version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"dependencies = [ "getrandom 0.3.4",][[package]]name = "rand_xorshift"version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"dependencies = [ "rand_core",] "proptest",[[package]]name = "tempfile"version = "3.27.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", "rustix", "windows-sys 0.61.2",]+1 / −0 text lines
+59 / −0 text lines
/// Secret masking laws (`SMH-SPEC-SPEC0001`, Compaction, cost, and secrets).////// Secret values use `[A-Z0-9]`, possibly empty, names `[a-z]`, and filler text never holds/// `{`: no value can match inside a placeholder and no input holds one, the/// precondition under which masking is reversible.#[cfg(test)]mod properties { use super::SecretProxy; use proptest::collection::vec; use proptest::prelude::*; /// Registered secrets and a text interleaving filler with their values. fn secrets_and_text() -> impl Strategy<Value = (Vec<(String, String)>, String)> { vec(("[a-z]{1,6}", "[A-Z0-9]{0,8}"), 1..5).prop_flat_map(|secrets| { let count = secrets.len(); let pieces = vec(("[^{]{0,12}", proptest::option::of(0..count)), 0..6); (Just(secrets), pieces).prop_map(|(secrets, pieces)| { let mut text = String::new(); for (filler, secret) in pieces { text.push_str(&filler); if let Some(index) = secret { text.push_str(&secrets[index].1); } } (secrets, text) }) }) } fn proxy(secrets: &[(String, String)]) -> SecretProxy { let mut proxy = SecretProxy::new(); for (name, value) in secrets { proxy.register(name.clone(), value.clone()); } proxy } proptest! { #[test] fn unmask_restores_masked_text((secrets, text) in secrets_and_text()) { let proxy = proxy(&secrets); prop_assert_eq!(proxy.unmask(&proxy.mask(&text)), text); } #[test] fn masked_text_holds_no_registered_value((secrets, text) in secrets_and_text()) { let masked = proxy(&secrets).mask(&text); // A later registration under the same name replaces the value. let registered: std::collections::HashMap<&str, &str> = secrets .iter() .map(|(name, value)| (name.as_str(), value.as_str())) .collect(); for value in registered.values().filter(|value| !value.is_empty()) { prop_assert!(!masked.contains(value), "{value} survived in {masked}"); } } }}+97 / −0 text lines
/// Frame stream round-trip law (`SMH-SPEC-SPEC0001`, Sessions).#[cfg(test)]mod properties { use super::*; use crate::session::EntryKind; use crate::session::properties::role; use proptest::collection::vec; use proptest::prelude::*; use smith::id::{BranchId, EntryId, MessageId, SessionId, ToolCallId}; fn kind() -> impl Strategy<Value = EntryKind> { prop_oneof![ (any::<u128>(), role()).prop_map(|(id, role)| EntryKind::Message { id: MessageId::from_u128(id), role, }), any::<u128>().prop_map(|id| EntryKind::ToolCall { call_id: ToolCallId::from_u128(id), }), (any::<u128>(), any::<bool>()).prop_map(|(id, ok)| EntryKind::ToolResult { call_id: ToolCallId::from_u128(id), ok, }), any::<bool>().prop_map(|compaction| EntryKind::Meta { compaction }), ] } /// Any frame this build writes: header, entry with opaque content bytes, /// or a frame of a kind it does not know. fn frame() -> impl Strategy<Value = Frame> { prop_oneof![ (any::<u128>(), any::<u128>()).prop_map(|(session, branch)| Frame::Header { header: SessionHeader { session_id: SessionId::from_u128(session), branch_id: BranchId::from_u128(branch), }, }), ( any::<u128>(), proptest::option::of(any::<u128>()), any::<i64>(), kind(), vec(any::<u8>(), 0..64), ) .prop_map(|(id, parent, timestamp_ms, kind, content)| Frame::Known { entry: EntryFrame { id: EntryId::from_u128(id), parent: parent.map(EntryId::from_u128), timestamp_ms, kind, content, }, }), ( any::<u16>().prop_filter("known kinds decode as known", |kind| { !matches!(*kind, KIND_ENTRY | KIND_SESSION_HEADER) }), any::<u16>(), vec(any::<u8>(), 0..64), ) .prop_map(|(kind, version, payload)| Frame::Unknown { kind, version, payload, }), ] } proptest! { #[test] fn encoded_frame_streams_decode_to_the_same_frames(frames in vec(frame(), 0..8)) { let mut bytes = Vec::new(); for frame in &frames { bytes.extend( frame .encode(DEFAULT_MAX_FRAME_BYTES) .map_err(|e| TestCaseError::fail(e.to_string()))?, ); } let recovery = read_frames(&mut bytes.as_slice(), DEFAULT_MAX_FRAME_BYTES); prop_assert!(recovery.damage.is_empty(), "damage: {:?}", recovery.damage); prop_assert_eq!(recovery.torn_tail_at, None); prop_assert_eq!(recovery.good_end, bytes.len() as u64); let mut again = Vec::new(); for frame in &recovery.frames { again.extend( frame .encode(DEFAULT_MAX_FRAME_BYTES) .map_err(|e| TestCaseError::fail(e.to_string()))?, ); } prop_assert_eq!(recovery.frames, frames); prop_assert_eq!(again, bytes); } }}+233 / −0 text lines
/// Laws of canonicalization, span arithmetic, and content encoding/// (`SMH-SPEC-SPEC0001`, Sessions).////// `serde_json` preserves insertion order but compares maps order-blind, so/// key-order laws compare serialized bytes, never values.#[cfg(test)]pub mod properties { use super::*; use proptest::collection::vec; use proptest::prelude::*; use serde_json::Value; /// Arbitrary JSON, at most three levels deep and 24 nodes large. fn json() -> impl Strategy<Value = Value> { let leaf = prop_oneof![ Just(Value::Null), any::<bool>().prop_map(Value::from), any::<i64>().prop_map(Value::from), any::<u64>().prop_map(Value::from), (proptest::num::f64::NORMAL | proptest::num::f64::ZERO).prop_map(Value::from), "\\PC{0,8}".prop_map(Value::from), ]; leaf.prop_recursive(3, 24, 4, |inner| { prop_oneof![ vec(inner.clone(), 0..4).prop_map(Value::Array), vec(("\\PC{0,4}", inner), 0..5) .prop_map(|entries| Value::Object(entries.into_iter().collect())), ] }) } /// `value` with the keys of every object reordered as `seed` dictates. fn reordered(value: &Value, seed: u64) -> Value { match value { Value::Object(map) => { let mut entries: Vec<(String, Value)> = map .iter() .map(|(key, value)| (key.clone(), reordered(value, seed.rotate_left(7)))) .collect(); if !entries.is_empty() { let by = usize::try_from(seed % entries.len() as u64).unwrap_or(0); entries.rotate_left(by); } if seed & 1 == 1 { entries.reverse(); } Value::Object(entries.into_iter().collect()) } Value::Array(items) => Value::Array( items .iter() .map(|item| reordered(item, seed.rotate_left(7))) .collect(), ), other => other.clone(), } } fn json_bytes(value: &Value) -> std::result::Result<Vec<u8>, TestCaseError> { serde_json::to_vec(value).map_err(|e| TestCaseError::fail(e.to_string())) } fn cbor<T: Serialize>(value: &T) -> std::result::Result<Vec<u8>, TestCaseError> { let mut out = Vec::new(); ciborium::ser::into_writer(value, &mut out) .map(|()| out) .map_err(|e| TestCaseError::fail(e.to_string())) } /// Any message role. pub fn role() -> impl Strategy<Value = Role> { prop_oneof![ Just(Role::User), Just(Role::Assistant), Just(Role::System), Just(Role::Tool), ] } fn block() -> impl Strategy<Value = ContentBlock> { prop_oneof![ "\\PC{0,16}".prop_map(ContentBlock::Text), "\\PC{0,16}".prop_map(ContentBlock::Thinking), ("\\PC{0,8}", json(), any::<u128>()).prop_map(|(name, input, id)| { ContentBlock::tool_use(name, input, ToolCallId::from_u128(id)) }), (any::<u128>(), any::<bool>(), "\\PC{0,16}").prop_map(|(id, ok, output)| { ContentBlock::tool_result(ToolCallId::from_u128(id), ok, output) }), ] } fn content() -> impl Strategy<Value = EntryContent> { prop_oneof![ (any::<u128>(), role(), vec(block(), 0..4), any::<i64>()).prop_map( |(id, role, blocks, timestamp_ms)| EntryContent::Message(Message { id: MessageId::from_u128(id), role, blocks, timestamp_ms, }) ), ("\\PC{0,8}", json(), any::<u128>()).prop_map(|(name, input, id)| { EntryContent::ToolCall { name, input, call_id: ToolCallId::from_u128(id), } }), (any::<bool>(), "\\PC{0,16}", any::<u128>()).prop_map(|(ok, output, id)| { EntryContent::ToolResult { ok, output, call_id: ToolCallId::from_u128(id), } }), ( prop_oneof![ Just(COMPACTION_KIND.to_string()), Just(PROVIDER_HTTP_KIND.to_string()), "\\PC{0,8}", ], json() ) .prop_map(|(kind, detail)| EntryContent::Meta { kind, detail }), ] } /// `content` with every JSON value in canonical key order. fn canonical_content(content: &EntryContent) -> EntryContent { match content { EntryContent::Message(message) => EntryContent::Message(canonical_message_of(message)), EntryContent::ToolCall { name, input, call_id, } => EntryContent::ToolCall { name: name.clone(), input: canonical_json(input), call_id: *call_id, }, EntryContent::ToolResult { .. } => content.clone(), EntryContent::Meta { kind, detail } => EntryContent::Meta { kind: kind.clone(), detail: canonical_json(detail), }, } } /// Offsets and lengths around the 4 GiB arena cap, plus anything. fn arena_size() -> impl Strategy<Value = usize> { let cap = u32::MAX as usize; prop_oneof![ 0..=cap, cap - 64..=cap + 64, (0..=64_usize).prop_map(move |below| cap - below), any::<usize>(), ] } proptest! { #[test] fn canonical_json_is_idempotent_and_keeps_the_value(value in json()) { let once = canonical_json(&value); prop_assert_eq!(json_bytes(&canonical_json(&once))?, json_bytes(&once)?); prop_assert!(is_canonical(&once)); prop_assert_eq!(once, value); } #[test] fn canonical_json_ignores_key_order(value in json(), seed in any::<u64>()) { let shuffled = reordered(&value, seed); prop_assert_eq!( json_bytes(&canonical_json(&shuffled))?, json_bytes(&canonical_json(&value))? ); } #[test] fn is_canonical_holds_exactly_when_canonicalizing_changes_nothing(value in json()) { prop_assert_eq!( is_canonical(&value), json_bytes(&canonical_json(&value))? == json_bytes(&value)? ); } #[test] fn span_at_is_exact_below_the_cap_and_an_error_above( offset in arena_size(), len in arena_size(), ) { let fits = offset .checked_add(len) .is_some_and(|end| u32::try_from(end).is_ok()); match Span::at(offset, len) { Ok(span) => { prop_assert!(fits); prop_assert_eq!(span.offset as usize, offset); prop_assert_eq!(span.len as usize, len); prop_assert_eq!(span.end(), offset + len); prop_assert_eq!(span.range().len(), len); } Err(error) => { prop_assert!(!fits); prop_assert_eq!(error.code(), "SESSION_ARENA_FULL"); } } } #[test] fn content_ref_serializes_like_owned_content(content in content()) { prop_assert_eq!(cbor(&EntryContentRef::from(&content))?, cbor(&content)?); } #[test] fn owned_and_borrowed_encodings_are_canonical_and_decode_back(content in content()) { let owned = EntryFrame::new(None, &content) .map_err(|e| TestCaseError::fail(e.to_string()))? .content; let mut session = Session::new(); let record = *session .append(EntryContentRef::from(&content)) .map_err(|e| TestCaseError::fail(e.to_string()))?; prop_assert_eq!(session.bytes(&record), owned.as_slice()); prop_assert_eq!(&owned, &cbor(&canonical_content(&content))?); prop_assert_eq!( EntryContent::decode(&owned).map_err(|e| TestCaseError::fail(e.to_string()))?, content ); } }}