From 52ad110e1aa8cc2ca73eef05606cda1f61fd9d9f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:33:41 +0100 Subject: [PATCH 01/10] thing-testkit: builders, bless door and pinned store move out of the contract tests (thing2 cut 2) The contract tests' builders (tests/common), golden_bytes/blessing and the pinned-clock store helpers become thing_testkit::{build, golden, store}; the contract tests link them as a dev-dependency. No golden byte changes. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 9 +++ crates/thing-contract/Cargo.toml | 1 + crates/thing-contract/tests/goldens.rs | 63 +++++++------------ crates/thing-contract/tests/nil_positions.rs | 13 ++-- crates/thing-contract/tests/result.rs | 4 +- crates/thing-testkit/Cargo.toml | 10 +++ .../mod.rs => thing-testkit/src/build.rs} | 27 +------- crates/thing-testkit/src/golden.rs | 32 ++++++++++ crates/thing-testkit/src/lib.rs | 6 ++ crates/thing-testkit/src/store.rs | 34 ++++++++++ 10 files changed, 125 insertions(+), 74 deletions(-) create mode 100644 crates/thing-testkit/Cargo.toml rename crates/{thing-contract/tests/common/mod.rs => thing-testkit/src/build.rs} (82%) create mode 100644 crates/thing-testkit/src/golden.rs create mode 100644 crates/thing-testkit/src/lib.rs create mode 100644 crates/thing-testkit/src/store.rs diff --git a/Cargo.lock b/Cargo.lock index 3898b9a..c4f3b61 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -378,6 +378,15 @@ dependencies = [ "rmp-serde", "serde", "serde_bytes", + "thing-testkit", +] + +[[package]] +name = "thing-testkit" +version = "0.1.0" +dependencies = [ + "cultcache-rs", + "thing-contract", ] [[package]] diff --git a/crates/thing-contract/Cargo.toml b/crates/thing-contract/Cargo.toml index f3ffd0f..b799adc 100644 --- a/crates/thing-contract/Cargo.toml +++ b/crates/thing-contract/Cargo.toml @@ -12,4 +12,5 @@ serde = { workspace = true } serde_bytes = "0.11" [dev-dependencies] +thing-testkit = { path = "../thing-testkit" } rmp-serde = { workspace = true } diff --git a/crates/thing-contract/tests/goldens.rs b/crates/thing-contract/tests/goldens.rs index e5c940d..d1891b7 100644 --- a/crates/thing-contract/tests/goldens.rs +++ b/crates/thing-contract/tests/goldens.rs @@ -2,23 +2,24 @@ //! byte. The TypeScript and C# packages and core are held to these files; none of them writes //! one. `THING_BLESS=1` rewrites them; any other run compares. -mod common; - use std::collections::BTreeSet; use std::fmt::Debug; use std::path::PathBuf; -use common::*; -use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore}; +use thing_testkit::{build::*, golden, store}; +use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry}; use thing_contract::*; -const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z"; +fn goldens_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens") +} + // A value that must never appear in a refusal. const CANARY: &str = "CANARY-7f3a91c2"; fn golden(name: &str, value: &T) -> String { let produced = rmp_serde::to_vec(value).unwrap(); - let committed = golden_bytes(&format!("{name}.bin"), &produced); + let committed = golden::check(&goldens_dir(), &format!("{name}.bin"), &produced); let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}")); assert_eq!(&decoded, value, "{name}: the golden does not decode to the constructed value"); assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes"); @@ -416,26 +417,17 @@ fn asset_catalog() -> AssetCatalog { /// A store with one record of each kind, written by cultcache-rs under a pinned clock. fn write_store(path: &std::path::Path) { - let _ = std::fs::remove_file(path); - let mut cache = CultCache::new(); - ThingContract.register_entries(&mut cache).unwrap(); - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); + let mut cache = store::create(path); let surface = full_surface(); let composition = full_composition(); let invocation = invocation(); let result = CommandResult::pending(&invocation, seq(1), "working"); let catalog = asset_catalog(); - put(&mut cache, &surface.record_key(), &surface); - put(&mut cache, &composition.record_key(), &composition); - put(&mut cache, &invocation.record_key(), &invocation); - put(&mut cache, &result.record_key(), &result); - put(&mut cache, &catalog.record_key(), &catalog); -} - -fn put(cache: &mut CultCache, key: &str, value: &T) { - let (mut envelope, _) = cache.prepare_entry(key, value).unwrap(); - envelope.stored_at = PINNED_CLOCK.into(); - cache.put_envelope::(envelope).unwrap(); + store::put_pinned(&mut cache, &surface.record_key(), &surface); + store::put_pinned(&mut cache, &composition.record_key(), &composition); + store::put_pinned(&mut cache, &invocation.record_key(), &invocation); + store::put_pinned(&mut cache, &result.record_key(), &result); + store::put_pinned(&mut cache, &catalog.record_key(), &catalog); } fn envelope(key: &str, payload: Vec) -> CultCacheEnvelope { @@ -443,19 +435,11 @@ fn envelope(key: &str, payload: Vec) -> CultCacheEnvelope key: key.into(), r#type: T::TYPE.into(), payload, - stored_at: PINNED_CLOCK.into(), + stored_at: store::PINNED_CLOCK.into(), schema_id: Some(T::TYPE.into()), } } -fn open_store(path: &std::path::Path) -> CultCache { - let mut cache = CultCache::new(); - ThingContract.register_entries(&mut cache).unwrap(); - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); - cache.pull_all_backing_stores().unwrap(); - cache -} - #[test] fn goldens_match() { let mut names = BTreeSet::new(); @@ -472,7 +456,7 @@ fn goldens_match() { // that no case names is an orphan. let refusals = refusal_payloads(); for (name, bytes) in &refusals { - golden_bytes(&format!("{name}.bin"), bytes); + golden::check(&goldens_dir(), &format!("{name}.bin"), bytes); names.insert((*name).to_string()); } let on_disk: BTreeSet = std::fs::read_dir(goldens_dir()) @@ -485,10 +469,10 @@ fn goldens_match() { // The store: one record of each kind, written under a pinned clock, byte for byte. let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc"); write_store(&scratch); - let committed = golden_bytes("surface.cc", &std::fs::read(&scratch).unwrap()); + let committed = golden::check(&goldens_dir(), "surface.cc", &std::fs::read(&scratch).unwrap()); let reopened = goldens_dir().join("surface.cc"); assert_eq!(std::fs::read(&reopened).unwrap(), committed); - let cache = open_store(&scratch); + let cache = store::open(&scratch); let surface = full_surface(); assert_eq!(cache.get::(&surface.record_key()).unwrap(), Some(surface)); let composition = full_composition(); @@ -572,7 +556,7 @@ fn refusal_payloads() -> Vec<(&'static str, Vec)> { #[test] fn refusal_cases() { let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect(); - let committed = |name: &str| golden_bytes(&format!("{name}.bin"), &payloads[name]); + let committed = |name: &str| golden::check(&goldens_dir(), &format!("{name}.bin"), &payloads[name]); // Stored under their key, each is refused naming the kind and the key, never a value. let cases: [(&str, &str, &str); 7] = [ @@ -679,15 +663,12 @@ fn deep_tree_body() { }; let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc"); - let _ = std::fs::remove_file(&path); { - let mut cache = CultCache::new(); - ThingContract.register_entries(&mut cache).unwrap(); - cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap(); - put(&mut cache, &deep.record_key(), &deep); - put(&mut cache, &wide.record_key(), &wide); + let mut cache = store::create(&path); + store::put_pinned(&mut cache, &deep.record_key(), &deep); + store::put_pinned(&mut cache, &wide.record_key(), &wide); } - let cache = open_store(&path); + let cache = store::open(&path); assert_eq!(cache.get::(&deep.record_key()).unwrap(), Some(deep)); assert_eq!(cache.get::(&wide.record_key()).unwrap(), Some(wide)); } diff --git a/crates/thing-contract/tests/nil_positions.rs b/crates/thing-contract/tests/nil_positions.rs index 27ee98d..f39c22f 100644 --- a/crates/thing-contract/tests/nil_positions.rs +++ b/crates/thing-contract/tests/nil_positions.rs @@ -4,14 +4,13 @@ //! TypeScript packages hold no list of their own and are held to every row. //! `THING_BLESS=1` rewrites `goldens/nil-positions.tsv`; any other run compares. -mod common; - use std::fmt::Debug; +use std::path::PathBuf; -use common::*; use serde::Serialize; use serde::de::DeserializeOwned; use thing_contract::*; +use thing_testkit::golden; /// One MessagePack value's byte span; `kids` is set for arrays only (maps are never walked). struct Span { @@ -79,7 +78,7 @@ fn elements(span: &Span, prefix: &str, out: &mut Vec<(String, usize, usize)>) { /// The rows of one golden: nil spliced over each element, decoded as `T`. An accepted variant /// must re-encode to the spliced bytes. fn rows(file: &str, out: &mut String) -> (usize, usize) { - let bytes = std::fs::read(goldens_dir().join(format!("{file}.bin"))).unwrap(); + let bytes = golden::read(&goldens_dir(), &format!("{file}.bin")); let mut found = Vec::new(); elements(&item(&bytes, 0), "", &mut found); let (mut accepted, mut refused) = (0, 0); @@ -125,5 +124,9 @@ fn nil_positions_match() { for (file, (accepted, refused)) in &totals { println!("NILTOTAL {file} accept={accepted} refuse={refused}"); } - golden_bytes("nil-positions.tsv", table.as_bytes()); + golden::check(&goldens_dir(), "nil-positions.tsv", table.as_bytes()); +} + +fn goldens_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens") } diff --git a/crates/thing-contract/tests/result.rs b/crates/thing-contract/tests/result.rs index bed0312..49fd667 100644 --- a/crates/thing-contract/tests/result.rs +++ b/crates/thing-contract/tests/result.rs @@ -1,6 +1,4 @@ -mod common; - -use common::*; +use thing_testkit::build::*; use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload}; use serde::Deserialize; use serde::de::IntoDeserializer; diff --git a/crates/thing-testkit/Cargo.toml b/crates/thing-testkit/Cargo.toml new file mode 100644 index 0000000..7886d45 --- /dev/null +++ b/crates/thing-testkit/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "thing-testkit" +version = "0.1.0" +edition = "2024" +license = "MIT" +publish = false + +[dependencies] +thing-contract = { path = "../thing-contract" } +cultcache-rs = { workspace = true } diff --git a/crates/thing-contract/tests/common/mod.rs b/crates/thing-testkit/src/build.rs similarity index 82% rename from crates/thing-contract/tests/common/mod.rs rename to crates/thing-testkit/src/build.rs index 5696035..f042d9f 100644 --- a/crates/thing-contract/tests/common/mod.rs +++ b/crates/thing-testkit/src/build.rs @@ -1,31 +1,8 @@ -//! Constructors for the values the goldens and the other tests share. Every value is built -//! through the crate's public types; no bytes are spelled here. - -#![allow(dead_code)] - -use std::path::PathBuf; +//! Constructors for the values the contract goldens, the fixtures and the other tests share. +//! Every value is built through the crate's public types; no bytes are spelled here. use thing_contract::*; -pub fn goldens_dir() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens") -} - -pub fn blessing() -> bool { - std::env::var("THING_BLESS").as_deref() == Ok("1") -} - -/// Bless the file or compare against it. Returns the committed bytes. -pub fn golden_bytes(file: &str, produced: &[u8]) -> Vec { - let path = goldens_dir().join(file); - if blessing() { - std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}")); - } - let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}")); - assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes"); - committed -} - pub fn seq(value: i32) -> Seq { Seq::new(value).unwrap() } diff --git a/crates/thing-testkit/src/golden.rs b/crates/thing-testkit/src/golden.rs new file mode 100644 index 0000000..728389a --- /dev/null +++ b/crates/thing-testkit/src/golden.rs @@ -0,0 +1,32 @@ +//! The one bless door. `THING_BLESS=1` writes; any other run compares and never writes. + +use std::path::Path; + +fn blessing() -> bool { + std::env::var("THING_BLESS").as_deref() == Ok("1") +} + +/// Bless the file or compare against it. Returns the committed bytes. A mismatch panics naming +/// the file and leaves it unchanged. +pub fn check(dir: &Path, file: &str, produced: &[u8]) -> Vec { + let path = dir.join(file); + if blessing() { + std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}")); + } + let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}")); + assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes"); + committed +} + +/// Bless or compare `stem.bin` and `stem.txt` together: the binary is the oracle, the text is +/// compared too so it cannot rot. Returns the committed binary. +pub fn check_with_text(dir: &Path, stem: &str, bytes: &[u8], text: &str) -> Vec { + let committed = check(dir, &format!("{stem}.bin"), bytes); + check(dir, &format!("{stem}.txt"), text.as_bytes()); + committed +} + +/// Read a committed file. Never writes: backends read core's goldens through this. +pub fn read(dir: &Path, file: &str) -> Vec { + std::fs::read(dir.join(file)).unwrap_or_else(|error| panic!("{file}: {error}")) +} diff --git a/crates/thing-testkit/src/lib.rs b/crates/thing-testkit/src/lib.rs new file mode 100644 index 0000000..bab5b04 --- /dev/null +++ b/crates/thing-testkit/src/lib.rs @@ -0,0 +1,6 @@ +//! The fakes, builders and the one bless door the Thing crates test with. A test crate +//! depends on this; no shipped crate does. + +pub mod build; +pub mod golden; +pub mod store; diff --git a/crates/thing-testkit/src/store.rs b/crates/thing-testkit/src/store.rs new file mode 100644 index 0000000..7889692 --- /dev/null +++ b/crates/thing-testkit/src/store.rs @@ -0,0 +1,34 @@ +//! CultCache single-file stores of contract documents, written under a pinned clock so the +//! bytes are reproducible. + +use std::path::Path; + +use cultcache_rs::{CultCache, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore}; +use thing_contract::ThingContract; + +pub const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z"; + +/// An empty cache with the contract registered over a fresh single-file store at `path`. +pub fn create(path: &Path) -> CultCache { + let _ = std::fs::remove_file(path); + let mut cache = CultCache::new(); + ThingContract.register_entries(&mut cache).unwrap(); + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); + cache +} + +/// Store `value` under `key` with `stored_at` pinned. +pub fn put_pinned(cache: &mut CultCache, key: &str, value: &T) { + let (mut envelope, _) = cache.prepare_entry(key, value).unwrap(); + envelope.stored_at = PINNED_CLOCK.into(); + cache.put_envelope::(envelope).unwrap(); +} + +/// A cache with the contract registered, pulled from the store at `path`. +pub fn open(path: &Path) -> CultCache { + let mut cache = CultCache::new(); + ThingContract.register_entries(&mut cache).unwrap(); + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); + cache.pull_all_backing_stores().unwrap(); + cache +} -- 2.47.3 From 0841c0dd8b8b5a73bd73076039ea7a23048055eb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:38:17 +0100 Subject: [PATCH 02/10] thing-core StatePort and thing-testkit MemState, fixture builders (thing2 cut 2) StatePort reads, lists, subscribes and drains queued changes and has no writer; a refusal is Lookup::Refused / Change::Refused, never absence. MemState is the CultCache-backed fake with a call log; the Fixture enum builds f01, f09 and f10 and loads their frozen stores. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 10 + crates/thing-core/Cargo.toml | 9 + crates/thing-core/src/lib.rs | 4 + crates/thing-core/src/port.rs | 102 ++++++++ crates/thing-testkit/Cargo.toml | 5 + crates/thing-testkit/src/fixture.rs | 323 ++++++++++++++++++++++++ crates/thing-testkit/src/lib.rs | 2 + crates/thing-testkit/src/mem_state.rs | 258 +++++++++++++++++++ crates/thing-testkit/src/store.rs | 13 +- crates/thing-testkit/tests/fixtures.rs | 161 ++++++++++++ crates/thing-testkit/tests/golden.rs | 59 +++++ crates/thing-testkit/tests/mem_state.rs | 245 ++++++++++++++++++ 12 files changed, 1187 insertions(+), 4 deletions(-) create mode 100644 crates/thing-core/Cargo.toml create mode 100644 crates/thing-core/src/lib.rs create mode 100644 crates/thing-core/src/port.rs create mode 100644 crates/thing-testkit/src/fixture.rs create mode 100644 crates/thing-testkit/src/mem_state.rs create mode 100644 crates/thing-testkit/tests/fixtures.rs create mode 100644 crates/thing-testkit/tests/golden.rs create mode 100644 crates/thing-testkit/tests/mem_state.rs diff --git a/Cargo.lock b/Cargo.lock index c4f3b61..c9fe90f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -381,12 +381,22 @@ dependencies = [ "thing-testkit", ] +[[package]] +name = "thing-core" +version = "0.1.0" +dependencies = [ + "thing-contract", +] + [[package]] name = "thing-testkit" version = "0.1.0" dependencies = [ + "anyhow", "cultcache-rs", + "rmp-serde", "thing-contract", + "thing-core", ] [[package]] diff --git a/crates/thing-core/Cargo.toml b/crates/thing-core/Cargo.toml new file mode 100644 index 0000000..d5fb718 --- /dev/null +++ b/crates/thing-core/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "thing-core" +version = "0.1.0" +edition = "2024" +license = "MIT" +publish = false + +[dependencies] +thing-contract = { path = "../thing-contract" } diff --git a/crates/thing-core/src/lib.rs b/crates/thing-core/src/lib.rs new file mode 100644 index 0000000..5b2775a --- /dev/null +++ b/crates/thing-core/src/lib.rs @@ -0,0 +1,4 @@ +//! Thing's core: a function of documents, state, input and time. It touches the world only +//! through ports; it reads no clock, spawns nothing and awaits nothing. + +pub mod port; diff --git a/crates/thing-core/src/port.rs b/crates/thing-core/src/port.rs new file mode 100644 index 0000000..40a77c2 --- /dev/null +++ b/crates/thing-core/src/port.rs @@ -0,0 +1,102 @@ +//! What core may ask of state. The port reads and queues changes; nothing in it writes, and +//! it never awaits: core drains queued changes inside its frame. + +use thing_contract::{AssetCatalog, CommandResult, CompositionDocument, ProviderId, RecordKey, SchemaId, SurfaceDocument}; + +/// One record: the provider that holds it, its schema and its key. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Address { + pub provider: ProviderId, + pub schema: SchemaId, + pub key: RecordKey, +} + +/// Every record of one provider and schema whose key starts with `key_prefix`. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Prefix { + pub provider: ProviderId, + pub schema: SchemaId, + pub key_prefix: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Interest { + Record(Address), + Prefix(Prefix), +} + +impl Prefix { + pub fn matches(&self, address: &Address) -> bool { + self.provider == address.provider + && self.schema == address.schema + && address.key.as_str().starts_with(&self.key_prefix) + } +} + +impl Interest { + /// Whether a change at `address` is of interest. + pub fn matches(&self, address: &Address) -> bool { + match self { + Interest::Record(record) => record == address, + Interest::Prefix(prefix) => prefix.matches(address), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct SubscriptionId(pub u64); + +/// A contract record the port carries, decoded. +#[derive(Clone, Debug, PartialEq)] +pub enum Record { + Surface(SurfaceDocument), + Composition(CompositionDocument), + Result(CommandResult), + Catalog(AssetCatalog), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Entry { + pub address: Address, + pub record: Record, +} + +/// A record the contract refused. `detail` is the decoder's message, which never carries a +/// value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Refusal { + pub address: Address, + pub kind: SchemaId, + pub detail: String, +} + +/// The answer for one address. A refusal is never absence. +#[derive(Clone, Debug, PartialEq)] +pub enum Lookup { + Present(Entry), + Absent, + Refused(Refusal), +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Change { + Upsert(Entry), + Delete(Address), + Refused(Refusal), +} + +/// Core's view of state. Object safe, and no method writes. +pub trait StatePort { + fn read(&self, address: &Address) -> Lookup; + + /// One lookup per record under the prefix, in key order. + fn list(&self, prefix: &Prefix) -> Vec; + + fn subscribe(&mut self, interest: Interest) -> SubscriptionId; + + fn unsubscribe(&mut self, id: SubscriptionId); + + /// Every change since the last drain that some live interest matches, in mutation order, + /// each once. + fn drain(&mut self) -> Vec; +} diff --git a/crates/thing-testkit/Cargo.toml b/crates/thing-testkit/Cargo.toml index 7886d45..523c1c2 100644 --- a/crates/thing-testkit/Cargo.toml +++ b/crates/thing-testkit/Cargo.toml @@ -8,3 +8,8 @@ publish = false [dependencies] thing-contract = { path = "../thing-contract" } cultcache-rs = { workspace = true } +thing-core = { path = "../thing-core" } +anyhow = { workspace = true } + +[dev-dependencies] +rmp-serde = { workspace = true } diff --git a/crates/thing-testkit/src/fixture.rs b/crates/thing-testkit/src/fixture.rs new file mode 100644 index 0000000..8cf2585 --- /dev/null +++ b/crates/thing-testkit/src/fixture.rs @@ -0,0 +1,323 @@ +//! The frozen fixture stores: typed contract documents built here, encoded through CultCache +//! under a pinned clock, committed under `fixtures/`, and loaded back through the same door +//! every consumer uses. `THING_BLESS=1` through `golden::check` is the only writer. + +use std::path::PathBuf; + +use thing_contract::*; + +use crate::build::*; +use crate::{golden, store}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Fixture { + F01SwarmDashboard, + F09CompositionStack, + F10Hostile, +} + +/// The documents of one fixture, each kind in record-key order. +#[derive(Clone, Debug, PartialEq)] +pub struct FixtureSet { + pub surfaces: Vec, + pub compositions: Vec, + pub catalogs: Vec, +} + +impl FixtureSet { + fn new( + mut surfaces: Vec, + mut compositions: Vec, + mut catalogs: Vec, + ) -> Self { + surfaces.sort_by_key(SurfaceDocument::record_key); + compositions.sort_by_key(CompositionDocument::record_key); + catalogs.sort_by_key(AssetCatalog::record_key); + Self { surfaces, compositions, catalogs } + } +} + +impl Fixture { + pub const ALL: [Fixture; 3] = [Fixture::F01SwarmDashboard, Fixture::F09CompositionStack, Fixture::F10Hostile]; + + pub fn file_name(self) -> &'static str { + match self { + Fixture::F01SwarmDashboard => "f01-swarm-dashboard.surface.cc", + Fixture::F09CompositionStack => "f09-composition-stack.surface.cc", + Fixture::F10Hostile => "f10-hostile.surface.cc", + } + } + + pub fn dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures") + } + + /// The documents the builders produce. + pub fn build(self) -> FixtureSet { + match self { + Fixture::F01SwarmDashboard => FixtureSet::new(vec![swarm_dashboard()], vec![], vec![]), + Fixture::F09CompositionStack => FixtureSet::new(vec![composition_stack()], vec![stack_card()], vec![]), + Fixture::F10Hostile => FixtureSet::new(hostile(), vec![hostile_dup()], vec![]), + } + } + + /// Encode the built documents into a store and bless or compare the committed file. + pub fn write(self) { + let scratch = std::env::temp_dir().join(format!("thing-testkit-{}-{}", std::process::id(), self.file_name())); + let mut cache = store::create(&scratch); + let set = self.build(); + for surface in &set.surfaces { + store::put_pinned(&mut cache, &surface.record_key(), surface); + } + for composition in &set.compositions { + store::put_pinned(&mut cache, &composition.record_key(), composition); + } + for catalog in &set.catalogs { + store::put_pinned(&mut cache, &catalog.record_key(), catalog); + } + let bytes = std::fs::read(&scratch).unwrap(); + let _ = std::fs::remove_file(&scratch); + golden::check(&Self::dir(), self.file_name(), &bytes); + } + + /// The committed store, decoded through the contract. + pub fn load(self) -> FixtureSet { + let cache = store::open(&Self::dir().join(self.file_name())); + FixtureSet::new(cache.get_all().unwrap(), cache.get_all().unwrap(), cache.get_all().unwrap()) + } +} + +const SWARM: &str = "provider.swarm"; +const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1"; + +fn swarm_ref(key: &str) -> StateSource { + StateSource::Record(StateRef { + provider: Some(ProviderId::new(SWARM)), + schema: SchemaId::new(SWARM_SCHEMA), + key: RecordKey::new(key), + }) +} + +fn swarm_dashboard() -> SurfaceDocument { + let load = Bind { + source: swarm_ref("summary"), + member: path(&["load"]), + format: Some(Format::Number(NumberFormat { precision: count(1), percent: true, unit: None })), + }; + let load_text = Node::Text(TextNode { + common: common("load"), + content: TextSource::Bound(load), + style_token: "title".into(), + wrap: false, + max_lines: Some(count(1)), + selectable: false, + }); + let minds = Node::Repeat(RepeatNode { + common: common("minds"), + collection: CollectionSource::Records(RecordsSource { + provider: Some(ProviderId::new(SWARM)), + schema: SchemaId::new(SWARM_SCHEMA), + key_prefix: "mind-".into(), + }), + key_member: path(&["id"]), + template: std::boxed::Box::new(Node::Text(TextNode { + common: common("mind-name"), + content: TextSource::Bound(item_bind(path(&["name"]))), + style_token: "body".into(), + wrap: false, + max_lines: Some(count(1)), + selectable: true, + })), + }); + let restart = Node::Button(ButtonNode { + common: common("restart"), + content: vec![text("restart-label", "Restart")], + on_activate: command("restart"), + enabled: lit_bool(true), + }); + let mut grid = style(); + grid.display = Display::Grid; + grid.grid_columns = vec![Dimension::Percent(Scalar { value: 50.0 }), Dimension::Percent(Scalar { value: 50.0 })]; + grid.grid_rows = vec![Dimension::Auto, Dimension::Auto]; + let root = Node::Box(BoxNode { + common: common("root"), + style: grid, + paint: plain_paint(), + role: Role::Group, + children: vec![load_text, minds, restart], + }); + SurfaceDocument { + provider_id: ProviderId::new(SWARM), + label: seg("dashboard"), + version: ver(1), + title: "Swarm".into(), + root, + commands: vec![CommandDecl { + id: CommandId::new("restart"), + payload_schema: SchemaId::new("gamecult.thing.test.restart.v1"), + captures: vec![], + confirm: Some("Restart the swarm?".into()), + }], + } +} + +const STACK: &str = "provider.stack"; + +/// A Use of the publisher's card with one argument of each arm and the given slot children. +fn card_use(id: &str, slot: Vec) -> Node { + let source = Bind { source: swarm_ref("summary"), member: path(&["load"]), format: None }; + let rows = CollectionSource::Records(RecordsSource { + provider: None, + schema: SchemaId::new(SWARM_SCHEMA), + key_prefix: "mind-".into(), + }); + let args = vec![ + Arg { name: "title".into(), value: ArgValue::Text(TextArg { value: "Card".into() }) }, + Arg { name: "count".into(), value: ArgValue::Number(NumberArg { value: 3.0 }) }, + Arg { name: "on".into(), value: ArgValue::Bool(BoolArg { value: true }) }, + Arg { name: "source".into(), value: ArgValue::Bind(source) }, + Arg { name: "rows".into(), value: ArgValue::Collection(CollectionArg { source: rows }) }, + Arg { name: "act".into(), value: ArgValue::Command(CommandArg { command: command("open") }) }, + Arg { name: "body".into(), value: ArgValue::Slot(SlotArg { nodes: slot }) }, + ]; + Node::Use(UseNode { + common: common(id), + composition: CompositionRef { publisher: STACK.into(), name: seg("card"), version: ver(1) }, + args, + }) +} + +fn composition_stack() -> SurfaceDocument { + // Two levels: the outer card's slot holds a second card. + let inner = card_use("inner-card", vec![text("inner-note", "nested")]); + let outer = card_use("outer-card", vec![inner]); + SurfaceDocument { + provider_id: ProviderId::new(STACK), + label: seg("stack"), + version: ver(1), + title: "Stack".into(), + root: boxed("root", vec![outer]), + commands: vec![CommandDecl { + id: CommandId::new("open"), + payload_schema: SchemaId::new("gamecult.thing.test.open.v1"), + captures: vec![], + confirm: None, + }], + } +} + +fn stack_card() -> CompositionDocument { + let title = Node::Text(TextNode { + common: common("card-title"), + content: TextSource::Param(param("title")), + style_token: "title".into(), + wrap: true, + max_lines: None, + selectable: false, + }); + let rows = Node::Repeat(RepeatNode { + common: common("card-rows"), + collection: CollectionSource::Param(param("rows")), + key_member: path(&["id"]), + template: std::boxed::Box::new(Node::Text(TextNode { + common: common("card-row"), + content: TextSource::Bound(item_bind(path(&["name"]))), + style_token: "body".into(), + wrap: false, + max_lines: None, + selectable: false, + })), + }); + let act = Node::Button(ButtonNode { + common: common("card-act"), + content: vec![text("card-act-label", "Open")], + on_activate: CommandRef::Param(param("act")), + enabled: BoolSource::Param(param("on")), + }); + CompositionDocument { + publisher: STACK.into(), + name: seg("card"), + version: ver(1), + params: [ + ("title", ParamKind::Text), + ("count", ParamKind::Number), + ("on", ParamKind::Bool), + ("source", ParamKind::Bind), + ("rows", ParamKind::Collection), + ("act", ParamKind::Command), + ("body", ParamKind::Slot), + ] + .into_iter() + .map(|(name, kind)| ParamDecl { name: name.into(), kind }) + .collect(), + body: boxed("card-root", vec![title, rows, act]), + } +} + +const HOSTILE: &str = "provider.hostile"; + +fn hostile_use(id: &str, name: &str) -> Node { + Node::Use(UseNode { + common: common(id), + composition: CompositionRef { publisher: HOSTILE.into(), name: seg(name), version: ver(1) }, + args: vec![], + }) +} + +fn hostile_surface(label: &str, children: Vec) -> SurfaceDocument { + SurfaceDocument { + provider_id: ProviderId::new(HOSTILE), + label: seg(label), + version: ver(1), + title: label.into(), + root: boxed("root", children), + commands: vec![], + } +} + +/// Four surfaces the resolver must refuse or flag, one hostile shape each. A surface whose +/// bytes the contract itself refuses (an unknown union arm) cannot live in a store, so that +/// case is the committed `node-unknown-arm.bin` golden, fed to a fake by the test. +fn hostile() -> Vec { + let undeclared = Node::Button(ButtonNode { + common: common("go"), + content: vec![text("go-label", "Go")], + on_activate: command("missing"), + enabled: lit_bool(true), + }); + let mismatched = Node::Text(TextNode { + common: common("mismatch"), + content: TextSource::Bound(Bind { + source: StateSource::Record(StateRef { + provider: Some(ProviderId::new(HOSTILE)), + schema: SchemaId::new("gamecult.thing.test.nowhere.v1"), + key: RecordKey::new("row-1"), + }), + member: path(&["name"]), + format: None, + }), + style_token: "body".into(), + wrap: false, + max_lines: None, + selectable: false, + }); + vec![ + hostile_surface("undeclared-command", vec![undeclared]), + // The composition `dup` emits `shared-id`, which the surface also uses. + hostile_surface("duplicate-id", vec![hostile_use("dup-use", "dup"), text("shared-id", "also here")]), + // No composition `ghost` exists anywhere. + hostile_surface("unresolved-use", vec![hostile_use("ghost-use", "ghost")]), + hostile_surface("schema-mismatch", vec![mismatched]), + ] +} + +/// The one composition a hostile surface needs: the duplicate-id case cannot expand without it. +fn hostile_dup() -> CompositionDocument { + CompositionDocument { + publisher: HOSTILE.into(), + name: seg("dup"), + version: ver(1), + params: vec![], + body: boxed("dup-root", vec![text("shared-id", "from the composition")]), + } +} diff --git a/crates/thing-testkit/src/lib.rs b/crates/thing-testkit/src/lib.rs index bab5b04..1107328 100644 --- a/crates/thing-testkit/src/lib.rs +++ b/crates/thing-testkit/src/lib.rs @@ -2,5 +2,7 @@ //! depends on this; no shipped crate does. pub mod build; +pub mod fixture; pub mod golden; +pub mod mem_state; pub mod store; diff --git a/crates/thing-testkit/src/mem_state.rs b/crates/thing-testkit/src/mem_state.rs new file mode 100644 index 0000000..96ec2cb --- /dev/null +++ b/crates/thing-testkit/src/mem_state.rs @@ -0,0 +1,258 @@ +//! `MemState`: an in-memory `StatePort`. Each provider's records live in a CultCache with the +//! contract registered, so a typed value and a raw payload meet one decode door. A payload the +//! contract refuses is never stored: the address becomes refused, and stays refused until a +//! record or a delete replaces it. + +use std::cell::RefCell; +use std::collections::HashMap; + +use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry}; +use thing_contract::*; +use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, SubscriptionId}; + +use crate::store; + +/// A contract kind the port carries. +pub trait StateKind: DatabaseEntry { + fn record_key(&self) -> String; + fn into_record(self) -> Record; +} + +macro_rules! state_kinds { + ($($kind:ident => $arm:ident),* $(,)?) => { + $(impl StateKind for $kind { + fn record_key(&self) -> String { + $kind::record_key(self) + } + fn into_record(self) -> Record { + Record::$arm(self) + } + })* + }; +} + +state_kinds!( + SurfaceDocument => Surface, + CompositionDocument => Composition, + CommandResult => Result, + AssetCatalog => Catalog, +); + +/// Run `$body` with `$t` bound to the contract kind whose schema is `$schema`, or `$none` for +/// a schema the port does not carry. +macro_rules! by_schema { + ($schema:expr, $t:ident => $body:expr, else $none:expr) => { + match $schema { + SurfaceDocument::SCHEMA_NAME => { + type $t = SurfaceDocument; + $body + } + CompositionDocument::SCHEMA_NAME => { + type $t = CompositionDocument; + $body + } + CommandResult::SCHEMA_NAME => { + type $t = CommandResult; + $body + } + AssetCatalog::SCHEMA_NAME => { + type $t = AssetCatalog; + $body + } + _ => $none, + } + }; +} + +/// One call the port received. +#[derive(Clone, Debug, PartialEq)] +pub enum Call { + Read(Address), + List(Prefix), + Subscribe(Interest), + Unsubscribe(SubscriptionId), + Drain, +} + +pub struct MemState { + providers: HashMap, + refused: HashMap, + interests: Vec<(SubscriptionId, Interest)>, + next_subscription: u64, + queue: Vec, + calls: RefCell>, +} + +impl Default for MemState { + fn default() -> Self { + Self::new() + } +} + +impl MemState { + pub fn new() -> Self { + Self { + providers: HashMap::new(), + refused: HashMap::new(), + interests: Vec::new(), + next_subscription: 0, + queue: Vec::new(), + calls: RefCell::new(Vec::new()), + } + } + + /// A state holding every document of a fixture, each under the provider that publishes it. + pub fn from_fixture(fixture: crate::fixture::Fixture) -> Self { + let set = fixture.load(); + let mut state = Self::new(); + for surface in &set.surfaces { + state.put(&surface.provider_id, surface); + } + for composition in &set.compositions { + state.put(&ProviderId::new(composition.publisher.clone()), composition); + } + for catalog in &set.catalogs { + state.put(&catalog.provider_id, catalog); + } + state + } + + /// Store a record under its record key at `provider`. + pub fn put(&mut self, provider: &ProviderId, value: &T) { + let address = Address { + provider: provider.clone(), + schema: SchemaId::new(T::SCHEMA_NAME), + key: RecordKey::new(value.record_key()), + }; + let outcome = self.cache(provider).put(address.key.as_str(), value); + self.admit::(address, outcome); + } + + /// Store a payload under `address`; the address's schema names the contract kind. A payload + /// the contract refuses makes the address refused. + pub fn put_raw(&mut self, address: Address, payload: Vec) { + by_schema!(address.schema.as_str(), T => { + let envelope = CultCacheEnvelope { + key: address.key.as_str().into(), + r#type: T::TYPE.into(), + payload, + stored_at: store::PINNED_CLOCK.into(), + schema_id: Some(T::SCHEMA_NAME.into()), + }; + let outcome = self.cache(&address.provider).put_envelope::(envelope); + self.admit::(address, outcome); + }, else panic!("no contract record kind has schema {}", address.schema.as_str())) + } + + /// Remove the record or the refusal at `address`; removing nothing is not a change. + pub fn delete(&mut self, address: &Address) { + let refused = self.refused.remove(address).is_some(); + let stored = by_schema!(address.schema.as_str(), T => { + match self.providers.get_mut(address.provider.as_str()) { + Some(cache) => cache.delete::(address.key.as_str()).unwrap(), + None => false, + } + }, else false); + if refused || stored { + self.queue(Change::Delete(address.clone())); + } + } + + /// Every call the port received, in order. + pub fn calls(&self) -> Vec { + self.calls.borrow().clone() + } + + fn cache(&mut self, provider: &ProviderId) -> &mut CultCache { + self.providers.entry(provider.as_str().to_string()).or_insert_with(store::memory) + } + + fn admit(&mut self, address: Address, outcome: anyhow::Result) { + match outcome { + Ok(value) => { + self.refused.remove(&address); + self.queue(Change::Upsert(Entry { address, record: value.into_record() })); + } + Err(error) => { + // The address is now refused: an older valid record under it no longer stands. + self.cache(&address.provider).delete::(address.key.as_str()).unwrap(); + let refusal = + Refusal { address: address.clone(), kind: address.schema.clone(), detail: format!("{error:#}") }; + self.refused.insert(address, refusal.clone()); + self.queue(Change::Refused(refusal)); + } + } + } + + fn queue(&mut self, change: Change) { + let address = match &change { + Change::Upsert(entry) => &entry.address, + Change::Delete(address) => address, + Change::Refused(refusal) => &refusal.address, + }; + if self.interests.iter().any(|(_, interest)| interest.matches(address)) { + self.queue.push(change); + } + } +} + +impl StatePort for MemState { + fn read(&self, address: &Address) -> Lookup { + self.calls.borrow_mut().push(Call::Read(address.clone())); + if let Some(refusal) = self.refused.get(address) { + return Lookup::Refused(refusal.clone()); + } + by_schema!(address.schema.as_str(), T => { + let stored = self.providers.get(address.provider.as_str()); + match stored.and_then(|cache| cache.get::(address.key.as_str()).expect("stored records decode")) { + Some(value) => Lookup::Present(Entry { address: address.clone(), record: value.into_record() }), + None => Lookup::Absent, + } + }, else Lookup::Absent) + } + + fn list(&self, prefix: &Prefix) -> Vec { + self.calls.borrow_mut().push(Call::List(prefix.clone())); + let at = |key: &str| Address { + provider: prefix.provider.clone(), + schema: prefix.schema.clone(), + key: RecordKey::new(key), + }; + let mut found: Vec<(String, Lookup)> = self + .refused + .values() + .filter(|refusal| prefix.matches(&refusal.address)) + .map(|refusal| (refusal.address.key.as_str().to_string(), Lookup::Refused(refusal.clone()))) + .collect(); + by_schema!(prefix.schema.as_str(), T => { + if let Some(cache) = self.providers.get(prefix.provider.as_str()) { + for (key, value) in cache.get_all_with_keys::().expect("stored records decode") { + if key.starts_with(&prefix.key_prefix) { + let entry = Entry { address: at(&key), record: value.into_record() }; + found.push((key, Lookup::Present(entry))); + } + } + } + }, else ()); + found.sort_by(|a, b| a.0.cmp(&b.0)); + found.into_iter().map(|(_, lookup)| lookup).collect() + } + + fn subscribe(&mut self, interest: Interest) -> SubscriptionId { + self.calls.borrow_mut().push(Call::Subscribe(interest.clone())); + let id = SubscriptionId(self.next_subscription); + self.next_subscription += 1; + self.interests.push((id, interest)); + id + } + + fn unsubscribe(&mut self, id: SubscriptionId) { + self.calls.borrow_mut().push(Call::Unsubscribe(id)); + self.interests.retain(|(live, _)| *live != id); + } + + fn drain(&mut self) -> Vec { + self.calls.borrow_mut().push(Call::Drain); + std::mem::take(&mut self.queue) + } +} diff --git a/crates/thing-testkit/src/store.rs b/crates/thing-testkit/src/store.rs index 7889692..4b8610a 100644 --- a/crates/thing-testkit/src/store.rs +++ b/crates/thing-testkit/src/store.rs @@ -8,11 +8,17 @@ use thing_contract::ThingContract; pub const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z"; +/// A cache with the contract registered and no backing store. +pub fn memory() -> CultCache { + let mut cache = CultCache::new(); + ThingContract.register_entries(&mut cache).unwrap(); + cache +} + /// An empty cache with the contract registered over a fresh single-file store at `path`. pub fn create(path: &Path) -> CultCache { let _ = std::fs::remove_file(path); - let mut cache = CultCache::new(); - ThingContract.register_entries(&mut cache).unwrap(); + let mut cache = memory(); cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); cache } @@ -26,8 +32,7 @@ pub fn put_pinned(cache: &mut CultCache, key: &str, value: &T) /// A cache with the contract registered, pulled from the store at `path`. pub fn open(path: &Path) -> CultCache { - let mut cache = CultCache::new(); - ThingContract.register_entries(&mut cache).unwrap(); + let mut cache = memory(); cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); cache.pull_all_backing_stores().unwrap(); cache diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs new file mode 100644 index 0000000..cd60559 --- /dev/null +++ b/crates/thing-testkit/tests/fixtures.rs @@ -0,0 +1,161 @@ +//! The committed fixture stores: they open through the contract, the builders reproduce them +//! byte for byte, and each holds the shapes its row of the fixture table names. +//! `THING_BLESS=1` on this test rewrites them; any other run compares. + +use thing_contract::*; +use thing_testkit::fixture::{Fixture, FixtureSet}; +use thing_testkit::mem_state::MemState; +use thing_testkit::store; +use thing_core::port::{Address, Lookup, StatePort}; + +/// Decoding runs on a 16 MiB thread until the workspace pin of cultcache-rs carries +/// decode-stack-safety. +fn on_big_stack(work: impl FnOnce() -> T + Send + 'static) -> T { + std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(work).unwrap().join().unwrap() +} + +fn load(fixture: Fixture) -> FixtureSet { + on_big_stack(move || fixture.load()) +} + +#[test] +fn every_fixture_round_trips_through_the_contract() { + on_big_stack(|| { + for fixture in Fixture::ALL { + // The builders reproduce the committed file byte for byte (or bless it). + fixture.write(); + let built = fixture.build(); + let loaded = fixture.load(); + assert_eq!(loaded, built, "{}: the store decodes to the built documents", fixture.file_name()); + + // Each record re-encodes to its stored payload. + let cache = store::open(&Fixture::dir().join(fixture.file_name())); + for surface in &loaded.surfaces { + let stored = cache.get_envelope::(&surface.record_key()).unwrap().unwrap(); + assert_eq!(rmp_serde::to_vec(surface).unwrap(), stored.payload); + } + for composition in &loaded.compositions { + let stored = cache.get_envelope::(&composition.record_key()).unwrap().unwrap(); + assert_eq!(rmp_serde::to_vec(composition).unwrap(), stored.payload); + } + assert_eq!( + cache.snapshot_envelopes().len(), + loaded.surfaces.len() + loaded.compositions.len() + loaded.catalogs.len(), + "{}: the store holds the documents and nothing else", + fixture.file_name() + ); + } + }); +} + +fn commands_declared(surface: &SurfaceDocument) -> Vec<&str> { + surface.commands.iter().map(|decl| decl.id.as_str()).collect() +} + +fn box_children(node: &Node) -> &[Node] { + match node { + Node::Box(node) => &node.children, + other => panic!("not a Box: {other:?}"), + } +} + +#[test] +fn f01_is_the_swarm_dashboard() { + let set = load(Fixture::F01SwarmDashboard); + assert_eq!(set.surfaces.len(), 1); + let surface = &set.surfaces[0]; + let Node::Box(root) = &surface.root else { panic!("root is not a Box") }; + assert_eq!(root.style.display, Display::Grid); + let [load, minds, restart] = &root.children[..] else { panic!("three children expected") }; + + let Node::Text(load) = load else { panic!("not a Text") }; + let TextSource::Bound(bind) = &load.content else { panic!("Text is not bound") }; + assert!(matches!(bind.format, Some(Format::Number(_)))); + + let Node::Repeat(minds) = minds else { panic!("not a Repeat") }; + assert!(matches!(minds.collection, CollectionSource::Records(_))); + + let Node::Button(restart) = restart else { panic!("not a Button") }; + let CommandRef::Id(command) = &restart.on_activate else { panic!("not a command id") }; + assert_eq!(commands_declared(surface), [command.id.as_str()]); +} + +#[test] +fn f09_stacks_compositions_with_every_argument_arm() { + let set = load(Fixture::F09CompositionStack); + assert_eq!((set.surfaces.len(), set.compositions.len()), (1, 1)); + let surface = &set.surfaces[0]; + let [outer] = box_children(&surface.root) else { panic!("one Use expected") }; + let Node::Use(outer) = outer else { panic!("not a Use") }; + assert_eq!(outer.composition.publisher, set.compositions[0].publisher); + assert_eq!(outer.composition.name, set.compositions[0].name); + assert_eq!(outer.composition.version, set.compositions[0].version); + + let arms: Vec<&str> = outer + .args + .iter() + .map(|arg| match arg.value { + ArgValue::Text(_) => "text", + ArgValue::Number(_) => "number", + ArgValue::Bool(_) => "bool", + ArgValue::Bind(_) => "bind", + ArgValue::Collection(_) => "collection", + ArgValue::Command(_) => "command", + ArgValue::Slot(_) => "slot", + }) + .collect(); + assert_eq!(arms, ["text", "number", "bool", "bind", "collection", "command", "slot"]); + + // The slot holds a second Use of the same composition: two levels. + let ArgValue::Slot(slot) = &outer.args[6].value else { unreachable!() }; + assert!(slot.nodes.iter().any(|node| matches!(node, Node::Use(inner) if inner.composition == outer.composition))); +} + +#[test] +fn f10_holds_exactly_the_four_hostile_surfaces() { + let set = load(Fixture::F10Hostile); + let labels: Vec<&str> = set.surfaces.iter().map(|surface| surface.label.as_str()).collect(); + assert_eq!(labels, ["duplicate-id", "schema-mismatch", "undeclared-command", "unresolved-use"]); + + let by = |label: &str| set.surfaces.iter().find(|surface| surface.label.as_str() == label).unwrap(); + + let undeclared = by("undeclared-command"); + let Node::Button(button) = &box_children(&undeclared.root)[0] else { panic!("not a Button") }; + let CommandRef::Id(command) = &button.on_activate else { panic!("not a command id") }; + assert!(!commands_declared(undeclared).contains(&command.id.as_str())); + + // The surface uses `shared-id` and so does the composition its Use expands to. + let dup = by("duplicate-id"); + let children = box_children(&dup.root); + assert!(children.iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "shared-id"))); + let Node::Use(used) = &children[0] else { panic!("not a Use") }; + let composition = set.compositions.iter().find(|composition| composition.name == used.composition.name).unwrap(); + assert!(box_children(&composition.body).iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "shared-id"))); + + // The unresolved Use names a composition no document holds. + let Node::Use(ghost) = &box_children(&by("unresolved-use").root)[0] else { panic!("not a Use") }; + assert!(set.compositions.iter().all(|composition| composition.name != ghost.composition.name)); + + // The Bind names a schema none of the fixtures use for state. + let Node::Text(text) = &box_children(&by("schema-mismatch").root)[0] else { panic!("not a Text") }; + let TextSource::Bound(Bind { source: StateSource::Record(state), .. }) = &text.content else { + panic!("Text is not bound to a record") + }; + let f01 = load(Fixture::F01SwarmDashboard); + let Node::Box(root) = &f01.surfaces[0].root else { unreachable!() }; + let Node::Text(f01_text) = &root.children[0] else { unreachable!() }; + let TextSource::Bound(Bind { source: StateSource::Record(f01_state), .. }) = &f01_text.content else { unreachable!() }; + assert_ne!(state.schema, f01_state.schema); +} + +#[test] +fn a_state_holds_every_fixture_document_under_its_publisher() { + let state = on_big_stack(|| MemState::from_fixture(Fixture::F09CompositionStack)); + let set = load(Fixture::F09CompositionStack); + let at = Address { + provider: ProviderId::new(set.compositions[0].publisher.clone()), + schema: SchemaId::new("gamecult.thing.composition.v1"), + key: RecordKey::new(set.compositions[0].record_key()), + }; + assert!(matches!(state.read(&at), Lookup::Present(_))); +} diff --git a/crates/thing-testkit/tests/golden.rs b/crates/thing-testkit/tests/golden.rs new file mode 100644 index 0000000..4930d57 --- /dev/null +++ b/crates/thing-testkit/tests/golden.rs @@ -0,0 +1,59 @@ +//! The bless door compares and never writes unless `THING_BLESS=1`. These tests assume it is +//! unset; the bless job runs only the fixtures test. + +use std::panic::catch_unwind; +use std::path::PathBuf; + +use thing_testkit::golden; + +fn scratch(name: &str) -> PathBuf { + let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("golden-{name}")); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn a_mismatch_panics_naming_the_file_and_leaves_it_unchanged() { + let dir = scratch("mismatch"); + std::fs::write(dir.join("a.bin"), b"committed").unwrap(); + + assert_eq!(golden::check(&dir, "a.bin", b"committed"), b"committed"); + + let panic = catch_unwind(|| golden::check(&dir, "a.bin", b"different")).unwrap_err(); + let message = panic.downcast_ref::().cloned().unwrap_or_default(); + assert!(message.contains("a.bin"), "the panic names the file: {message}"); + assert_eq!(std::fs::read(dir.join("a.bin")).unwrap(), b"committed"); +} + +#[test] +fn a_missing_file_is_a_failure_not_a_write() { + let dir = scratch("missing"); + assert!(catch_unwind(|| golden::check(&dir, "absent.bin", b"x")).is_err()); + assert!(catch_unwind(|| golden::read(&dir, "absent.bin")).is_err()); + assert!(!dir.join("absent.bin").exists()); +} + +#[test] +fn the_text_beside_the_binary_is_compared_too() { + let dir = scratch("text"); + std::fs::write(dir.join("s.bin"), b"bytes").unwrap(); + std::fs::write(dir.join("s.txt"), "text").unwrap(); + + assert_eq!(golden::check_with_text(&dir, "s", b"bytes", "text"), b"bytes"); + + let panic = catch_unwind(|| golden::check_with_text(&dir, "s", b"bytes", "other")).unwrap_err(); + let message = panic.downcast_ref::().cloned().unwrap_or_default(); + assert!(message.contains("s.txt"), "the panic names the text file: {message}"); + assert_eq!(std::fs::read(dir.join("s.txt")).unwrap(), b"text"); + + assert!(catch_unwind(|| golden::check_with_text(&dir, "s", b"changed", "text")).is_err()); + assert_eq!(std::fs::read(dir.join("s.bin")).unwrap(), b"bytes"); +} + +#[test] +fn read_returns_the_committed_bytes() { + let dir = scratch("read"); + std::fs::write(dir.join("r.bin"), b"abc").unwrap(); + assert_eq!(golden::read(&dir, "r.bin"), b"abc"); +} diff --git a/crates/thing-testkit/tests/mem_state.rs b/crates/thing-testkit/tests/mem_state.rs new file mode 100644 index 0000000..512160e --- /dev/null +++ b/crates/thing-testkit/tests/mem_state.rs @@ -0,0 +1,245 @@ +//! MemState as core sees it: through `StatePort`, with its own put and delete as the only +//! writers. + +use std::path::PathBuf; + +use thing_contract::*; +use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, StatePort, SubscriptionId}; +use thing_testkit::build::*; +use thing_testkit::golden; +use thing_testkit::mem_state::{Call, MemState}; + +const SURFACE: &str = "gamecult.thing.surface.v1"; +const COMPOSITION: &str = "gamecult.thing.composition.v1"; +const RESULT: &str = "gamecult.thing.command_result.v1"; +const CATALOG: &str = "gamecult.thing.asset_catalog.v1"; +// A value that must never appear in a refusal; node-unknown-arm.bin carries it. +const CANARY: &str = "CANARY-7f3a91c2"; + +fn provider(name: &str) -> ProviderId { + ProviderId::new(name) +} + +fn address(provider_name: &str, schema: &str, key: &str) -> Address { + Address { provider: provider(provider_name), schema: SchemaId::new(schema), key: RecordKey::new(key) } +} + +fn prefix(provider_name: &str, schema: &str, key_prefix: &str) -> Prefix { + Prefix { provider: provider(provider_name), schema: SchemaId::new(schema), key_prefix: key_prefix.into() } +} + +fn surface(provider_name: &str, label: &str) -> SurfaceDocument { + SurfaceDocument { + provider_id: provider(provider_name), + label: seg(label), + version: ver(1), + title: label.into(), + root: boxed("root", vec![]), + commands: vec![], + } +} + +fn composition(publisher: &str, name: &str) -> CompositionDocument { + CompositionDocument { + publisher: publisher.into(), + name: seg(name), + version: ver(1), + params: vec![], + body: boxed("body", vec![]), + } +} + +fn catalog(provider_name: &str, id: &str) -> AssetCatalog { + AssetCatalog { provider_id: provider(provider_name), catalog_id: seg(id), version: ver(1), assets: vec![] } +} + +fn surface_at(provider_name: &str, value: &SurfaceDocument) -> Address { + address(provider_name, SURFACE, &value.record_key()) +} + +fn unknown_arm() -> Vec { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../thing-contract/tests/goldens"); + golden::read(&dir, "node-unknown-arm.bin") +} + +#[test] +fn port_is_object_safe() { + let one = surface("provider.a", "one"); + let mut state = MemState::new(); + state.put(&provider("provider.a"), &one); + let port: &mut dyn StatePort = &mut state; + let id = port.subscribe(Interest::Record(surface_at("provider.a", &one))); + assert!(matches!(port.read(&surface_at("provider.a", &one)), Lookup::Present(_))); + assert_eq!(port.list(&prefix("provider.a", SURFACE, "thing:")).len(), 1); + port.unsubscribe(id); + assert!(port.drain().is_empty()); + let boxed: Box = Box::new(MemState::new()); + assert_eq!(boxed.read(&address("provider.a", SURFACE, "k")), Lookup::Absent); +} + +#[test] +fn a_refusal_is_not_absence() { + let main = surface("provider.a", "main"); + let at = surface_at("provider.a", &main); + assert_eq!(at.key.as_str(), "thing:surface:provider.a.main"); + let mut state = MemState::new(); + state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:"))); + + state.put_raw(at.clone(), unknown_arm()); + + let drained = state.drain(); + assert_eq!(drained.len(), 1, "one change: {drained:?}"); + let Change::Refused(refusal) = &drained[0] else { panic!("not a refusal: {drained:?}") }; + assert_eq!(refusal.address, at); + assert_eq!(refusal.kind, SchemaId::new(SURFACE)); + assert!(refusal.detail.contains(at.key.as_str()), "the detail names the key: {}", refusal.detail); + assert!(!refusal.detail.contains(CANARY), "the detail echoed a value: {}", refusal.detail); + assert_eq!(state.read(&at), Lookup::Refused(refusal.clone())); + assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:")), vec![Lookup::Refused(refusal.clone())]); + + // A valid record replaces the refusal; a refusal over a valid record leaves the address + // refused, not the older record. + state.put(&provider("provider.a"), &main); + assert!(matches!(state.read(&at), Lookup::Present(_))); + state.put_raw(at.clone(), unknown_arm()); + assert!(matches!(state.read(&at), Lookup::Refused(_))); + assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:")).len(), 1); + state.drain(); + + // Deleting a refusal is a change; deleting nothing is not. + state.delete(&at); + assert_eq!(state.read(&at), Lookup::Absent); + assert_eq!(state.drain(), vec![Change::Delete(at.clone())]); + state.delete(&at); + assert!(state.drain().is_empty()); +} + +#[test] +fn changes_drain_in_mutation_order_for_live_interests() { + let provider_a = provider("provider.a"); + let one = surface("provider.a", "one"); + let two = surface("provider.a", "two"); + let panel = composition("provider.a", "panel"); + let other = composition("provider.a", "other"); + let icons = catalog("provider.a", "icons"); + let one_at = surface_at("provider.a", &one); + let panel_at = address("provider.a", COMPOSITION, &panel.record_key()); + + let mut state = MemState::new(); + let ids: Vec = vec![ + state.subscribe(Interest::Record(one_at.clone())), + state.subscribe(Interest::Record(panel_at.clone())), + state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:"))), + ]; + + state.put(&provider_a, &one); // matches two interests and drains once + state.put(&provider_a, &panel); + state.put(&provider_a, &icons); // another schema under the same provider + state.put(&provider_a, &other); // a composition nobody asked for + // The same key and schema under another provider. + state.put_raw(address("provider.b", SURFACE, &two.record_key()), rmp_serde::to_vec(&two).unwrap()); + state.put(&provider_a, &two); + state.delete(&one_at); + + let entry = |address: Address, record: Record| Change::Upsert(Entry { address, record }); + assert_eq!( + state.drain(), + vec![ + entry(one_at.clone(), Record::Surface(one.clone())), + entry(panel_at, Record::Composition(panel)), + entry(surface_at("provider.a", &two), Record::Surface(two.clone())), + Change::Delete(one_at), + ] + ); + assert!(state.drain().is_empty(), "each change drains once"); + + for id in ids { + state.unsubscribe(id); + } + state.put(&provider_a, &one); + assert!(state.drain().is_empty()); +} + +#[test] +fn without_a_live_interest_nothing_queues() { + let mut state = MemState::new(); + state.put_raw(address("provider.a", SURFACE, "thing:surface:provider.a.main"), unknown_arm()); + state.put(&provider("provider.a"), &surface("provider.a", "one")); + assert!(state.drain().is_empty()); +} + +#[test] +fn each_kind_reads_back_as_its_own_arm() { + let provider_a = provider("provider.a"); + let mut state = MemState::new(); + let first = surface("provider.a", "b"); + let invocation = invocation(); + let result = CommandResult::pending(&invocation, seq(1), "working"); + let panel = composition("provider.a", "panel"); + let icons = catalog("provider.a", "icons"); + state.put(&provider_a, &first); + state.put(&provider_a, &panel); + state.put(&provider_a, &result); + state.put(&provider_a, &icons); + + let present = |at: Address, record: Record| Lookup::Present(Entry { address: at, record }); + let first_at = surface_at("provider.a", &first); + assert_eq!(state.read(&first_at), present(first_at.clone(), Record::Surface(first.clone()))); + let panel_at = address("provider.a", COMPOSITION, &panel.record_key()); + assert_eq!(state.read(&panel_at), present(panel_at.clone(), Record::Composition(panel))); + let result_at = address("provider.a", RESULT, &result.record_key()); + assert_eq!(state.read(&result_at), present(result_at.clone(), Record::Result(result))); + let icons_at = address("provider.a", CATALOG, &icons.record_key()); + assert_eq!(state.read(&icons_at), present(icons_at.clone(), Record::Catalog(icons))); + + // A newer record replaces the older; an absent key, another provider and another schema read Absent. + let mut newer = first.clone(); + newer.title = "newer".into(); + state.put(&provider_a, &newer); + assert_eq!(state.read(&first_at), present(first_at.clone(), Record::Surface(newer))); + assert_eq!(state.read(&address("provider.a", SURFACE, "missing")), Lookup::Absent); + assert_eq!(state.read(&address("provider.b", SURFACE, first_at.key.as_str())), Lookup::Absent); + assert_eq!(state.read(&address("provider.a", COMPOSITION, first_at.key.as_str())), Lookup::Absent); + assert_eq!(state.read(&address("provider.a", "gamecult.thing.nowhere.v1", "k")), Lookup::Absent); + + // A list holds the prefix's records in key order and no others. + let a = surface("provider.a", "a"); + let c = surface("provider.a", "c"); + state.put(&provider_a, &c); + state.put(&provider_a, &a); + let keys: Vec = state + .list(&prefix("provider.a", SURFACE, "thing:surface:provider.a.")) + .into_iter() + .map(|lookup| match lookup { + Lookup::Present(entry) => entry.address.key.as_str().to_string(), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(keys, ["thing:surface:provider.a.a", "thing:surface:provider.a.b", "thing:surface:provider.a.c"]); + assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:surface:provider.a.b")).len(), 1); + assert!(state.list(&prefix("provider.b", SURFACE, "thing:")).is_empty()); +} + +#[test] +fn every_call_is_logged_in_order() { + let at = address("provider.a", SURFACE, "k"); + let under = prefix("provider.a", SURFACE, "p"); + let mut state = MemState::new(); + state.read(&at); + let id = state.subscribe(Interest::Prefix(under.clone())); + state.list(&under); + state.drain(); + state.unsubscribe(id); + assert_eq!( + state.calls(), + vec![ + Call::Read(at.clone()), + Call::Subscribe(Interest::Prefix(under.clone())), + Call::List(under), + Call::Drain, + Call::Unsubscribe(id), + ] + ); + let second = state.subscribe(Interest::Record(at)); + assert_ne!(second, id, "a subscription id is never reused"); +} -- 2.47.3 From 644f122aab1104a5288c15553dc06c4dce8e7a98 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:40:02 +0100 Subject: [PATCH 03/10] thing-testkit: fixtures README (thing2 cut 2) Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-testkit/fixtures/README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 crates/thing-testkit/fixtures/README.md diff --git a/crates/thing-testkit/fixtures/README.md b/crates/thing-testkit/fixtures/README.md new file mode 100644 index 0000000..edb41dc --- /dev/null +++ b/crates/thing-testkit/fixtures/README.md @@ -0,0 +1,22 @@ +# thing-testkit fixtures + +Each `.cc` is a CultCache single-file store of contract documents, written under the pinned +clock `2026-01-01T00:00:00Z`. The builders are `thing_testkit::fixture`; the bytes below are +frozen, and a normal test run only compares and reads them. The rows are the fixture table of +`docs/thing2-build-spec.md` section 2.5; map rules are those of the build spec. + +| File | Holds | Map rules | +|---|---|---| +| `f01-swarm-dashboard.surface.cc` | One surface: a Grid Box root, a Text bound with a Number Format, a Repeat over a RecordsSource prefix whose template binds Item members, and a Button whose CommandRef is declared | 6, 9 | +| `f09-composition-stack.surface.cc` | One surface whose Use passes one argument of each ArgValue arm and a Slot holding a second Use (two levels), and the publisher CompositionDocument both name | 5 | +| `f10-hostile.surface.cc` | Four surfaces, one hostile shape each: an undeclared CommandRef, a duplicate id after expansion, an unresolved Use, and a Bind whose schema no fixture provides; plus the one composition (`dup`) the duplicate-id surface expands | 4, 5, 6 | + +A surface whose bytes the contract refuses (an unknown union arm) cannot live in a store: that +case is `crates/thing-contract/tests/goldens/node-unknown-arm.bin`, read in place and fed to +`MemState::put_raw`. + +## Regenerate + +`THING_BLESS=1 cargo test -p thing-testkit --test fixtures every_fixture_round_trips` rewrites +the files through `golden::check`, the one bless door; review the diff before committing. Run +the tests without `THING_BLESS` to compare. -- 2.47.3 From f7fcb62d1058c73faba874ee59624455ff9cd34f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:40:29 +0100 Subject: [PATCH 04/10] thing-testkit: bless fixtures f01, f09, f10 (thing2 cut 2) Co-Authored-By: Claude Sonnet 5.5 --- .../fixtures/f01-swarm-dashboard.surface.cc | Bin 0 -> 976 bytes .../fixtures/f09-composition-stack.surface.cc | Bin 0 -> 1984 bytes .../fixtures/f10-hostile.surface.cc | Bin 0 -> 2689 bytes 3 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 crates/thing-testkit/fixtures/f01-swarm-dashboard.surface.cc create mode 100644 crates/thing-testkit/fixtures/f09-composition-stack.surface.cc create mode 100644 crates/thing-testkit/fixtures/f10-hostile.surface.cc diff --git a/crates/thing-testkit/fixtures/f01-swarm-dashboard.surface.cc b/crates/thing-testkit/fixtures/f01-swarm-dashboard.surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..c09bf8836864bee2e9972e17f1761d27c8348b7e GIT binary patch literal 976 zcmb7?ziZn-6vywH6gqavZZveNg`FXTmUPY1p)G~B1bVivu|TrI-Pt9S&Ry?^n(V>G zWN3#_3WZXHMJE3Rf&3Bq6Y_L-b>d(_D-QAQ>3u)ncc*90`=eC!Nq;~?E^VvsA_96MLq}pD8+I`8bIw3;9RFvM?rm(8~#n8wfwPJKH<$P8Zgz zPA9VK?ZtyH$KO{$XG;*CzO2a_eKix7=RzY@l~-s>V_7dGHDngg9wYnMxaH!)Zd{E1 zB`)-ayj>at_KlP4O=sg_mbQ$&1j$uBbOtJTLzfTbV)xn!7E2wNS&u!JS&1Ffl;v$X zl1AfWGf8t2!)dBgW22F|cX7Y(4TGRu_5an77_>^5`@yPKfAg7k qN_sT)9jVz1S7)_VIfwjRsVe^N{;azSkA#_*=N{A&1KP6VyL$sE)owok literal 0 HcmV?d00001 diff --git a/crates/thing-testkit/fixtures/f09-composition-stack.surface.cc b/crates/thing-testkit/fixtures/f09-composition-stack.surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..2fbb0ce2e4cf9f693d8d2d7162b30574ff28c5de GIT binary patch literal 1984 zcmd^9&2G~`5MDPF^}vA(cjOBkh?VxhAs3Li!vTZ@2nokt8jIK)t=Ekz#5?S+-R54L z0zLGA5E6fq)reD{AQBJ38^G+YleAWBID=(b>)n}eX1@7m)AwF7V4mysu@f^wv9q%& z$Dg;|5UT@+^@C{J@klr%alir+H5`4b_X5-g$65cS9YY48dl%x`UArF0zEN5}#59I< z8jT?;*oQdmfwA3v^7NHx$byeQR^rA9eeQa=X8Y4>YY1B7FniWqW*P3!C6*|Jd8;~JuF*X=9G+Ld4bE zs!a)D5{YT?16@&YfCFFHIlX-u=|``xnsugs%o_d8I#X#ZUTFdBBjc{pQV1oOMq8{) z7sSu|LuTM*vRvn>37({-%9C0PpoPeC>qYjX&)*y=hi(1vJn_45n;C@tN ajKpCCY-4{uVj|NNeOc8K#T|5n7ry~I&Gmi& literal 0 HcmV?d00001 diff --git a/crates/thing-testkit/fixtures/f10-hostile.surface.cc b/crates/thing-testkit/fixtures/f10-hostile.surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..e96531a55a06aa0abc2fd1730bcade67a9c935bf GIT binary patch literal 2689 zcmd^>&x_MQ6vq>)HxFLCm)=AZ+CA(c7d`3ClL#scn=#pNbR@S z$@i}AqI5wGEZgg<26lUx*ny3`ilrarUZ7gxIJe$52<*VspF!M))+iThJj^U#AfLc? zDvcp3*t^JWgKX*Df{F2xD09rC- z(lEY&p5kL1Fe#cQzomOjqAXpa3}$AJ?@Ii~`*qPD@PX({|I#0@8oh2z2HBUwo!t^) zGBK{U>}M_#z3C4-123`5+jREmk8qeR{c4obI7zN2BpNaKI35#A_mQdCCTx0|z~5EJ z$8J5aP<`dWkJ{LLGfgIg`2ztZ1G*N7V;g#aK(d5w36jon0m(-Iu~d_9j8aac|DF+J zcjEXwy^bM4oKReNNZGwz3v;YH1lKL(qXj`an2Qprl_C^{O>u4F>VaWxNAX>e;^&;8 zoS)bYmOS4s7Ee{An;bK#Nc3l}P6vnts)vtKj!^B+e0-#|q6j2L9=v`M&UTVafNg6- zdWN2f42P#Yq_?YkTPEp25$|PDQ(iN-E0Al0__T{TUO~Kz6-RF)M-Z2y)2Dcmj4*W$ z7lObSOS%gDl#Tp+M6lC`k_{DMyVQJAWcMlbR`ulEcvqM~ksWu_Pl}2%d&Ui9O8){Z C(Wc7) literal 0 HcmV?d00001 -- 2.47.3 From 963aec6f83b45b721838767040b6e99842b113dc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:46:51 +0100 Subject: [PATCH 05/10] thing2 cut 2: core tests for interest matching, write returns the committed bytes, unsubscribe is per interest Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-core/src/port.rs | 34 +++++++++++++++++++++++++ crates/thing-testkit/src/fixture.rs | 7 ++--- crates/thing-testkit/tests/fixtures.rs | 4 ++- crates/thing-testkit/tests/mem_state.rs | 22 ++++++++++++++++ 4 files changed, 63 insertions(+), 4 deletions(-) diff --git a/crates/thing-core/src/port.rs b/crates/thing-core/src/port.rs index 40a77c2..c897d5e 100644 --- a/crates/thing-core/src/port.rs +++ b/crates/thing-core/src/port.rs @@ -100,3 +100,37 @@ pub trait StatePort { /// each once. fn drain(&mut self) -> Vec; } + +#[cfg(test)] +mod tests { + use super::*; + + fn address(provider: &str, schema: &str, key: &str) -> Address { + Address { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key: RecordKey::new(key) } + } + + fn prefix(provider: &str, schema: &str, key_prefix: &str) -> Prefix { + Prefix { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key_prefix: key_prefix.into() } + } + + #[test] + fn a_prefix_matches_provider_schema_and_key_prefix_together() { + let under = prefix("p", "s", "row-"); + assert!(under.matches(&address("p", "s", "row-1"))); + assert!(under.matches(&address("p", "s", "row-"))); + assert!(!under.matches(&address("q", "s", "row-1"))); + assert!(!under.matches(&address("p", "t", "row-1"))); + assert!(!under.matches(&address("p", "s", "col-1"))); + assert!(!under.matches(&address("p", "s", "ro"))); + } + + #[test] + fn a_record_interest_matches_only_its_address() { + let interest = Interest::Record(address("p", "s", "k")); + assert!(interest.matches(&address("p", "s", "k"))); + assert!(!interest.matches(&address("p", "s", "k2"))); + assert!(!interest.matches(&address("q", "s", "k"))); + assert!(Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "k2"))); + assert!(!Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "j"))); + } +} diff --git a/crates/thing-testkit/src/fixture.rs b/crates/thing-testkit/src/fixture.rs index 8cf2585..ff83ad9 100644 --- a/crates/thing-testkit/src/fixture.rs +++ b/crates/thing-testkit/src/fixture.rs @@ -61,8 +61,9 @@ impl Fixture { } } - /// Encode the built documents into a store and bless or compare the committed file. - pub fn write(self) { + /// Encode the built documents into a store and bless or compare the committed file; returns + /// the committed bytes. + pub fn write(self) -> Vec { let scratch = std::env::temp_dir().join(format!("thing-testkit-{}-{}", std::process::id(), self.file_name())); let mut cache = store::create(&scratch); let set = self.build(); @@ -77,7 +78,7 @@ impl Fixture { } let bytes = std::fs::read(&scratch).unwrap(); let _ = std::fs::remove_file(&scratch); - golden::check(&Self::dir(), self.file_name(), &bytes); + golden::check(&Self::dir(), self.file_name(), &bytes) } /// The committed store, decoded through the contract. diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs index cd60559..c559c50 100644 --- a/crates/thing-testkit/tests/fixtures.rs +++ b/crates/thing-testkit/tests/fixtures.rs @@ -23,7 +23,9 @@ fn every_fixture_round_trips_through_the_contract() { on_big_stack(|| { for fixture in Fixture::ALL { // The builders reproduce the committed file byte for byte (or bless it). - fixture.write(); + let committed = fixture.write(); + assert_eq!(committed, std::fs::read(Fixture::dir().join(fixture.file_name())).unwrap()); + assert!(!committed.is_empty()); let built = fixture.build(); let loaded = fixture.load(); assert_eq!(loaded, built, "{}: the store decodes to the built documents", fixture.file_name()); diff --git a/crates/thing-testkit/tests/mem_state.rs b/crates/thing-testkit/tests/mem_state.rs index 512160e..1a0c5d9 100644 --- a/crates/thing-testkit/tests/mem_state.rs +++ b/crates/thing-testkit/tests/mem_state.rs @@ -243,3 +243,25 @@ fn every_call_is_logged_in_order() { let second = state.subscribe(Interest::Record(at)); assert_ne!(second, id, "a subscription id is never reused"); } + +#[test] +fn unsubscribing_ends_only_that_interest() { + let provider_a = provider("provider.a"); + let panel = composition("provider.a", "panel"); + let one = surface("provider.a", "one"); + let panel_at = address("provider.a", COMPOSITION, &panel.record_key()); + let mut state = MemState::new(); + let by_record = state.subscribe(Interest::Record(panel_at.clone())); + let by_prefix = state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:"))); + + state.unsubscribe(by_prefix); + state.put(&provider_a, &one); + state.put(&provider_a, &panel); + let drained = state.drain(); + assert_eq!(drained.len(), 1, "only the composition interest is live: {drained:?}"); + assert!(matches!(&drained[0], Change::Upsert(entry) if entry.address == panel_at)); + + state.unsubscribe(by_record); + state.put(&provider_a, &panel); + assert!(state.drain().is_empty()); +} -- 2.47.3 From f8c7af593ebb5dcdd786b3bbfbfe23a39a665adb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:01:21 +0100 Subject: [PATCH 06/10] thing2 cut 2 fix batch: fixture load never writes, bless writer tested, MemState edges pinned Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-core/src/port.rs | 3 +- crates/thing-testkit/src/fixture.rs | 13 +++++++-- crates/thing-testkit/src/mem_state.rs | 2 ++ crates/thing-testkit/tests/fixtures.rs | 22 ++++++++++++++ crates/thing-testkit/tests/golden.rs | 27 ++++++++++++++++++ crates/thing-testkit/tests/mem_state.rs | 38 +++++++++++++++++++++++++ 6 files changed, 102 insertions(+), 3 deletions(-) diff --git a/crates/thing-core/src/port.rs b/crates/thing-core/src/port.rs index c897d5e..9687fba 100644 --- a/crates/thing-core/src/port.rs +++ b/crates/thing-core/src/port.rs @@ -96,7 +96,8 @@ pub trait StatePort { fn unsubscribe(&mut self, id: SubscriptionId); - /// Every change since the last drain that some live interest matches, in mutation order, + /// Every change since the last drain that some interest matched when it happened, in mutation + /// order (unsubscribing does not recall changes already queued), /// each once. fn drain(&mut self) -> Vec; } diff --git a/crates/thing-testkit/src/fixture.rs b/crates/thing-testkit/src/fixture.rs index ff83ad9..8ffc052 100644 --- a/crates/thing-testkit/src/fixture.rs +++ b/crates/thing-testkit/src/fixture.rs @@ -83,8 +83,17 @@ impl Fixture { /// The committed store, decoded through the contract. pub fn load(self) -> FixtureSet { - let cache = store::open(&Self::dir().join(self.file_name())); - FixtureSet::new(cache.get_all().unwrap(), cache.get_all().unwrap(), cache.get_all().unwrap()) + // Opening a store creates a lock file beside it, so open a copy: the fixtures directory + // is never written by a load. + let work = std::env::temp_dir().join(format!("thing-testkit-load-{}-{}", std::process::id(), self.file_name())); + std::fs::create_dir_all(&work).unwrap(); + let copy = work.join(self.file_name()); + std::fs::copy(Self::dir().join(self.file_name()), ©).unwrap(); + let cache = store::open(©); + let set = FixtureSet::new(cache.get_all().unwrap(), cache.get_all().unwrap(), cache.get_all().unwrap()); + drop(cache); + let _ = std::fs::remove_dir_all(&work); + set } } diff --git a/crates/thing-testkit/src/mem_state.rs b/crates/thing-testkit/src/mem_state.rs index 96ec2cb..b649c4e 100644 --- a/crates/thing-testkit/src/mem_state.rs +++ b/crates/thing-testkit/src/mem_state.rs @@ -208,6 +208,8 @@ impl StatePort for MemState { Some(value) => Lookup::Present(Entry { address: address.clone(), record: value.into_record() }), None => Lookup::Absent, } + // A schema outside the four contract arms reads Absent. Cut 4 replaces this with the provider-state + // answer once thing2:question:provider-state-value is ruled. }, else Lookup::Absent) } diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs index c559c50..4702291 100644 --- a/crates/thing-testkit/tests/fixtures.rs +++ b/crates/thing-testkit/tests/fixtures.rs @@ -161,3 +161,25 @@ fn a_state_holds_every_fixture_document_under_its_publisher() { }; assert!(matches!(state.read(&at), Lookup::Present(_))); } + +#[test] +fn loading_a_fixture_writes_nothing_in_the_fixtures_directory() { + let listing = || { + let mut names: Vec<_> = std::fs::read_dir(Fixture::dir()) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + names.sort(); + names + }; + let before = listing(); + let mut permissions = std::fs::metadata(Fixture::dir()).unwrap().permissions(); + let writable = permissions.clone(); + permissions.set_readonly(true); + std::fs::set_permissions(Fixture::dir(), permissions).unwrap(); + for fixture in Fixture::ALL { + load(fixture); + } + std::fs::set_permissions(Fixture::dir(), writable).unwrap(); + assert_eq!(listing(), before); +} diff --git a/crates/thing-testkit/tests/golden.rs b/crates/thing-testkit/tests/golden.rs index 4930d57..367cddd 100644 --- a/crates/thing-testkit/tests/golden.rs +++ b/crates/thing-testkit/tests/golden.rs @@ -57,3 +57,30 @@ fn read_returns_the_committed_bytes() { std::fs::write(dir.join("r.bin"), b"abc").unwrap(); assert_eq!(golden::read(&dir, "r.bin"), b"abc"); } + +/// Re-runs this binary with THING_BLESS=1 so the writer is observed without touching this +/// process's environment. +#[test] +fn blessing_writes_the_file_and_the_text() { + let dir = scratch("bless"); + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "bless_child", "--test-threads=1"]) + .env("THING_BLESS", "1") + .env("THING_BLESS_CHILD_DIR", &dir) + .status() + .unwrap(); + assert!(status.success()); + assert_eq!(std::fs::read(dir.join("b.bin")).unwrap(), b"blessed"); + assert_eq!(std::fs::read(dir.join("t.bin")).unwrap(), b"tb"); + assert_eq!(std::fs::read(dir.join("t.txt")).unwrap(), b"tt"); +} + +/// The child half of the test above; does nothing in a normal run. +#[test] +fn bless_child() { + if let Ok(dir) = std::env::var("THING_BLESS_CHILD_DIR") { + let dir = PathBuf::from(dir); + golden::check(&dir, "b.bin", b"blessed"); + golden::check_with_text(&dir, "t", b"tb", "tt"); + } +} diff --git a/crates/thing-testkit/tests/mem_state.rs b/crates/thing-testkit/tests/mem_state.rs index 1a0c5d9..44651bd 100644 --- a/crates/thing-testkit/tests/mem_state.rs +++ b/crates/thing-testkit/tests/mem_state.rs @@ -265,3 +265,41 @@ fn unsubscribing_ends_only_that_interest() { state.put(&provider_a, &panel); assert!(state.drain().is_empty()); } + +#[test] +fn unsubscribing_keeps_changes_already_queued() { + let one = surface("provider.a", "one"); + let mut state = MemState::new(); + let id = state.subscribe(Interest::Record(surface_at("provider.a", &one))); + state.put(&provider("provider.a"), &one); + state.unsubscribe(id); + assert_eq!(state.drain().len(), 1, "a change queued while the interest was live is still drained"); +} + +#[test] +fn a_list_mixes_refused_and_present_in_key_order() { + let a = surface("provider.a", "a"); + let c = surface("provider.a", "c"); + let b_at = address("provider.a", SURFACE, "thing:surface:provider.a.b"); + let mut state = MemState::new(); + state.put(&provider("provider.a"), &c); + state.put_raw(b_at.clone(), unknown_arm()); + state.put(&provider("provider.a"), &a); + let kinds: Vec<(&str, String)> = state + .list(&prefix("provider.a", SURFACE, "thing:")) + .into_iter() + .map(|lookup| match lookup { + Lookup::Present(entry) => ("present", entry.address.key.as_str().to_string()), + Lookup::Refused(refusal) => ("refused", refusal.address.key.as_str().to_string()), + Lookup::Absent => panic!("a list holds no absence"), + }) + .collect(); + assert_eq!( + kinds, + [ + ("present", "thing:surface:provider.a.a".to_string()), + ("refused", b_at.key.as_str().to_string()), + ("present", "thing:surface:provider.a.c".to_string()), + ] + ); +} -- 2.47.3 From a9dcab651620a9963eb1213423da4dbe3f4c62f0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:02:15 +0100 Subject: [PATCH 07/10] thing-testkit: Fixture::open reads a copy so the fixtures directory stays unwritten Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-testkit/src/fixture.rs | 21 +++++++++++++-------- crates/thing-testkit/tests/fixtures.rs | 3 +-- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/crates/thing-testkit/src/fixture.rs b/crates/thing-testkit/src/fixture.rs index 8ffc052..d982071 100644 --- a/crates/thing-testkit/src/fixture.rs +++ b/crates/thing-testkit/src/fixture.rs @@ -4,6 +4,7 @@ use std::path::PathBuf; +use cultcache_rs::CultCache; use thing_contract::*; use crate::build::*; @@ -81,19 +82,23 @@ impl Fixture { golden::check(&Self::dir(), self.file_name(), &bytes) } - /// The committed store, decoded through the contract. - pub fn load(self) -> FixtureSet { - // Opening a store creates a lock file beside it, so open a copy: the fixtures directory - // is never written by a load. - let work = std::env::temp_dir().join(format!("thing-testkit-load-{}-{}", std::process::id(), self.file_name())); + + /// The committed store, opened through the contract. Opening creates a lock file beside the + /// store, so this opens a copy: the fixtures directory is never written. + pub fn open(self) -> CultCache { + let work = std::env::temp_dir().join(format!("thing-testkit-open-{}-{}", std::process::id(), self.file_name())); std::fs::create_dir_all(&work).unwrap(); let copy = work.join(self.file_name()); std::fs::copy(Self::dir().join(self.file_name()), ©).unwrap(); let cache = store::open(©); - let set = FixtureSet::new(cache.get_all().unwrap(), cache.get_all().unwrap(), cache.get_all().unwrap()); - drop(cache); let _ = std::fs::remove_dir_all(&work); - set + cache + } + + /// The committed store, decoded through the contract. + pub fn load(self) -> FixtureSet { + let cache = self.open(); + FixtureSet::new(cache.get_all().unwrap(), cache.get_all().unwrap(), cache.get_all().unwrap()) } } diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs index 4702291..ac44d06 100644 --- a/crates/thing-testkit/tests/fixtures.rs +++ b/crates/thing-testkit/tests/fixtures.rs @@ -5,7 +5,6 @@ use thing_contract::*; use thing_testkit::fixture::{Fixture, FixtureSet}; use thing_testkit::mem_state::MemState; -use thing_testkit::store; use thing_core::port::{Address, Lookup, StatePort}; /// Decoding runs on a 16 MiB thread until the workspace pin of cultcache-rs carries @@ -31,7 +30,7 @@ fn every_fixture_round_trips_through_the_contract() { assert_eq!(loaded, built, "{}: the store decodes to the built documents", fixture.file_name()); // Each record re-encodes to its stored payload. - let cache = store::open(&Fixture::dir().join(fixture.file_name())); + let cache = fixture.open(); for surface in &loaded.surfaces { let stored = cache.get_envelope::(&surface.record_key()).unwrap().unwrap(); assert_eq!(rmp_serde::to_vec(surface).unwrap(), stored.payload); -- 2.47.3 From aa0dd94ec65f11cde1b3d8dcf7ee30cc88f8fd8a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:03:07 +0100 Subject: [PATCH 08/10] thing-testkit tests: compare stored payloads from the snapshot Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-testkit/tests/fixtures.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs index ac44d06..f44d270 100644 --- a/crates/thing-testkit/tests/fixtures.rs +++ b/crates/thing-testkit/tests/fixtures.rs @@ -31,16 +31,17 @@ fn every_fixture_round_trips_through_the_contract() { // Each record re-encodes to its stored payload. let cache = fixture.open(); + let stored = cache.snapshot_envelopes(); + let payload = |kind: &str, key: String| { + stored.iter().find(|envelope| envelope.r#type == kind && envelope.key == key).unwrap().payload.clone() + }; for surface in &loaded.surfaces { - let stored = cache.get_envelope::(&surface.record_key()).unwrap().unwrap(); - assert_eq!(rmp_serde::to_vec(surface).unwrap(), stored.payload); + assert_eq!(rmp_serde::to_vec(surface).unwrap(), payload("gamecult.thing.surface", surface.record_key())); } for composition in &loaded.compositions { - let stored = cache.get_envelope::(&composition.record_key()).unwrap().unwrap(); - assert_eq!(rmp_serde::to_vec(composition).unwrap(), stored.payload); + let key = composition.record_key(); + assert_eq!(rmp_serde::to_vec(composition).unwrap(), payload("gamecult.thing.composition", key)); } - assert_eq!( - cache.snapshot_envelopes().len(), loaded.surfaces.len() + loaded.compositions.len() + loaded.catalogs.len(), "{}: the store holds the documents and nothing else", fixture.file_name() -- 2.47.3 From 7165c998d0b8a6acfc0649f4460963549f590419 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:03:41 +0100 Subject: [PATCH 09/10] thing-testkit tests: restore assert_eq Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-testkit/tests/fixtures.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs index f44d270..7508e7b 100644 --- a/crates/thing-testkit/tests/fixtures.rs +++ b/crates/thing-testkit/tests/fixtures.rs @@ -42,6 +42,8 @@ fn every_fixture_round_trips_through_the_contract() { let key = composition.record_key(); assert_eq!(rmp_serde::to_vec(composition).unwrap(), payload("gamecult.thing.composition", key)); } + assert_eq!( + stored.len(), loaded.surfaces.len() + loaded.compositions.len() + loaded.catalogs.len(), "{}: the store holds the documents and nothing else", fixture.file_name() -- 2.47.3 From e0ed7e9a1de8f002fb9a6aa26e0e941a9622ca9a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:18:25 +0100 Subject: [PATCH 10/10] thing-testkit: each fixture open has its own temp directory; the read-only test restores permissions on drop Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-testkit/src/fixture.rs | 7 +++++-- crates/thing-testkit/tests/fixtures.rs | 10 ++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/thing-testkit/src/fixture.rs b/crates/thing-testkit/src/fixture.rs index d982071..07eaa10 100644 --- a/crates/thing-testkit/src/fixture.rs +++ b/crates/thing-testkit/src/fixture.rs @@ -84,9 +84,12 @@ impl Fixture { /// The committed store, opened through the contract. Opening creates a lock file beside the - /// store, so this opens a copy: the fixtures directory is never written. + /// store, so this opens a copy in a directory of its own (process id and a serial), removed + /// once the store is read: the fixtures directory is never written. pub fn open(self) -> CultCache { - let work = std::env::temp_dir().join(format!("thing-testkit-open-{}-{}", std::process::id(), self.file_name())); + static OPENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let serial = OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let work = std::env::temp_dir().join(format!("thing-testkit-open-{}-{serial}", std::process::id())); std::fs::create_dir_all(&work).unwrap(); let copy = work.join(self.file_name()); std::fs::copy(Self::dir().join(self.file_name()), ©).unwrap(); diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs index 7508e7b..73c0e00 100644 --- a/crates/thing-testkit/tests/fixtures.rs +++ b/crates/thing-testkit/tests/fixtures.rs @@ -175,13 +175,19 @@ fn loading_a_fixture_writes_nothing_in_the_fixtures_directory() { names }; let before = listing(); + // Restores the directory's permissions even when the test panics. + struct Restore(std::fs::Permissions); + impl Drop for Restore { + fn drop(&mut self) { + let _ = std::fs::set_permissions(Fixture::dir(), self.0.clone()); + } + } let mut permissions = std::fs::metadata(Fixture::dir()).unwrap().permissions(); - let writable = permissions.clone(); + let _restore = Restore(permissions.clone()); permissions.set_readonly(true); std::fs::set_permissions(Fixture::dir(), permissions).unwrap(); for fixture in Fixture::ALL { load(fixture); } - std::fs::set_permissions(Fixture::dir(), writable).unwrap(); assert_eq!(listing(), before); } -- 2.47.3