From 15976b125830e5ebf2a544b67dffda9d19e7576c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:46:55 +0100 Subject: [PATCH] Thing 2.0 cut 4 fixes: every member kind against every site kind, refusals and vanished sites dirty, nested records from a real store, budget and template-id edges Soul s1: the Mixed testkit record (int, bool, nil, nested, list, stamp) and the tests that kill its 14 survivors. Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-core/src/bind/format.rs | 4 +- crates/thing-core/tests/bind.rs | 264 ++++++++++++++++++++++++++- crates/thing-testkit/src/state.rs | 43 ++++- 3 files changed, 307 insertions(+), 4 deletions(-) diff --git a/crates/thing-core/src/bind/format.rs b/crates/thing-core/src/bind/format.rs index 85de973..0f3078f 100644 --- a/crates/thing-core/src/bind/format.rs +++ b/crates/thing-core/src/bind/format.rs @@ -1,7 +1,7 @@ //! Format: total and locale-free. Each function takes the value the site read and returns the //! text, or the reason the value does not fit (a detail that never carries the value). -use thing_contract::{AffixFormat, NumberFormat, is_stored_at_stamp}; +use thing_contract::{AffixFormat, NumberFormat, is_timestamp_text}; /// Fixed-point text of `n` at `format.precision`, scaled by 100 for a percent, with the percent /// sign and the unit. Non-finite numbers print as NaN, inf, -inf; negative zero prints as zero. @@ -80,7 +80,7 @@ fn civil(days: i64) -> (i64, i64, i64) { /// Text that is already a `stored_at` stamp, as written. pub fn stamp(text: &str) -> Result { - if is_stored_at_stamp(text) { Ok(text.to_string()) } else { Err("the text is not a timestamp") } + if is_timestamp_text(text) { Ok(text.to_string()) } else { Err("the text is not a timestamp") } } pub fn affix(text: &str, format: &AffixFormat) -> String { diff --git a/crates/thing-core/tests/bind.rs b/crates/thing-core/tests/bind.rs index 46af8c8..4e78e17 100644 --- a/crates/thing-core/tests/bind.rs +++ b/crates/thing-core/tests/bind.rs @@ -13,7 +13,7 @@ use thing_testkit::build::*; use thing_testkit::fixture::Fixture; use thing_testkit::golden; use thing_testkit::mem_state::{Call, MemState}; -use thing_testkit::state::{self, Item, Series, Swarm, SwarmRenamed}; +use thing_testkit::state::{self, Inner, Item, Mixed, Series, Swarm, SwarmRenamed}; const SWARM: &str = "provider.swarm"; const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1"; @@ -617,3 +617,265 @@ fn pipeline_smoke_f09() { assert_eq!(code(value(tree, "std-stat/stat-value", Field::Content)), Code::BindTypeMismatch); assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::>(), [Code::BindTypeMismatch]); } + +static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +const MIXED: &str = "gamecult.thing.test.mixed.v1"; + +fn mixed(id: &str, count: i64, maybe: Option<&str>) -> Mixed { + Mixed { + id: id.into(), + count, + flag: true, + maybe: maybe.map(Into::into), + inner: Inner { label: "L".into(), weight: 2.5 }, + tags: vec!["a".into(), "b".into()], + when: "2026-01-01T00:00:00Z".into(), + } +} + +/// A state whose `Mixed` records came through a real store file and `load_store`, so every value is +/// what the port decodes by the store's own member rows. +fn mixed_state(records: &[(&str, Mixed)]) -> MemState { + let dir = std::env::temp_dir().join(format!("thing-bind-mixed-{}-{}", std::process::id(), SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("mixed.cc"); + std::fs::write(&path, state::mixed_store(records)).unwrap(); + let mut state = MemState::new(); + state.load_store(&ProviderId::new(SWARM), &path); + let _ = std::fs::remove_dir_all(&dir); + state +} + +fn mixed_bind(key: &str, steps: Vec, format: Option) -> Bind { + bind_at(MIXED, key, steps, format) +} + +fn mixed_records(prefix: &str) -> CollectionSource { + CollectionSource::Records(RecordsSource { provider: Some(ProviderId::new(SWARM)), schema: SchemaId::new(MIXED), key_prefix: prefix.into() }) +} + +fn repeat_over(id: &str, collection: CollectionSource, key: &[&str], template: Node) -> Node { + Node::Repeat(RepeatNode { common: common(id), collection, key_member: path(key), template: std::boxed::Box::new(template) }) +} + +fn with_x(mut document: SurfaceDocument) -> SurfaceDocument { + document.commands = vec![CommandDecl { id: CommandId::new("x"), payload_schema: SchemaId::new("gamecult.thing.test.x.v1"), captures: vec![], confirm: None }]; + document +} + +fn site_of(kind: &str, bind: Bind) -> Node { + match kind { + "text" => bound_text(kind, bind), + "number" => Node::Slider(SliderNode { common: common(kind), min: 0.0, max: 1.0, step: 0.1, value: NumberSource::Bound(bind), commit: command("x") }), + "bool" => Node::Toggle(ToggleNode { common: common(kind), checked: BoolSource::Bound(bind), on_change: command("x") }), + "series" => Node::Plot(PlotNode { common: common(kind), series: bind, mark: PlotMark::Line, x_min: None, x_max: None, y_min: None, y_max: None }), + _ => unreachable!(), + } +} + +fn kind_field(kind: &str) -> Field { + match kind { + "text" => Field::Content, + "number" => Field::Value, + "bool" => Field::Checked, + _ => Field::Series, + } +} + +#[test] +fn every_member_kind_against_every_site_kind() { + use Bound::*; + // (member, [text, number, bool, series]); None is BindTypeMismatch. + let rows: [(&str, [Option; 4]); 6] = [ + ("Id", [Some(Text("m1".into())), None, None, None]), + ("Count", [None, Some(Number(7.0)), None, None]), + ("Flag", [None, None, Some(Bool(true)), None]), + ("Inner", [None, None, None, None]), + ("Tags", [None, None, None, None]), + ("Maybe", [Some(Absent), Some(Absent), Some(Absent), Some(Absent)]), + ]; + let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None))])); + for (member, expected) in rows { + for (kind, want) in ["text", "number", "bool", "series"].into_iter().zip(expected) { + let document = with_x(page(&format!("pair-{member}-{kind}"), vec![site_of(kind, mixed_bind("m1", vec![name(member)], None))])); + rig.bind(&document); + let got = value(rig.tree(&document), kind, kind_field(kind)); + match want { + Some(bound) => assert_eq!(got, &bound, "{member} at a {kind} site"), + None => assert_eq!(code(got), Code::BindTypeMismatch, "{member} at a {kind} site"), + } + } + } +} + +#[test] +fn a_series_with_a_non_number_is_refused_whole() { + // The nested record decodes as [Text, Float]: filtering would bind [2.5]. + let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None))])); + let document = with_x(page("series", vec![site_of("series", mixed_bind("m1", vec![name("Inner")], None))])); + rig.bind(&document); + assert_eq!(code(value(rig.tree(&document), "series", Field::Series)), Code::BindTypeMismatch); +} + +#[test] +fn nested_records_are_positional_and_a_name_step_into_one_is_loud() { + let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None))])); + let one = Some(Format::Number(NumberFormat { precision: count(1), percent: false, unit: None })); + let document = page( + "nested", + vec![ + bound_text("by-name", mixed_bind("m1", vec![name("Inner"), name("Label")], None)), + bound_text("by-index", mixed_bind("m1", vec![name("Inner"), index(0)], None)), + bound_text("weight", mixed_bind("m1", vec![name("Inner"), index(1)], one)), + bound_text("past", mixed_bind("m1", vec![name("Inner"), index(2)], None)), + ], + ); + let applied = rig.bind(&document); + let tree = rig.tree(&document); + assert_eq!(code(value(tree, "by-name", Field::Content)), Code::BindTypeMismatch); + assert_eq!(value(tree, "by-index", Field::Content), &Bound::Text("L".into())); + assert_eq!(value(tree, "weight", Field::Content), &Bound::Text("2.5".into())); + assert_eq!(code(value(tree, "past", Field::Content)), Code::BindMemberMissing); + assert_eq!(applied.diagnostics.len(), 2); +} + +#[test] +fn timestamp_text_is_validated_and_shown_as_written() { + let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None))])); + let document = page( + "stamps", + vec![ + bound_text("stamp", mixed_bind("m1", vec![name("When")], Some(Format::Timestamp))), + bound_text("not-a-stamp", mixed_bind("m1", vec![name("Id")], Some(Format::Timestamp))), + bound_text("text-as-duration", mixed_bind("m1", vec![name("Id")], Some(Format::Duration))), + ], + ); + rig.bind(&document); + let tree = rig.tree(&document); + assert_eq!(value(tree, "stamp", Field::Content), &Bound::Text("2026-01-01T00:00:00Z".into())); + assert_eq!(code(value(tree, "not-a-stamp", Field::Content)), Code::BindTypeMismatch); + assert_eq!(code(value(tree, "text-as-duration", Field::Content)), Code::BindTypeMismatch); +} + +#[test] +fn nil_is_absence_at_the_end_and_in_the_middle_but_an_error_as_an_option() { + let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None)), ("m2", mixed("m2", 8, Some("two")))])); + let select = Node::Select(SelectNode { + common: common("pick"), + options: OptionList::Bound(BoundOptions { collection: mixed_records("m"), value_member: path(&["Id"]), label_member: path(&["Maybe"]) }), + value: mixed_bind("m1", vec![name("Maybe"), name("deeper")], None), + on_change: command("x"), + }); + let document = with_x(page( + "nil", + vec![bound_text("end", mixed_bind("m1", vec![name("Maybe")], None)), bound_text("middle", mixed_bind("m1", vec![name("Maybe"), name("x")], None)), select], + )); + let applied = rig.bind(&document); + let tree = rig.tree(&document); + assert_eq!(value(tree, "end", Field::Content), &Bound::Absent); + assert_eq!(value(tree, "middle", Field::Content), &Bound::Absent); + assert_eq!(value(tree, "pick", Field::Selected), &Bound::Absent); + assert_eq!(code(value(tree, "pick", Field::Options)), Code::BindTypeMismatch); + assert_eq!(applied.diagnostics.len(), 1); +} + +#[test] +fn collections_and_keys_take_their_own_kinds() { + let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None)), ("m2", mixed("m2", 8, None))])); + let tag = |id: &str| bound_text(id, item_bind(path(&[]))); + let document = page( + "collections", + vec![ + // A list member of a record: the items are its elements, keyed by themselves. + repeat_over("tags", CollectionSource::Member(mixed_bind("m1", vec![name("Tags")], None)), &[], tag("tag")), + // A member that is not a list is the Repeat's error, not an empty Repeat. + repeat_over("not-a-list", CollectionSource::Member(mixed_bind("m1", vec![name("Count")], None)), &[], tag("tag2")), + // An Int key is its decimal text. + repeat_over("by-count", mixed_records("m"), &["Count"], bound_text("c", item_bind(path(&["Id"])))), + // A key that is neither Text nor Int is the Repeat's error. + repeat_over("by-flag", mixed_records("m"), &["Flag"], bound_text("f", item_bind(path(&["Id"])))), + // A record that is not there is an empty Repeat, not an error. + repeat_over("absent", CollectionSource::Member(mixed_bind("nobody", vec![name("Tags")], None)), &[], tag("tag3")), + ], + ); + rig.bind(&document); + let tree = rig.tree(&document); + assert_eq!(tree.instances(&nid("tags")).iter().map(|i| i.key.as_str()).collect::>(), ["a", "b"]); + assert_eq!(value(tree, "tags#1:a/tag", Field::Content), &Bound::Text("a".into())); + assert_eq!(tree.repeat_error(&nid("not-a-list")).map(|e| e.code), Some(Code::BindTypeMismatch)); + assert_eq!(tree.instances(&nid("by-count")).iter().map(|i| i.key.as_str()).collect::>(), ["7", "8"]); + assert_eq!(value(tree, "by-count#1:7/c", Field::Content), &Bound::Text("m1".into())); + assert_eq!(tree.repeat_error(&nid("by-flag")).map(|e| e.code), Some(Code::BindTypeMismatch)); + assert!(tree.instances(&nid("absent")).is_empty() && tree.repeat_error(&nid("absent")).is_none()); +} + +#[test] +fn a_refusal_reaches_the_site_and_marks_it_dirty() { + let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard); + rig.bind(&document); + rig.state.put_state_raw(address("summary"), vec![0xc1], &Swarm::schema_members()); + let applied = rig.settle(); + assert_eq!(code(value(rig.tree(&document), "load", Field::Content)), Code::DecodeRefused); + assert_eq!(nodes(&applied, &document), ["load"]); + assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::>(), [Code::DecodeRefused]); + + // A refused item of the collection becomes a refused instance in place. + rig.state.put_state_raw(address("mind-2"), vec![0xc1], &Swarm::schema_members()); + let applied = rig.settle(); + let keys: Vec = rig.tree(&document).instances(&nid("minds")).iter().map(|i| i.key.clone()).collect(); + assert_eq!(keys, ["mind-1", "!mind-2", "mind-3"]); + assert!(nodes(&applied, &document).contains(&"minds".to_string())); + assert_eq!(code(value(rig.tree(&document), "minds!6:mind-2/mind-name", Field::Content)), Code::DecodeRefused); + + // The record coming back replaces the refusal. + rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Swarm", 0.1)); + let applied = rig.settle(); + assert_eq!(value(rig.tree(&document), "load", Field::Content), &Bound::Text("10.0%".into())); + assert_eq!(nodes(&applied, &document), ["load"]); +} + +#[test] +fn what_a_rebind_drops_is_dirty() { + let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard); + rig.bind(&document); + // The Repeat becomes a Box (only a Visible site) with its id (so the id is not a vanished site) and the button goes. + let mut next = document.clone(); + let Node::Box(root) = &mut next.root else { panic!("root is a Box") }; + root.children = vec![root.children[0].clone(), boxed("minds", vec![])]; + next.commands.clear(); + let applied = rig.bind(&next); + let dirty = nodes(&applied, &next); + for gone in ["restart", "restart-label", "minds#6:mind-1/mind-name"] { + assert!(dirty.contains(&gone.to_string()), "{gone} vanished and is not dirty: {dirty:?}"); + } + // `minds` keeps a visible site equal to before: only its instance set vanished. + assert!(dirty.contains(&"minds".to_string())); + assert!(!dirty.contains(&"load".to_string())); + assert!(rig.tree(&next).instances(&nid("minds")).is_empty()); +} + +#[test] +fn instance_budget_edge_and_the_ids_of_other_templates() { + let source = || CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() }); + let document = page("budget", vec![repeat_over("rows", source(), &["Id"], text("t", "row"))]); + let tree = resolve(&document, &swarm_state(), &Limits::default()).tree.unwrap(); + for (max_nodes, fine) in [(3, true), (2, false)] { + let mut state = swarm_state(); + let mut binder = Binder::new(Limits { max_nodes, ..Limits::default() }); + binder.bind(tree.clone(), &mut state, &mut Ledger::new()); + let bound = binder.tree(&document.record_key()).unwrap(); + assert_eq!(bound.repeat_error(&nid("rows")).is_none(), fine, "max_nodes {max_nodes}"); + } + + // An id inside another Repeat's template is an id of the tree too. + let hidden = repeat_over( + "other", + CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "zzz".into() }), + &["Id"], + text("rows#6:mind-1/t", "taken"), + ); + let document = page("hidden", vec![repeat_over("rows", source(), &["Id"], text("t", "row")), hidden]); + let mut rig = Rig::new(swarm_state()); + rig.bind(&document); + assert_eq!(rig.tree(&document).repeat_error(&nid("rows")).map(|e| e.code), Some(Code::DuplicateNodeId)); +} diff --git a/crates/thing-testkit/src/state.rs b/crates/thing-testkit/src/state.rs index 59e0f89..43b7d42 100644 --- a/crates/thing-testkit/src/state.rs +++ b/crates/thing-testkit/src/state.rs @@ -5,7 +5,7 @@ //! A CultCache store names a record's schema by its entry type, not by `SCHEMA_NAME`, so each type //! here is registered under its schema id: the id a Bind names is the id the store holds. -use cultcache_rs::DatabaseEntry; +use cultcache_rs::{CultSlots, DatabaseEntry}; use serde::{Deserialize, Serialize}; use thing_contract::{ProviderId, RecordKey, SchemaId}; use thing_core::port::Address; @@ -51,6 +51,47 @@ pub struct SwarmRenamed { pub burden: f64, } +/// A nested record: it decodes as a positional list, `[label, weight]`. +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct Inner { + #[cultcache(key = 0)] + pub label: String, + #[cultcache(key = 1)] + pub weight: f64, +} + +/// One member of every kind a site can be asked for: text, int, bool, nil, a nested record, a +/// list of text and a stamp. +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "gamecult.thing.test.mixed.v1", schema = "gamecult.thing.test.mixed.v1")] +pub struct Mixed { + #[cultcache(key = 0)] + pub id: String, + #[cultcache(key = 1)] + pub count: i64, + #[cultcache(key = 2)] + pub flag: bool, + #[cultcache(key = 3)] + pub maybe: Option, + #[cultcache(key = 4)] + pub inner: Inner, + #[cultcache(key = 5)] + pub tags: Vec, + #[cultcache(key = 6)] + pub when: String, +} + +/// A committed-store stand-in: the bytes of a store holding `records` under the pinned clock, +/// written by the real cache with `Mixed` registered, for `MemState::load_store`. +pub fn mixed_store(records: &[(&str, Mixed)]) -> Vec { + crate::store::bytes(|cache| { + cache.register_entry_type::().unwrap(); + for (key, record) in records { + crate::store::put_pinned(cache, key, record); + } + }) +} + #[derive(Clone, Debug, PartialEq, DatabaseEntry)] #[cultcache(type = "gamecult.thing.test.target.v1", schema = "gamecult.thing.test.target.v1")] pub struct Target {