From b1cd0ae08f012b7ab20b0468c967a687463d2777 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 13:16:05 +0200 Subject: [PATCH] Checkpoint live registered attributes and parity fixture Preserve the in-progress registered attribute binding and its differential fixture. Library and example Clippy pass; the dedicated vanilla differential gate is still pending. --- .../examples/live_attributes_fixture.rs | 221 ++++++++++ crates/horizon-world/src/attributes/entity.rs | 8 + crates/horizon-world/src/attributes/live.rs | 398 ++++++++++++++++++ crates/horizon-world/src/attributes/mod.rs | 1 + 4 files changed, 628 insertions(+) create mode 100644 crates/horizon-world/examples/live_attributes_fixture.rs create mode 100644 crates/horizon-world/src/attributes/live.rs diff --git a/crates/horizon-world/examples/live_attributes_fixture.rs b/crates/horizon-world/examples/live_attributes_fixture.rs new file mode 100644 index 000000000..e90d8cb4f --- /dev/null +++ b/crates/horizon-world/examples/live_attributes_fixture.rs @@ -0,0 +1,221 @@ +use horizon_world::{ + attribute_map::ValueKind, + attributes::{ + Modifier, Operation, + entity::Catalog, + live::{Error, Handle, LiveAttributes}, + }, + effect_attribute_modifiers::{self as effects, Definitions, Template}, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, + sync::Arc, +}; +fn number(v: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn bits(v: f64) -> String { + format!( + "{:016x}", + if v.is_nan() { + f64::NAN.to_bits() + } else { + v.to_bits() + } + ) +} +fn error(e: Error) -> &'static str { + match e { + Error::NullAttribute | Error::MissingInstanceModifier => "null", + Error::MissingAttribute => "attribute", + Error::MissingModifier => "modifier", + Error::DuplicateModifier(_) => "duplicate", + _ => panic!("invalid fixture: {e:?}"), + } +} +fn handle(h: Option<&Handle>) -> String { + h.map_or("null".into(), |h| h.index().to_string()) +} +fn refs(mods: &[Modifier], pool: &mut Vec) -> String { + mods.iter() + .map(|m| { + let id = pool + .iter() + .position(|p| p.same_identity(m)) + .unwrap_or_else(|| { + pool.push(m.clone()); + pool.len() - 1 + }); + format!( + "{id}:{}:{}:{}", + m.id(), + bits(m.amount()), + m.operation() as u8 + ) + }) + .collect::>() + .join(",") +} +fn effect_error(e: effects::Error) -> Error { + match e { + effects::Error::World(e) => e, + _ => panic!("fixture definitions unexpectedly invalid"), + } +} +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let dir = Path::new(&args[1]); + let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( + &fs::read_to_string(dir.join("catalog.json"))?, + )?)?); + let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); + for line in fs::read_to_string(dir.join(format!("inputs-{}.txt", args[2])))?.lines() { + let f: Value = serde_json::from_str(line)?; + let hashes: Vec<_> = f["holder_hashes"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap() as i32) + .collect(); + let mut identities = f["instance_hashes"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap() as i32); + let mut attrs = LiveAttributes::new( + catalog.clone(), + f["entity"].as_str().unwrap(), + &hashes, + || identities.next().unwrap(), + ) + .unwrap(); + let mut defs = Definitions::default(); + let mut pool = Vec::new(); + for op in f["ops"].as_array().unwrap() { + let index = op["attribute"].as_i64().unwrap(); + let key = (index >= 0).then(|| attrs.keys()[index as usize].clone()); + let m = Modifier::new( + op["id"].as_str().unwrap(), + number(&op["amount"]), + Operation::ALL[op["operation"].as_u64().unwrap() as usize], + )?; + let mode = op["mode"].as_str().unwrap(); + let result: Result = match mode { + "value" => attrs.value(key, ValueKind::Computed).map(bits), + "base" => attrs.value(key, ValueKind::Base).map(bits), + "has" => attrs.has_attribute(key).map(|v| v.to_string()), + "has_modifier" => attrs.has_modifier(key, m.id()).map(|v| v.to_string()), + "modifier" => attrs.modifier_value(key, m.id()).map(bits), + "ensure" => attrs.get_instance(key).map(|h| handle(h.as_ref())), + "reset" => attrs.reset_base(key).map(|v| v.to_string()), + "ack_update" => { + let h = attrs.lookup(key.as_ref()); + attrs.updates_mut().remove(h.as_ref()); + Ok("ok".into()) + } + "ack_sync" => { + let h = attrs.lookup(key.as_ref()); + attrs.sync_mut().remove(h.as_ref()); + Ok("ok".into()) + } + "clear_updates" => { + attrs.updates_mut().clear(); + Ok("ok".into()) + } + "clear_sync" => { + attrs.sync_mut().clear(); + Ok("ok".into()) + } + "define" => { + effects::add_definition( + &mut defs, + key, + Template::new(m.id(), m.amount(), m.operation())?, + ); + Ok("ok".into()) + } + "effect-add" => attrs + .add_effect_modifiers(&mut defs, op["amplifier"].as_i64().unwrap() as i32) + .map_err(effect_error) + .map(|()| "ok".into()), + "effect-remove" => attrs + .remove_effect_modifiers(&mut defs) + .map_err(effect_error) + .map(|()| "ok".into()), + _ => match attrs.get_instance(key) { + Err(e) => Err(e), + Ok(None) => Ok("absent".into()), + Ok(Some(h)) => attrs.edit(&h, |a, o| match mode { + "set" => a + .set_base_value(number(&op["base"]), o) + .map(|()| "ok".into()), + "add" => a.add_transient(m.clone(), o).map(|()| "ok".into()), + "update" => a + .add_or_update_transient(m.clone(), o) + .map(|()| "ok".into()), + "permanent" => a.add_permanent(m.clone(), o).map(|()| "ok".into()), + "remove" => a.remove(m.id(), o).map(|v| v.to_string()), + "clear" => a.remove_all(o).map(|()| "ok".into()), + _ => panic!("mode"), + }), + }, + }; + writeln!( + out, + "result {}", + result.unwrap_or_else(|e| format!("error {}", error(e))) + )?; + writeln!( + out, + "map {}", + attrs + .entries() + .iter() + .map(|(k, h)| format!( + "{}={}", + k.as_ref().map_or("null", |k| k.name()), + handle(h.as_ref()) + )) + .collect::>() + .join(",") + )?; + writeln!( + out, + "updates {}", + attrs + .updates() + .values() + .map(handle) + .collect::>() + .join(",") + )?; + writeln!( + out, + "sync {}", + attrs + .sync() + .values() + .map(handle) + .collect::>() + .join(",") + )?; + for (h, key, a) in attrs.instances() { + writeln!( + out, + "instance {} {} {} {} {} | {} | {}", + h.index(), + key.name(), + bits(a.base_value()), + a.is_dirty(), + bits(a.cached_value()), + refs(a.modifiers(), &mut pool), + refs(a.permanent_modifiers(), &mut pool) + )?; + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/attributes/entity.rs b/crates/horizon-world/src/attributes/entity.rs index 63efca2b7..1bdf94aaf 100644 --- a/crates/horizon-world/src/attributes/entity.rs +++ b/crates/horizon-world/src/attributes/entity.rs @@ -7,6 +7,11 @@ use std::{collections::BTreeMap, convert::Infallible, io, sync::Arc}; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct AttributeId(usize); +impl AttributeId { + pub(super) fn index(self) -> usize { + self.0 + } +} #[derive(Debug)] pub struct RegisteredAttribute { pub name: String, @@ -33,6 +38,9 @@ fn number(v: &Value) -> io::Result { )) } impl Catalog { + pub(super) fn default_bases(&self, entity: &str) -> Option]>> { + self.defaults.get(entity).cloned() + } /// Imports a version-checked export of registered definitions and actual /// DefaultAttributes suppliers. Defaults contain base values, not instances. pub fn from_json(v: &Value) -> io::Result { diff --git a/crates/horizon-world/src/attributes/live.rs b/crates/horizon-world/src/attributes/live.rs new file mode 100644 index 000000000..ea661871b --- /dev/null +++ b/crates/horizon-world/src/attributes/live.rs @@ -0,0 +1,398 @@ +//! Registered entity attributes backed by live native-order maps and queues. +use super::{ + AttributeError, Instance, Modifier, Observer, + entity::{AttributeId, Catalog}, +}; +use crate::{ + attribute_map::{AttributeMap, ModifierValueError, QueryWorld, ValueKind}, + effect_attribute_modifiers::{self as effects, Definitions}, + object_open_set::{ObjectKey, ObjectOpenSet}, + stored_effect_attributes::{self as stored, AttributeAccess}, +}; +use std::{convert::Infallible, sync::Arc}; + +#[derive(Clone)] +pub struct Key { + catalog: Arc, + id: AttributeId, + hash: i32, +} +impl Key { + pub fn attribute(&self) -> AttributeId { + self.id + } + pub fn name(&self) -> &str { + &self.catalog.attribute(self.id).name + } +} +impl PartialEq for Key { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.catalog, &other.catalog) && self.id == other.id + } +} +impl Eq for Key {} +impl ObjectKey for Key { + fn object_hash(&self) -> i32 { + self.hash + } +} +#[derive(Clone)] +pub struct Handle { + owner: Arc<()>, + index: usize, + hash: i32, +} +impl Handle { + pub fn index(&self) -> usize { + self.index + } +} +impl PartialEq for Handle { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.owner, &other.owner) && self.index == other.index + } +} +impl Eq for Handle {} +impl ObjectKey for Handle { + fn object_hash(&self) -> i32 { + self.hash + } +} +#[derive(Debug)] +pub enum Error { + UnknownEntity, + InvalidHolderHashes, + NullAttribute, + MissingAttribute, + MissingModifier, + MissingInstanceModifier, + ForeignInstance, + DuplicateModifier(String), +} +struct Node { + handle: Handle, + key: Key, + value: Instance, +} +/// Observer for registered attributes. Registry syncability is immutable for +/// this binding; richer virtual attributes can use AttributeMap directly. +pub struct Dirty<'a> { + map: &'a mut AttributeMap, + handle: Handle, + syncable: bool, +} +impl Observer for Dirty<'_> { + type Error = Infallible; + fn dirty(&mut self, _: &mut Instance) -> Result<(), Infallible> { + self.map + .modified(Some(self.handle.clone()), |_, _| Ok(self.syncable)) + } +} +struct Data { + catalog: Arc, + bases: Arc<[Option]>, + keys: Vec, + owner: Arc<()>, + nodes: Vec, + next_identity: G, +} +impl i32> Data { + fn base(&self, key: &Key) -> Option { + Arc::ptr_eq(&self.catalog, &key.catalog) + .then(|| self.bases[key.id.index()]) + .flatten() + } + fn node(&self, h: &Handle) -> Result<&Node, Error> { + if !Arc::ptr_eq(&self.owner, &h.owner) { + return Err(Error::ForeignInstance); + } + self.nodes.get(h.index).ok_or(Error::ForeignInstance) + } + fn node_mut(&mut self, h: &Handle) -> Result<&mut Node, Error> { + if !Arc::ptr_eq(&self.owner, &h.owner) { + return Err(Error::ForeignInstance); + } + self.nodes.get_mut(h.index).ok_or(Error::ForeignInstance) + } + fn create( + &mut self, + map: &mut AttributeMap, + key: Option, + ) -> Result, Error> { + let Some(key) = key else { + return Ok(None); + }; + let Some(base) = self.base(&key) else { + return Ok(None); + }; + let definition = self.catalog.attribute(key.id); + let mut source = Instance::new(definition.definition); + // Registered suppliers have no modifiers. Preserve exported base bits + // rather than invoking an equality-short-circuiting setter here. + source.base = base; + let mut value = Instance::new(definition.definition); + let handle = Handle { + owner: self.owner.clone(), + index: self.nodes.len(), + hash: (self.next_identity)(), + }; + let mut observer = Dirty { + map, + handle: handle.clone(), + syncable: definition.syncable, + }; + value + .replace_from(&source, &mut observer) + .map_err(convert_error)?; + self.nodes.push(Node { + key, + handle: handle.clone(), + value, + }); + Ok(Some(handle)) + } + fn edit( + &mut self, + map: &mut AttributeMap, + handle: &Handle, + edit: impl FnOnce(&mut Instance, &mut Dirty<'_>) -> Result>, + ) -> Result { + let node = self.node_mut(handle)?; + let syncable = node.key.catalog.attribute(node.key.id).syncable; + let mut observer = Dirty { + map, + handle: handle.clone(), + syncable, + }; + edit(&mut node.value, &mut observer).map_err(convert_error) + } +} +fn convert_error(error: AttributeError) -> Error { + match error { + AttributeError::DuplicateModifier(id) => Error::DuplicateModifier(id), + AttributeError::Observer(e) => match e {}, + } +} +impl i32> QueryWorld for Data { + type Error = Error; + fn supplier_has_attribute( + &mut self, + _: &mut AttributeMap, + key: Option, + ) -> Result { + Ok(key.is_some_and(|k| self.base(&k).is_some())) + } + fn supplier_has_modifier( + &mut self, + _: &mut AttributeMap, + _: Option, + _: &str, + ) -> Result { + Ok(false) + } + fn supplier_value( + &mut self, + _: &mut AttributeMap, + key: Option, + kind: ValueKind, + ) -> Result { + let key = key.ok_or(Error::NullAttribute)?; + let base = self.base(&key).ok_or(Error::MissingAttribute)?; + Ok(match kind { + ValueKind::Base => base, + ValueKind::Computed => self.catalog.attribute(key.id).definition.sanitize(base), + }) + } + fn supplier_modifier_value( + &mut self, + _: &mut AttributeMap, + key: Option, + _: &str, + ) -> Result { + let key = key.ok_or(Error::NullAttribute)?; + self.base(&key).ok_or(Error::MissingAttribute)?; + Err(Error::MissingModifier) + } + fn instance_value( + &mut self, + _: &mut AttributeMap, + h: Handle, + kind: ValueKind, + ) -> Result { + let value = &mut self.node_mut(&h)?.value; + Ok(match kind { + ValueKind::Computed => value.value(), + ValueKind::Base => value.base_value(), + }) + } + fn instance_modifier( + &mut self, + _: &mut AttributeMap, + h: Handle, + id: &str, + ) -> Result, Error> { + Ok(self.node(&h)?.value.modifier(id).map(|m| m.amount())) + } + fn set_instance_base( + &mut self, + map: &mut AttributeMap, + h: Handle, + value: f64, + ) -> Result<(), Error> { + self.edit(map, &h, |a, o| a.set_base_value(value, o)) + } +} +impl i32> AttributeAccess for Data { + type Error = Error; + fn create_instance( + &mut self, + _: &mut Definitions, + map: &mut AttributeMap, + key: Option, + ) -> Result, Error> { + self.create(map, key) + } + fn remove_modifier( + &mut self, + _: &mut Definitions, + map: &mut AttributeMap, + h: &Handle, + id: &str, + ) -> Result<(), Error> { + self.edit(map, h, |a, o| a.remove(id, o)).map(|_| ()) + } + fn add_permanent( + &mut self, + _: &mut Definitions, + map: &mut AttributeMap, + h: &Handle, + modifier: Modifier, + ) -> Result<(), Error> { + self.edit(map, h, |a, o| a.add_permanent(modifier, o)) + } +} +/// Owns an entity's instances and pending queues. Holder hashes come from the +/// registry runtime; instance hashes come from the supplied identity allocator. +/// Supplying oracle hashes permits reproducible JVM-order differential checks. +pub struct LiveAttributes { + map: AttributeMap, + data: Data, +} +impl i32> LiveAttributes { + pub fn new( + catalog: Arc, + entity: &str, + holder_hashes: &[i32], + next_identity: G, + ) -> Result { + let bases = catalog.default_bases(entity).ok_or(Error::UnknownEntity)?; + if holder_hashes.len() != bases.len() { + return Err(Error::InvalidHolderHashes); + } + let keys = catalog + .attributes() + .map(|(id, _)| Key { + catalog: catalog.clone(), + id, + hash: holder_hashes[id.index()], + }) + .collect(); + Ok(Self { + map: AttributeMap::default(), + data: Data { + catalog, + bases, + keys, + owner: Arc::new(()), + nodes: Vec::new(), + next_identity, + }, + }) + } + pub fn catalog(&self) -> &Arc { + &self.data.catalog + } + pub fn key(&self, name: &str) -> Option { + self.data + .catalog + .id(name) + .map(|id| self.data.keys[id.index()].clone()) + } + pub fn keys(&self) -> &[Key] { + &self.data.keys + } + pub fn lookup(&self, key: Option<&Key>) -> Option { + self.map.instances.get(key) + } + pub fn get_instance(&mut self, key: Option) -> Result, Error> { + self.map + .get_instance(key, |map, key| self.data.create(map, key)) + } + pub fn has_attribute(&mut self, key: Option) -> Result { + self.map.has_attribute(key, &mut self.data) + } + pub fn has_modifier(&mut self, key: Option, id: &str) -> Result { + self.map.has_modifier(key, id, &mut self.data) + } + pub fn value(&mut self, key: Option, kind: ValueKind) -> Result { + self.map.value(key, kind, &mut self.data) + } + pub fn modifier_value(&mut self, key: Option, id: &str) -> Result { + self.map + .modifier_value(key, id, &mut self.data) + .map_err(|e| match e { + ModifierValueError::World(e) => e, + ModifierValueError::MissingInstanceModifier => Error::MissingInstanceModifier, + }) + } + pub fn reset_base(&mut self, key: Option) -> Result { + self.map.reset_base(key, &mut self.data) + } + pub fn instance(&self, handle: &Handle) -> Result<&Instance, Error> { + self.data.node(handle).map(|n| &n.value) + } + pub fn attribute(&self, handle: &Handle) -> Result<&Key, Error> { + self.data.node(handle).map(|n| &n.key) + } + pub fn instances(&self) -> impl Iterator { + self.data + .nodes + .iter() + .map(|n| (&n.handle, &n.key, &n.value)) + } + pub fn entries(&self) -> Vec<(Option, Option)> { + self.map.instances.entries() + } + pub fn updates(&self) -> &ObjectOpenSet { + &self.map.updates + } + pub fn updates_mut(&mut self) -> &mut ObjectOpenSet { + &mut self.map.updates + } + pub fn sync(&self) -> &ObjectOpenSet { + &self.map.sync + } + pub fn sync_mut(&mut self) -> &mut ObjectOpenSet { + &mut self.map.sync + } + pub fn edit( + &mut self, + handle: &Handle, + edit: impl FnOnce(&mut Instance, &mut Dirty<'_>) -> Result>, + ) -> Result { + self.data.edit(&mut self.map, handle, edit) + } + pub fn add_effect_modifiers( + &mut self, + definitions: &mut Definitions, + amplifier: i32, + ) -> Result<(), effects::Error> { + stored::add(definitions, &mut self.map, &mut self.data, amplifier) + } + pub fn remove_effect_modifiers( + &mut self, + definitions: &mut Definitions, + ) -> Result<(), effects::Error> { + stored::remove(definitions, &mut self.map, &mut self.data) + } +} diff --git a/crates/horizon-world/src/attributes/mod.rs b/crates/horizon-world/src/attributes/mod.rs index 9c3d6f20e..6778db429 100644 --- a/crates/horizon-world/src/attributes/mod.rs +++ b/crates/horizon-world/src/attributes/mod.rs @@ -2,6 +2,7 @@ use crate::compression::invalid; use std::{fmt, io, sync::Arc}; pub mod entity; +pub mod live; mod operation_map; use operation_map::OperationMap; #[derive(Clone, Copy, Debug, PartialEq, Eq)]