Thing 2.0 cut 4: no value kind is read as another (text that parses, bytes, floats, ints at option and key sites), and a port that lists a record of another schema
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Successful in 3m0s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Successful in 3m38s

MemState::put_value serves a decoded value a typed record cannot hold. Soul s2.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 04:07:05 +01:00
commit 0ba85530ea
2 changed files with 164 additions and 1 deletions

View file

@ -7,7 +7,7 @@ use std::path::PathBuf;
use thing_contract::*;
use thing_core::bind::{Applied, Binder, Bound, BoundTree, Field};
use thing_core::diagnostic::Code;
use thing_core::port::{Address, Change, Interest, Ledger, Prefix, StatePort};
use thing_core::port::{Address, Change, Interest, Ledger, Prefix, StatePort, StateValue};
use thing_core::resolve::{Limits, resolve};
use thing_testkit::build::*;
use thing_testkit::fixture::Fixture;
@ -879,3 +879,155 @@ fn instance_budget_edge_and_the_ids_of_other_templates() {
rig.bind(&document);
assert_eq!(rig.tree(&document).repeat_error(&nid("rows")).map(|e| e.code), Some(Code::DuplicateNodeId));
}
const RAW: &str = "gamecult.thing.test.raw.v1";
fn raw_address(key: &str) -> Address {
Address { provider: ProviderId::new(SWARM), schema: SchemaId::new(RAW), key: RecordKey::new(key) }
}
fn raw_record(members: Vec<(&str, StateValue)>) -> StateValue {
StateValue::Record(members.into_iter().map(|(name, value)| (name.to_string(), value)).collect())
}
/// One record holding a value of every kind a reader could be tempted to convert: numeric,
/// boolean and stamp text, bytes, a float and an int, a list of numeric text and a list of numbers.
fn raw_state() -> MemState {
use StateValue::*;
let mut state = MemState::new();
let members = vec![
("Num", Text("42".into())),
("Truth", Text("true".into())),
("Stamp", Text("2026-01-01T00:00:00Z".into())),
("Blob", Bytes(vec![0x34, 0x32])),
("Float", Float(1.5)),
("Int", Int(3)),
("NumTexts", List(vec![Text("1".into()), Text("2".into())])),
("Numbers", List(vec![Int(1), Float(2.5)])),
("Bools", List(vec![Bool(true)])),
];
state.put_value(raw_address("r1"), raw_record(members));
state
}
#[test]
fn no_value_kind_is_read_as_another() {
use Bound::*;
// (member, [text, number, bool, series]); None is BindTypeMismatch.
let rows: [(&str, [Option<Bound>; 4]); 9] = [
("Num", [Some(Text("42".into())), None, None, None]),
("Truth", [Some(Text("true".into())), None, None, None]),
("Stamp", [Some(Text("2026-01-01T00:00:00Z".into())), None, None, None]),
("Blob", [None, None, None, None]),
("Float", [None, Some(Number(1.5)), None, None]),
("Int", [None, Some(Number(3.0)), None, None]),
("NumTexts", [None, None, None, None]),
("Numbers", [None, None, None, Some(Series(vec![1.0, 2.5]))]),
("Bools", [None, None, None, None]),
];
let mut rig = Rig::new(raw_state());
for (member, expected) in rows {
for (kind, want) in ["text", "number", "bool", "series"].into_iter().zip(expected) {
let document = with_x(page(&format!("raw-{member}-{kind}"), vec![site_of(kind, bind_at(RAW, "r1", 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 options_and_keys_take_text_and_int_only() {
use StateValue::*;
let mut state = MemState::new();
for (key, text, int, float, blob, flag) in [("r1", "a", 1, 1.5, vec![1u8], true), ("r2", "b", 2, 2.5, vec![2u8], false)] {
let members = vec![
("Id", Text(text.into())),
("Int", Int(int)),
("Float", Float(float)),
("Blob", Bytes(blob)),
("Flag", Bool(flag)),
];
state.put_value(raw_address(key), raw_record(members));
}
let records = || CollectionSource::Records(RecordsSource { provider: Some(ProviderId::new(SWARM)), schema: SchemaId::new(RAW), key_prefix: "r".into() });
let select = |id: &str, value_member: &str, label_member: &str| {
Node::Select(SelectNode {
common: common(id),
options: OptionList::Bound(BoundOptions { collection: records(), value_member: path(&[value_member]), label_member: path(&[label_member]) }),
value: bind_at(RAW, "none", vec![name("Id")], None),
on_change: command("x"),
})
};
let mut nodes_ = vec![select("opt-text", "Id", "Id")];
for member in ["Int", "Float", "Blob", "Flag"] {
nodes_.push(select(&format!("opt-value-{member}"), member, "Id"));
nodes_.push(select(&format!("opt-label-{member}"), "Id", member));
}
for (n, member) in ["Id", "Int", "Float", "Blob", "Flag"].into_iter().enumerate() {
nodes_.push(repeat_over(&format!("key-{member}"), records(), &[member], text(&format!("cell{n}"), "x")));
}
let document = with_x(page("raw-options", nodes_));
let mut rig = Rig::new(state);
rig.bind(&document);
let tree = rig.tree(&document);
let Bound::Options(options) = value(tree, "opt-text", Field::Options) else { panic!("not options") };
assert_eq!(options.len(), 2);
for member in ["Int", "Float", "Blob", "Flag"] {
assert_eq!(code(value(tree, &format!("opt-value-{member}"), Field::Options)), Code::BindTypeMismatch, "{member} as an option value");
assert_eq!(code(value(tree, &format!("opt-label-{member}"), Field::Options)), Code::BindTypeMismatch, "{member} as an option label");
}
assert_eq!(tree.instances(&nid("key-Id")).iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["a", "b"]);
assert_eq!(tree.instances(&nid("key-Int")).iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["1", "2"]);
for member in ["Float", "Blob", "Flag"] {
assert_eq!(tree.repeat_error(&nid(&format!("key-{member}"))).map(|e| e.code), Some(Code::BindTypeMismatch), "{member} as a key");
}
}
/// A port whose `list` also serves a state record of another schema than the prefix names: a port
/// fault (the contract is one lookup per record of the prefix's schema), which the Binder must
/// refuse rather than bind.
struct Odd(MemState);
impl StatePort for Odd {
fn read(&self, address: &Address) -> thing_core::port::Lookup {
self.0.read(address)
}
fn list(&self, prefix: &Prefix) -> Vec<thing_core::port::Lookup> {
let mut found = self.0.list(prefix);
found.push(thing_core::port::Lookup::Present(thing_core::port::Entry {
address: Address { provider: prefix.provider.clone(), schema: prefix.schema.clone(), key: RecordKey::new("mind-9") },
record: thing_core::port::Record::State {
schema: SchemaId::new("gamecult.thing.test.other.v1"),
value: StateValue::Record(vec![("Name".into(), StateValue::Text("Intruder".into()))]),
},
}));
found
}
fn subscribe(&mut self, interest: Interest) -> thing_core::port::SubscriptionId {
self.0.subscribe(interest)
}
fn unsubscribe(&mut self, id: thing_core::port::SubscriptionId) {
self.0.unsubscribe(id)
}
fn drain(&mut self) -> Vec<Change> {
self.0.drain()
}
}
#[test]
fn a_listed_record_of_another_schema_is_refused_in_place() {
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let mut port = Odd(swarm_state());
let tree = resolve(&document, &port, &Limits::default()).tree.unwrap();
let mut binder = Binder::new(Limits::default());
let applied = binder.bind(tree, &mut port, &mut Ledger::new());
let bound = binder.tree(&document.record_key()).unwrap();
let keys: Vec<&str> = bound.instances(&nid("minds")).iter().map(|i| i.key.as_str()).collect();
assert_eq!(keys, ["mind-1", "mind-2", "mind-3", "!mind-9"]);
assert_eq!(code(value(bound, "minds!6:mind-9/mind-name", Field::Content)), Code::BindSchemaMismatch);
assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::BindSchemaMismatch]);
}

View file

@ -204,6 +204,17 @@ impl MemState {
self.put_state_raw(address, payload, &T::schema_members());
}
/// Store an already-decoded provider-state `value` under `address`, as a port that decoded it
/// would hand it over: for the kinds a typed record cannot hold (bytes, a float where an int is
/// asked), which the tests of a reader feed through the one door.
pub fn put_value(&mut self, address: Address, value: StateValue) {
assert!(!is_contract(&address.schema), "{} is a contract kind: put", address.schema.as_str());
let slot = (address.provider.as_str().to_string(), address.key.as_str().to_string());
let schema = address.schema.clone();
self.state.insert(slot, Held::Value { schema: schema.clone(), value: value.clone() });
self.queue(Change::Upsert(Entry { address, record: Record::State { schema, value } }));
}
/// Store a provider-state payload under `address`, decoded with the schema's member `rows`.
/// A payload decode refuses makes the key refused, replacing any record it held.
pub fn put_state_raw(&mut self, address: Address, payload: Vec<u8>, rows: &[SchemaCatalogMember]) {