Skip to content

Entities Design Notes

Robert Jacobson edited this page Nov 21, 2025 · 13 revisions

Notes about Entity Implementation

ToDo

A few chores have been kicked down the street.

  • Add Property<E: Entity>::hash_value() in preparation for indexes
  • Make a decision either way about unsafe in entity::entity_store::get_entity_metadata_static.
  • Add Property<E: Entity>::type_id() in preparation for indexes
  • define_derived_property! Macro rough edges:

Integration with Context

API on Context

Should add_entity<E: Entity> return a Result<EntityId<E>, IxaError>? Right now it fails only if InitializationList is invalid.

pub fn add_entity<E: Entity, PL: PropertyList<E>>(&mut self, property_list: PL) -> Result<EntityId<E>, IxaError>;
  • Makes sense to return a Result if we let user add an entity, say, at debug console or via web API.
  • Makes sense to just panic if we only care about calling the method from client code directly.

Should EntityStore / PropertyStore be fields of Context?

Arguments for making the EntityStore and PropertyStore fields of Context:

  • Not every subsystem cares about entities/properties, but a lot of them do. (PluginContext defines the minimal interface all DataPlugins can assume exists. Half of the trait extension constraints in PluginContext are related to PeopleContext.)
  • Accesses to these stores are often in the hottest paths / tightest loops, which recommends minimizing indirection (one fewer pointer dereference)

Arguments against making the EntityStore and PropertyStore fields of Context:

  • Historically the only intrinsic properties and functions of the concrete Context type is managing the timeline (events and plans). All other functionality is (was) provided by plugins. Adding entities (EntityStore and PropertyStore) to Context expands its responsibilities from "events that happen in time" to also include "state of the world". Philosophically, one could argue this violates the "separation of concerns" / "single responsibility" principle. (Counterargument: A good software engineer is not constrained by rules of thumb.)
  • Is the indirection required for accessing a DataPlugin even measurable?

ValueVec

Options for !Drop

std::mem::ManuallyDrop<T>

A wrapper to inhibit the compiler from automatically calling T’s destructor. This wrapper is 0-cost.

Compiler error on std::mem::needs_drop::<V>()

We can prevent construction of ValueVecs for values with destructors by using the needs_drop function:

impl<V> ValueVec<V> {
    pub fn new() -> Self {
        // Panics if `V` has a destructor.
        assert!(!needs_drop::<V>(), "Type must not have a destructor");
        
        ValueVec {
            values: Vec::new(),
        }
    }
}

Homework assignments

  • Can we further constrain V to be !Drop (and/or !Clone) ?
  • Where is the compiler inserting Drop? Can we only implement mutating primitives such that Drop is not called? (If we never "delete" something. Is Drop called when overwritten?)
  • If we provide a trivial implementation of Drop for all Property types, does that solve the problem? (Could there be a hidden Drop impl called somehow by virtue of what the type is?)

Types

struct EntityId<E: Entity>(usize, PhantomData<E>)

  • The entity ID should know the Entity type so that a PersonId can't be used as a SettingId.
  • The original PersonId type is opaque–it cannot be created or destructured outside of the ixa crate. To achieve the same thing, we do this: EntityId<E: Entity>(usize, PhantomData<E>)
  • Entity cannot store the entity count, because we don't want client code to be able to create a new entity (or modify the entity count), and the Entity types are implemented in client code. So we store the entity count in the EntityStore.

EntityCreatedEvent?

This is suspicious:

/// Emitted when a new person is created
/// These should not be emitted outside this module
#[derive(Clone, Copy, IxaEvent)]
#[allow(clippy::manual_non_exhaustive)]
pub struct PersonCreatedEvent {
  /// The [`PersonId`] of the new person.
  pub person_id: PersonId,
}

What does "should not be emitted outside this module" mean? Does this mean that add_person is the only thing that emits the event?

The code adding the entity (person) already gets the new PersonId, so this is for nonlocal code execution on entity creation.

Properties

Required versus Explicit

Originally it appears we assumed that it is not possible to have a non-required property without a default value. (I think we just let an internal unwrap fail.) Should we enforce this in the macro implementations? (Related to the next section as well.)

Right now we store: Vec<Option<Property>>

But maybe we should only store: Vec<Property>

If the value is allowed to be not set, it should be an Option<Property>. The difference is, do we enforce this at the API level, or do we make client code deal with it?

Semantics of Property Change

  • If you try to set a property to the value it already has, is a property change event emitted? (Previously, yes.)
  • If you try to set an unset property to its default value, is a property change event emitted? (Previously, yes.)

See PropertyValueStore::replace().

Also: Previously, it appears we assumed that it is not possible to have a non-required property without a default value. Now we do allow this. Thus, PropertyChangeEvent::previous is now an option.

General Stuff

Internal checks

There are several places in ixa internals where we have checks for things that should never happen unless there's a bug in ixa itself. These checks could be conditionally removed depending on the build profile:

#[inline(always)]
fn expect_debug_only<T>(opt: Option<T>, msg: &str) -> T {
    if cfg!(debug_assertions) {
        opt.expect(msg)
    } else {
        unsafe { opt.unwrap_unchecked() }
    }
}

// or the plain vanilla inline version:
let value = if cfg!(debug_assertions) {
  property_store
          .get(entity_id)
          .expect("getting a property value with \"constant\" initialization should never fail")
} else {
  unsafe { property_store.get(entity_id).unwrap_unchecked() }
};

The actual performance impact of this is probably negligible. It might be worth running some experiments to see if it's worth it.

define_rng! macro

We have this "rng_name_duplication_guard_" thing that I don't understand. Some research shows it was a pre-Rust 2018 hack to prevent global singletons with the same name.

  • It doesn't work anymore (maybe?).
  • Why not have RNGs with the same name?
  • The macro makes the RNG private, so it's not accessible outside of the module anyway.

Alternatives (that I am also suspicious of):

  1. Just remove it. We trust client code to know how to refer to the correct symbol in other places.
  2. "private trait" trick:
$crate::paste::paste! {
    trait [<__rng_guard_ $random_id>] {}
    impl [<__rng_guard_ $random_id>] for () {}
}
  1. unique const generic:
struct __RngNameDupGuard<const NAME: &'static str>;
type _ = __RngNameDupGuard<{ stringify!($random_id) }>;

Visibility of Synthesized types

We synthesize these types with macros without a pub visibility (or any other visibility).

  • DataPlugin
  • RNGs
  • Entity
  • Property<E: Entity>

Clone this wiki locally