repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

test(property): frame roundtrip, canonicalization, span, content-ref bytes, secret masking laws

f97b510237a713e75da10b58bac5046fd05885bd

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (5)

+550 / −2 text lines

Diff layout

Cargo.lock

Modified

+160 / −2 text lines

155155source = "registry+https://github.com/rust-lang/crates.io-index"
156156checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
158[[package]]
159name = "bit-set"
160version = "0.8.0"
161source = "registry+https://github.com/rust-lang/crates.io-index"
162checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
163dependencies = [
164 "bit-vec",
165]
167[[package]]
168name = "bit-vec"
169version = "0.8.0"
170source = "registry+https://github.com/rust-lang/crates.io-index"
171checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
158173[[package]]
159174name = "bitflags"
160175version = "2.13.2"
718733 "windows-sys 0.61.2",
736[[package]]
737name = "fastrand"
738version = "2.5.0"
739source = "registry+https://github.com/rust-lang/crates.io-index"
740checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
721742[[package]]
722743name = "find-msvc-tools"
723744version = "0.1.14"
873894 "wasi",
897[[package]]
898name = "getrandom"
899version = "0.3.4"
900source = "registry+https://github.com/rust-lang/crates.io-index"
901checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
902dependencies = [
903 "cfg-if",
904 "libc",
905 "r-efi 5.3.0",
906 "wasip2",
907]
876909[[package]]
877910name = "getrandom"
878911version = "0.4.3"
881914dependencies = [
882915 "cfg-if",
883916 "libc",
884 "r-efi",
917 "r-efi 6.0.0",
887920[[package]]
13531386 "zerovec",
1389[[package]]
1390name = "ppv-lite86"
1391version = "0.2.21"
1392source = "registry+https://github.com/rust-lang/crates.io-index"
1393checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
1394dependencies = [
1395 "zerocopy",
13561398[[package]]
13571399name = "predicates"
13581400version = "3.1.4"
14021444 "unicode-ident",
1447[[package]]
1448name = "proptest"
1449version = "1.11.0"
1450source = "registry+https://github.com/rust-lang/crates.io-index"
1451checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
1452dependencies = [
1453 "bit-set",
1454 "bit-vec",
1455 "bitflags",
1456 "num-traits",
1457 "rand",
1458 "rand_chacha",
1459 "rand_xorshift",
1460 "regex-syntax",
1461 "rusty-fork",
1462 "tempfile",
1463 "unarray",
14051466[[package]]
14061467name = "pulley-interpreter"
14071468version = "49.0.1"
14251486 "syn 2.0.119",
1489[[package]]
1490name = "quick-error"
1491version = "1.2.3"
1492source = "registry+https://github.com/rust-lang/crates.io-index"
1493checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
14281495[[package]]
14291496name = "quote"
14301497version = "1.0.47"
14341501 "proc-macro2",
1504[[package]]
1505name = "r-efi"
1506version = "5.3.0"
1507source = "registry+https://github.com/rust-lang/crates.io-index"
1508checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
14371510[[package]]
14381511name = "r-efi"
14391512version = "6.0.0"
14401513source = "registry+https://github.com/rust-lang/crates.io-index"
14411514checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
1516[[package]]
1517name = "rand"
1518version = "0.9.5"
1519source = "registry+https://github.com/rust-lang/crates.io-index"
1520checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
1521dependencies = [
1522 "rand_chacha",
1523 "rand_core",
1526[[package]]
1527name = "rand_chacha"
1528version = "0.9.0"
1529source = "registry+https://github.com/rust-lang/crates.io-index"
1530checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
1531dependencies = [
1532 "ppv-lite86",
1533 "rand_core",
1536[[package]]
1537name = "rand_core"
1538version = "0.9.5"
1539source = "registry+https://github.com/rust-lang/crates.io-index"
1540checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
1541dependencies = [
1542 "getrandom 0.3.4",
1545[[package]]
1546name = "rand_xorshift"
1547version = "0.4.0"
1548source = "registry+https://github.com/rust-lang/crates.io-index"
1549checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
1550dependencies = [
1551 "rand_core",
14431554[[package]]
14441555name = "rayon"
14451556version = "1.12.0"
15941705source = "registry+https://github.com/rust-lang/crates.io-index"
15951706checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
1708[[package]]
1709name = "rusty-fork"
1710version = "0.3.1"
1711source = "registry+https://github.com/rust-lang/crates.io-index"
1712checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
1713dependencies = [
1714 "fnv",
1715 "quick-error",
1716 "tempfile",
1717 "wait-timeout",
15971720[[package]]
15981721name = "same-file"
15991722version = "1.0.6"
17841907 "futures",
17851908 "ignore",
17861909 "nix",
1910 "proptest",
17871911 "serde",
17881912 "serde_json",
17891913 "smith",
18081932name = "smith-plugin-echo"
18091933version = "0.1.0"
18101934dependencies = [
1811 "wit-bindgen",
1935 "wit-bindgen 0.62.0",
18141938[[package]]
18872011source = "registry+https://github.com/rust-lang/crates.io-index"
18882012checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
2014[[package]]
2015name = "tempfile"
2016version = "3.27.0"
2017source = "registry+https://github.com/rust-lang/crates.io-index"
2018checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
2019dependencies = [
2020 "fastrand",
2021 "getrandom 0.4.3",
2022 "once_cell",
2023 "rustix",
2024 "windows-sys 0.61.2",
18902027[[package]]
18912028name = "termcolor"
18922029version = "1.4.1"
20242161source = "registry+https://github.com/rust-lang/crates.io-index"
20252162checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
2164[[package]]
2165name = "unarray"
2166version = "0.1.4"
2167source = "registry+https://github.com/rust-lang/crates.io-index"
2168checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
20272170[[package]]
20282171name = "unicode-ident"
20292172version = "1.0.26"
21432286source = "registry+https://github.com/rust-lang/crates.io-index"
21442287checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
2289[[package]]
2290name = "wasip2"
2291version = "1.0.4+wasi-0.2.12"
2292source = "registry+https://github.com/rust-lang/crates.io-index"
2293checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
2294dependencies = [
2295 "wit-bindgen 0.57.1",
21462298[[package]]
21472299name = "wasm-bindgen"
21482300version = "0.2.129"
26172769 "memchr",
2772[[package]]
2773name = "wit-bindgen"
2774version = "0.57.1"
2775source = "registry+https://github.com/rust-lang/crates.io-index"
2776checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
26202778[[package]]
26212779name = "wit-bindgen"
26222780version = "0.62.0"

smith-core/Cargo.toml

Modified

+1 / −0 text lines

2222[dev-dependencies]
2323smith-alloc = { path = "../smith-alloc", version = "0.1.0" }
24proptest = { workspace = true }

smith-core/src/agent.rs

Modified

+59 / −0 text lines

12281228 let _ = std::fs::remove_dir_all(&dir);
1232/// Secret masking laws (`SMH-SPEC-SPEC0001`, Compaction, cost, and secrets).
1233///
1234/// Secret values use `[A-Z0-9]`, possibly empty, names `[a-z]`, and filler text never holds
1235/// `{`: no value can match inside a placeholder and no input holds one, the
1236/// precondition under which masking is reversible.
1237#[cfg(test)]
1238mod properties {
1239 use super::SecretProxy;
1240 use proptest::collection::vec;
1241 use proptest::prelude::*;
1243 /// Registered secrets and a text interleaving filler with their values.
1244 fn secrets_and_text() -> impl Strategy<Value = (Vec<(String, String)>, String)> {
1245 vec(("[a-z]{1,6}", "[A-Z0-9]{0,8}"), 1..5).prop_flat_map(|secrets| {
1246 let count = secrets.len();
1247 let pieces = vec(("[^{]{0,12}", proptest::option::of(0..count)), 0..6);
1248 (Just(secrets), pieces).prop_map(|(secrets, pieces)| {
1249 let mut text = String::new();
1250 for (filler, secret) in pieces {
1251 text.push_str(&filler);
1252 if let Some(index) = secret {
1253 text.push_str(&secrets[index].1);
1254 }
1255 }
1256 (secrets, text)
1257 })
1258 })
1259 }
1261 fn proxy(secrets: &[(String, String)]) -> SecretProxy {
1262 let mut proxy = SecretProxy::new();
1263 for (name, value) in secrets {
1264 proxy.register(name.clone(), value.clone());
1265 }
1266 proxy
1267 }
1269 proptest! {
1270 #[test]
1271 fn unmask_restores_masked_text((secrets, text) in secrets_and_text()) {
1272 let proxy = proxy(&secrets);
1273 prop_assert_eq!(proxy.unmask(&proxy.mask(&text)), text);
1274 }
1276 #[test]
1277 fn masked_text_holds_no_registered_value((secrets, text) in secrets_and_text()) {
1278 let masked = proxy(&secrets).mask(&text);
1279 // A later registration under the same name replaces the value.
1280 let registered: std::collections::HashMap<&str, &str> = secrets
1281 .iter()
1282 .map(|(name, value)| (name.as_str(), value.as_str()))
1283 .collect();
1284 for value in registered.values().filter(|value| !value.is_empty()) {
1285 prop_assert!(!masked.contains(value), "{value} survived in {masked}");
1286 }
1287 }
1288 }

smith-core/src/frame.rs

Modified

+97 / −0 text lines

797797 assert_eq!(crc32(0x3231, 0x3433, b"56789"), 0xCBF4_3926);
798798 }
801/// Frame stream round-trip law (`SMH-SPEC-SPEC0001`, Sessions).
802#[cfg(test)]
803mod properties {
804 use super::*;
805 use crate::session::EntryKind;
806 use crate::session::properties::role;
807 use proptest::collection::vec;
808 use proptest::prelude::*;
809 use smith::id::{BranchId, EntryId, MessageId, SessionId, ToolCallId};
811 fn kind() -> impl Strategy<Value = EntryKind> {
812 prop_oneof![
813 (any::<u128>(), role()).prop_map(|(id, role)| EntryKind::Message {
814 id: MessageId::from_u128(id),
815 role,
816 }),
817 any::<u128>().prop_map(|id| EntryKind::ToolCall {
818 call_id: ToolCallId::from_u128(id),
819 }),
820 (any::<u128>(), any::<bool>()).prop_map(|(id, ok)| EntryKind::ToolResult {
821 call_id: ToolCallId::from_u128(id),
822 ok,
823 }),
824 any::<bool>().prop_map(|compaction| EntryKind::Meta { compaction }),
825 ]
826 }
828 /// Any frame this build writes: header, entry with opaque content bytes,
829 /// or a frame of a kind it does not know.
830 fn frame() -> impl Strategy<Value = Frame> {
831 prop_oneof![
832 (any::<u128>(), any::<u128>()).prop_map(|(session, branch)| Frame::Header {
833 header: SessionHeader {
834 session_id: SessionId::from_u128(session),
835 branch_id: BranchId::from_u128(branch),
836 },
837 }),
838 (
839 any::<u128>(),
840 proptest::option::of(any::<u128>()),
841 any::<i64>(),
842 kind(),
843 vec(any::<u8>(), 0..64),
844 )
845 .prop_map(|(id, parent, timestamp_ms, kind, content)| Frame::Known {
846 entry: EntryFrame {
847 id: EntryId::from_u128(id),
848 parent: parent.map(EntryId::from_u128),
849 timestamp_ms,
850 kind,
851 content,
852 },
853 }),
854 (
855 any::<u16>().prop_filter("known kinds decode as known", |kind| {
856 !matches!(*kind, KIND_ENTRY | KIND_SESSION_HEADER)
857 }),
858 any::<u16>(),
859 vec(any::<u8>(), 0..64),
860 )
861 .prop_map(|(kind, version, payload)| Frame::Unknown {
862 kind,
863 version,
864 payload,
865 }),
866 ]
867 }
869 proptest! {
870 #[test]
871 fn encoded_frame_streams_decode_to_the_same_frames(frames in vec(frame(), 0..8)) {
872 let mut bytes = Vec::new();
873 for frame in &frames {
874 bytes.extend(
875 frame
876 .encode(DEFAULT_MAX_FRAME_BYTES)
877 .map_err(|e| TestCaseError::fail(e.to_string()))?,
878 );
879 }
880 let recovery = read_frames(&mut bytes.as_slice(), DEFAULT_MAX_FRAME_BYTES);
881 prop_assert!(recovery.damage.is_empty(), "damage: {:?}", recovery.damage);
882 prop_assert_eq!(recovery.torn_tail_at, None);
883 prop_assert_eq!(recovery.good_end, bytes.len() as u64);
884 let mut again = Vec::new();
885 for frame in &recovery.frames {
886 again.extend(
887 frame
888 .encode(DEFAULT_MAX_FRAME_BYTES)
889 .map_err(|e| TestCaseError::fail(e.to_string()))?,
890 );
891 }
892 prop_assert_eq!(recovery.frames, frames);
893 prop_assert_eq!(again, bytes);
894 }
895 }
896}

smith-core/src/session.rs

Modified

+233 / −0 text lines

11001100 assert_eq!(restored, session);
1104/// Laws of canonicalization, span arithmetic, and content encoding
1105/// (`SMH-SPEC-SPEC0001`, Sessions).
1106///
1107/// `serde_json` preserves insertion order but compares maps order-blind, so
1108/// key-order laws compare serialized bytes, never values.
1109#[cfg(test)]
1110pub mod properties {
1111 use super::*;
1112 use proptest::collection::vec;
1113 use proptest::prelude::*;
1114 use serde_json::Value;
1116 /// Arbitrary JSON, at most three levels deep and 24 nodes large.
1117 fn json() -> impl Strategy<Value = Value> {
1118 let leaf = prop_oneof![
1119 Just(Value::Null),
1120 any::<bool>().prop_map(Value::from),
1121 any::<i64>().prop_map(Value::from),
1122 any::<u64>().prop_map(Value::from),
1123 (proptest::num::f64::NORMAL | proptest::num::f64::ZERO).prop_map(Value::from),
1124 "\\PC{0,8}".prop_map(Value::from),
1125 ];
1126 leaf.prop_recursive(3, 24, 4, |inner| {
1127 prop_oneof![
1128 vec(inner.clone(), 0..4).prop_map(Value::Array),
1129 vec(("\\PC{0,4}", inner), 0..5)
1130 .prop_map(|entries| Value::Object(entries.into_iter().collect())),
1131 ]
1132 })
1133 }
1135 /// `value` with the keys of every object reordered as `seed` dictates.
1136 fn reordered(value: &Value, seed: u64) -> Value {
1137 match value {
1138 Value::Object(map) => {
1139 let mut entries: Vec<(String, Value)> = map
1140 .iter()
1141 .map(|(key, value)| (key.clone(), reordered(value, seed.rotate_left(7))))
1142 .collect();
1143 if !entries.is_empty() {
1144 let by = usize::try_from(seed % entries.len() as u64).unwrap_or(0);
1145 entries.rotate_left(by);
1146 }
1147 if seed & 1 == 1 {
1148 entries.reverse();
1149 }
1150 Value::Object(entries.into_iter().collect())
1151 }
1152 Value::Array(items) => Value::Array(
1153 items
1154 .iter()
1155 .map(|item| reordered(item, seed.rotate_left(7)))
1156 .collect(),
1157 ),
1158 other => other.clone(),
1159 }
1160 }
1162 fn json_bytes(value: &Value) -> std::result::Result<Vec<u8>, TestCaseError> {
1163 serde_json::to_vec(value).map_err(|e| TestCaseError::fail(e.to_string()))
1164 }
1166 fn cbor<T: Serialize>(value: &T) -> std::result::Result<Vec<u8>, TestCaseError> {
1167 let mut out = Vec::new();
1168 ciborium::ser::into_writer(value, &mut out)
1169 .map(|()| out)
1170 .map_err(|e| TestCaseError::fail(e.to_string()))
1171 }
1173 /// Any message role.
1174 pub fn role() -> impl Strategy<Value = Role> {
1175 prop_oneof![
1176 Just(Role::User),
1177 Just(Role::Assistant),
1178 Just(Role::System),
1179 Just(Role::Tool),
1180 ]
1181 }
1183 fn block() -> impl Strategy<Value = ContentBlock> {
1184 prop_oneof![
1185 "\\PC{0,16}".prop_map(ContentBlock::Text),
1186 "\\PC{0,16}".prop_map(ContentBlock::Thinking),
1187 ("\\PC{0,8}", json(), any::<u128>()).prop_map(|(name, input, id)| {
1188 ContentBlock::tool_use(name, input, ToolCallId::from_u128(id))
1189 }),
1190 (any::<u128>(), any::<bool>(), "\\PC{0,16}").prop_map(|(id, ok, output)| {
1191 ContentBlock::tool_result(ToolCallId::from_u128(id), ok, output)
1192 }),
1193 ]
1194 }
1196 fn content() -> impl Strategy<Value = EntryContent> {
1197 prop_oneof![
1198 (any::<u128>(), role(), vec(block(), 0..4), any::<i64>()).prop_map(
1199 |(id, role, blocks, timestamp_ms)| EntryContent::Message(Message {
1200 id: MessageId::from_u128(id),
1201 role,
1202 blocks,
1203 timestamp_ms,
1204 })
1205 ),
1206 ("\\PC{0,8}", json(), any::<u128>()).prop_map(|(name, input, id)| {
1207 EntryContent::ToolCall {
1208 name,
1209 input,
1210 call_id: ToolCallId::from_u128(id),
1211 }
1212 }),
1213 (any::<bool>(), "\\PC{0,16}", any::<u128>()).prop_map(|(ok, output, id)| {
1214 EntryContent::ToolResult {
1215 ok,
1216 output,
1217 call_id: ToolCallId::from_u128(id),
1218 }
1219 }),
1220 (
1221 prop_oneof![
1222 Just(COMPACTION_KIND.to_string()),
1223 Just(PROVIDER_HTTP_KIND.to_string()),
1224 "\\PC{0,8}",
1225 ],
1226 json()
1227 )
1228 .prop_map(|(kind, detail)| EntryContent::Meta { kind, detail }),
1229 ]
1230 }
1232 /// `content` with every JSON value in canonical key order.
1233 fn canonical_content(content: &EntryContent) -> EntryContent {
1234 match content {
1235 EntryContent::Message(message) => EntryContent::Message(canonical_message_of(message)),
1236 EntryContent::ToolCall {
1237 name,
1238 input,
1239 call_id,
1240 } => EntryContent::ToolCall {
1241 name: name.clone(),
1242 input: canonical_json(input),
1243 call_id: *call_id,
1244 },
1245 EntryContent::ToolResult { .. } => content.clone(),
1246 EntryContent::Meta { kind, detail } => EntryContent::Meta {
1247 kind: kind.clone(),
1248 detail: canonical_json(detail),
1249 },
1250 }
1251 }
1253 /// Offsets and lengths around the 4 GiB arena cap, plus anything.
1254 fn arena_size() -> impl Strategy<Value = usize> {
1255 let cap = u32::MAX as usize;
1256 prop_oneof![
1257 0..=cap,
1258 cap - 64..=cap + 64,
1259 (0..=64_usize).prop_map(move |below| cap - below),
1260 any::<usize>(),
1261 ]
1262 }
1264 proptest! {
1265 #[test]
1266 fn canonical_json_is_idempotent_and_keeps_the_value(value in json()) {
1267 let once = canonical_json(&value);
1268 prop_assert_eq!(json_bytes(&canonical_json(&once))?, json_bytes(&once)?);
1269 prop_assert!(is_canonical(&once));
1270 prop_assert_eq!(once, value);
1271 }
1273 #[test]
1274 fn canonical_json_ignores_key_order(value in json(), seed in any::<u64>()) {
1275 let shuffled = reordered(&value, seed);
1276 prop_assert_eq!(
1277 json_bytes(&canonical_json(&shuffled))?,
1278 json_bytes(&canonical_json(&value))?
1279 );
1280 }
1282 #[test]
1283 fn is_canonical_holds_exactly_when_canonicalizing_changes_nothing(value in json()) {
1284 prop_assert_eq!(
1285 is_canonical(&value),
1286 json_bytes(&canonical_json(&value))? == json_bytes(&value)?
1287 );
1288 }
1290 #[test]
1291 fn span_at_is_exact_below_the_cap_and_an_error_above(
1292 offset in arena_size(),
1293 len in arena_size(),
1294 ) {
1295 let fits = offset
1296 .checked_add(len)
1297 .is_some_and(|end| u32::try_from(end).is_ok());
1298 match Span::at(offset, len) {
1299 Ok(span) => {
1300 prop_assert!(fits);
1301 prop_assert_eq!(span.offset as usize, offset);
1302 prop_assert_eq!(span.len as usize, len);
1303 prop_assert_eq!(span.end(), offset + len);
1304 prop_assert_eq!(span.range().len(), len);
1305 }
1306 Err(error) => {
1307 prop_assert!(!fits);
1308 prop_assert_eq!(error.code(), "SESSION_ARENA_FULL");
1309 }
1310 }
1311 }
1313 #[test]
1314 fn content_ref_serializes_like_owned_content(content in content()) {
1315 prop_assert_eq!(cbor(&EntryContentRef::from(&content))?, cbor(&content)?);
1316 }
1318 #[test]
1319 fn owned_and_borrowed_encodings_are_canonical_and_decode_back(content in content()) {
1320 let owned = EntryFrame::new(None, &content)
1321 .map_err(|e| TestCaseError::fail(e.to_string()))?
1322 .content;
1323 let mut session = Session::new();
1324 let record = *session
1325 .append(EntryContentRef::from(&content))
1326 .map_err(|e| TestCaseError::fail(e.to_string()))?;
1327 prop_assert_eq!(session.bytes(&record), owned.as_slice());
1328 prop_assert_eq!(&owned, &cbor(&canonical_content(&content))?);
1329 prop_assert_eq!(
1330 EntryContent::decode(&owned).map_err(|e| TestCaseError::fail(e.to_string()))?,
1331 content
1332 );
1333 }
1334 }