From 15ddd079e6cae75fe7dc3905532631a2769233b5 Mon Sep 17 00:00:00 2001 From: Kelly Kinkade Date: Fri, 4 Dec 2026 10:39:35 -0600 Subject: [PATCH 1/3] performance enhancements in lua object pushes These modifications provide a roughly 30% performance increase in bulk pushes of metadata objects into Lua tables by memoizing the last virtual table lookup and by leveraging the bidirectionality of the registry index to avoid doing repeated lookups for the same type identity --- docs/changelog.txt | 1 + library/DataDefs.cpp | 46 ++++++++++++++++++++++++++++++++++++------ library/LuaWrapper.cpp | 23 +++++++++++++++++---- 3 files changed, 60 insertions(+), 10 deletions(-) diff --git a/docs/changelog.txt b/docs/changelog.txt index 99a82c7352..70b3b6afe7 100644 --- a/docs/changelog.txt +++ b/docs/changelog.txt @@ -63,6 +63,7 @@ Template for new versions: ## Misc Improvements - Core: docs files generated by previous builds are now cleaned up automatically, so switching branches no longer breaks the build with missing-file errors +- Core: performance tweaks in Lua identity handling: memoize last virtual identity lookup to provide a fast path for homogeneous loads; leverage the registry index's bidirectionality to speed metatable discovery - `tailor`: clothing needs are now computed from each unit's body plan instead of a fixed armor/pants/shoes list: dwarves get two shoes, units with any number of stance parts get appropriately many pairs of shoes, and helmets, gloves, and unusually-shaped citizens are covered too. Clothing types are chosen to maximize body coverage using their UBSTEP/LBSTEP/UPSTEP reach - `tailor`: pending manager orders now count toward clothing needs, so repeating ``tailor now`` no longer creates additional orders in other materials for needs that are already covered by an outstanding order diff --git a/library/DataDefs.cpp b/library/DataDefs.cpp index ce11f174ed..b450597364 100644 --- a/library/DataDefs.cpp +++ b/library/DataDefs.cpp @@ -28,6 +28,8 @@ distribution. #include #include #include +#include +#include #include "MemAccess.h" #include "Core.h" @@ -148,6 +150,11 @@ bool compound_identity::is_equivalent(const compound_identity* other) const static std::mutex *known_mutex = NULL; +// Bumped whenever an entry is removed from virtual_identity::known, so +// that the per-thread memo in virtual_identity::find(void*) below can't +// hand out a stale identity pointer. +static std::atomic known_erase_generation{0}; + void compound_identity::Init(Core *core) { if (!known_mutex) @@ -314,13 +321,16 @@ decltype(virtual_identity::interpose_list_map) virtual_identity::interpose_list_ void virtual_identity::ensure_virtual_identity_init() { - static std::once_flag virtual_identity_init_flag; - std::call_once(virtual_identity_init_flag, []() { + // Magic static: on the steady-state path this is just a guard check, + // cheaper than std::call_once on this hot path. + static bool initialized = []() { name_lookup = new (std::remove_pointer::type)(); known = new (std::remove_pointer::type)(); vtable_ptr_map = new (std::remove_pointer::type)(); interpose_list_map = new (std::remove_pointer::type)(); - }); + return true; + }(); + (void)initialized; } virtual_identity::virtual_identity(size_t size, const TAllocateFn alloc, @@ -350,10 +360,16 @@ virtual_identity::~virtual_identity() // Remove global lookup table entries if we're from a plugin if (is_plugin) { - (*name_lookup).erase(getOriginalName()); + if (known_mutex) + { + std::lock_guard lock(*known_mutex); + (*name_lookup).erase(getOriginalName()); + + if (vtable_ptr()) + (*known).erase(vtable_ptr()); + } - if (vtable_ptr()) - (*known).erase(vtable_ptr()); + known_erase_generation.fetch_add(1, std::memory_order_relaxed); } } @@ -391,6 +407,21 @@ const virtual_identity *virtual_identity::find(void *vtable) if (!vtable || !known_mutex) return nullptr; + // Bulk materialization (e.g. vectors of homogeneous df objects) + // repeats the same vtable lookup; memoize the last hit per thread + // and skip the map lock entirely. `known` is only appended to after + // init except that plugin identities are removed by the destructor + // above, so the memo is validated by a generation counter. + static thread_local struct { + void *vtable; + const virtual_identity *identity; + uint64_t generation; + } last_hit = { nullptr, nullptr, 0 }; + + uint64_t gen = known_erase_generation.load(std::memory_order_relaxed); + if (vtable == last_hit.vtable && gen == last_hit.generation) + return last_hit.identity; + ensure_virtual_identity_init(); // Actually, a reader/writer lock would be sufficient, @@ -399,7 +430,10 @@ const virtual_identity *virtual_identity::find(void *vtable) auto it = (*known).find(vtable); if (it != (*known).end()) + { + last_hit = { vtable, it->second, gen }; return it->second; + } // If using a reader/writer lock, re-grab as write here, and recheck Core &core = Core::getInstance(); diff --git a/library/LuaWrapper.cpp b/library/LuaWrapper.cpp index 0d30429297..9dff299e3e 100644 --- a/library/LuaWrapper.cpp +++ b/library/LuaWrapper.cpp @@ -234,13 +234,28 @@ void LuaWrapper::push_object_internal(lua_State *state, const type_identity *typ } /* - * Resolve metatable by identity, and push the object + * Resolve metatable by identity, and push the object. + * + * Fast path: identity -> metatable mappings are mirrored directly + * in the registry under the identity pointer, so a single rawgetp + * suffices for types that have been pushed before (this is the + * common case for e.g. bulk vector materialization). */ - lua_pushlightuserdata(state, const_cast(type)); // () -> type + lua_rawgetp(state, LUA_REGISTRYINDEX, type); + if (lua_isnil(state, -1)) + { + lua_pop(state, 1); + + lua_pushlightuserdata(state, const_cast(type)); // () -> type - if (!LookupTypeInfo(state, in_method)) // type -> metatable? - BuildTypeMetatable(state, type); // () -> metatable + if (!LookupTypeInfo(state, in_method)) // type -> metatable? + BuildTypeMetatable(state, type); // () -> metatable + + lua_pushlightuserdata(state, const_cast(type)); + lua_pushvalue(state, -2); + lua_rawset(state, LUA_REGISTRYINDEX); // registry[type] = metatable + } push_object_ref(state, ptr); // metatable -> userdata } From 7b47bad681790717b4371aab4874f83c8462a0fc Mon Sep 17 00:00:00 2001 From: Kelly Kinkade Date: Fri, 4 Dec 2026 16:33:30 -0600 Subject: [PATCH 2/3] add metadata lookup caching these changes enable metadata lookup caching and reuse, which provides further performance improvements for common bulk object operations - `getContainedItems` can see as much as a 50% improvement in performance --- docs/changelog.txt | 2 +- library/LuaTypes.cpp | 24 +++- library/LuaWrapper.cpp | 170 ++++++++++++++++++++++- library/include/LuaTools.h | 10 ++ library/include/LuaWrapper.h | 13 +- test/library/items_fortress.lua | 109 +++++++++++++++ test/structures/object_refs.lua | 71 ++++++++++ test/structures/object_refs_fortress.lua | 98 +++++++++++++ 8 files changed, 489 insertions(+), 8 deletions(-) create mode 100644 test/library/items_fortress.lua create mode 100644 test/structures/object_refs.lua create mode 100644 test/structures/object_refs_fortress.lua diff --git a/docs/changelog.txt b/docs/changelog.txt index 70b3b6afe7..1827cc7305 100644 --- a/docs/changelog.txt +++ b/docs/changelog.txt @@ -63,7 +63,7 @@ Template for new versions: ## Misc Improvements - Core: docs files generated by previous builds are now cleaned up automatically, so switching branches no longer breaks the build with missing-file errors -- Core: performance tweaks in Lua identity handling: memoize last virtual identity lookup to provide a fast path for homogeneous loads; leverage the registry index's bidirectionality to speed metatable discovery +- Core: performance tweaks in Lua identity handling: memoize last virtual identity lookup to provide a fast path for homogeneous loads; leverage the registry index's bidirectionality to speed metatable discovery; add a cache for identity to metatable lookups to enable userdata reuse - `tailor`: clothing needs are now computed from each unit's body plan instead of a fixed armor/pants/shoes list: dwarves get two shoes, units with any number of stance parts get appropriately many pairs of shoes, and helmets, gloves, and unusually-shaped citizens are covered too. Clothing types are chosen to maximize body coverage using their UBSTEP/LBSTEP/UPSTEP reach - `tailor`: pending manager orders now count toward clothing needs, so repeating ``tailor now`` no longer creates additional orders in other materials for needs that are already covered by an outstanding order diff --git a/library/LuaTypes.cpp b/library/LuaTypes.cpp index 45d1f8e8e3..8e5c24846b 100644 --- a/library/LuaTypes.cpp +++ b/library/LuaTypes.cpp @@ -479,7 +479,9 @@ static void field_reference(lua_State *state, const struct_field_info *field, vo { case struct_field_info::PRIMITIVE: case struct_field_info::SUBSTRUCT: - push_object_internal(state, field->type, ptr); + // Field refs are mutated below, so they must not come from + // the shared ref cache. + push_object_internal(state, field->type, ptr, true, false); get_object_ref_header(state, -1)->field_info = field; return; @@ -565,6 +567,14 @@ static int meta_struct_index(lua_State *state) auto struct_type = (struct_identity*)get_object_identity(state, 1, "read", false); if (auto tag_field = find_union_tag(struct_type, field)) { + // The produced ref may be shared via the ref cache; union + // tag data is stored per-ref, so substitute a private copy + // before tagging it. + if (lua_isuserdata(state, -1) && lua_getmetatable(state, -1)) + { + push_object_ref(state, get_object_ref(state, -2)); + lua_replace(state, -2); + } get_object_ref_header(state, -1)->tag_ptr = ptr + tag_field->offset; get_object_ref_header(state, -1)->tag_identity = tag_field->type; get_object_ref_header(state, -1)->tag_attr = field->extra ? field->extra->union_tag_attr : nullptr; @@ -857,7 +867,17 @@ static void attach_container_item_tagged_union(lua_State *state, int container, auto tag_container = (container_identity*)header->tag_identity; - auto ref = get_object_ref_header(state, item); + // The element ref may be shared via the ref cache; union tags + // are stored per-ref, so substitute a private copy before + // tagging it. + int aitem = lua_absindex(state, item); + if (lua_isuserdata(state, aitem) && lua_getmetatable(state, aitem)) + { + push_object_ref(state, get_object_ref(state, aitem)); + lua_replace(state, aitem); + } + + auto ref = get_object_ref_header(state, aitem); // on both msvc and gcc, vectors have the same memory layout auto item_type = tag_container->getItemType(); diff --git a/library/LuaWrapper.cpp b/library/LuaWrapper.cpp index 9dff299e3e..5eb63a6347 100644 --- a/library/LuaWrapper.cpp +++ b/library/LuaWrapper.cpp @@ -169,6 +169,14 @@ void LuaWrapper::SaveTypeInfo(lua_State *state, void *node) static void BuildTypeMetatable(lua_State *state, const type_identity *type); +/* + * Address of this object is used as a unique key: metatable[key] holds + * the ref cache for the type, a weak-valued table mapping object + * pointer -> canonical ref userdata. Using a lightuserdata field keeps + * the cache invisible to table enumeration. + */ +static char refcache_field_key; + /** * Push the pointer as DF object ref using metatable on the stack. */ @@ -203,10 +211,28 @@ void *LuaWrapper::get_object_ref(lua_State *state, int val_index) return get_object_ref_header(state, val_index)->ptr; } -/** - * Push the pointer using given identity. +/* + * Expects a type metatable on the stack top; pushes its ref cache + * table, creating it on first use. Result: [meta, cache]. */ -void LuaWrapper::push_object_internal(lua_State *state, const type_identity *type, void *ptr, bool in_method) +static void push_ref_cache(lua_State *state) +{ + lua_rawgetp(state, -1, &refcache_field_key); // -> cache + if (lua_istable(state, -1)) + return; + + lua_pop(state, 1); // [meta] + + lua_createtable(state, 0, 0); // [meta, cache] + lua_createtable(state, 0, 1); // [meta, cache, weakmeta] + lua_pushliteral(state, "v"); + lua_setfield(state, -2, "__mode"); + lua_setmetatable(state, -2); // [meta, cache] + lua_pushvalue(state, -1); + lua_rawsetp(state, -3, &refcache_field_key); // [meta, cache] +} + +void LuaWrapper::push_object_internal(lua_State *state, const type_identity *type, void *ptr, bool in_method, bool cacheable) { /* * If NULL pointer or no type, push something simple @@ -257,7 +283,143 @@ void LuaWrapper::push_object_internal(lua_State *state, const type_identity *typ lua_rawset(state, LUA_REGISTRYINDEX); // registry[type] = metatable } - push_object_ref(state, ptr); // metatable -> userdata + // stack: [metatable] + + if (!cacheable) + { + push_object_ref(state, ptr); // metatable -> userdata + return; + } + + /* + * Probe the metatable's ref cache for a canonical ref for this + * pointer. Cached refs are shared: field refs and union-tagged + * refs carry per-reference metadata in their DFRefHeader, so code + * paths that write those fields must either pass cacheable=false + * above or substitute a private ref before mutating. + */ + push_ref_cache(state); // [meta, cache] + + lua_pushlightuserdata(state, ptr); + lua_rawget(state, -2); // [meta, cache, ref|nil] + + if (lua_isuserdata(state, -1)) + { + lua_remove(state, -2); // [meta, ref] + lua_remove(state, -2); // [ref] + return; + } + + lua_pop(state, 1); // [meta, cache] + + // Create the ref and publish it. + lua_swap(state); // [cache, meta] + push_object_ref(state, ptr); // [cache, ref] + lua_pushlightuserdata(state, ptr); // [cache, ref, ptr] + lua_pushvalue(state, -2); // [cache, ref, ptr, ref] + lua_rawset(state, -4); // cache[ptr] = ref -> [cache, ref] + lua_remove(state, -2); // [ref] +} + +/** + * Metatable lookup shared by the vector push slow path. + */ +static void push_metatable_for(lua_State *state, const type_identity *type) +{ + lua_rawgetp(state, LUA_REGISTRYINDEX, type); + if (lua_isnil(state, -1)) + { + lua_pop(state, 1); + + lua_pushlightuserdata(state, const_cast(type)); + + if (!LookupTypeInfo(state, false)) // type -> metatable? + BuildTypeMetatable(state, type); // () -> metatable + + lua_pushlightuserdata(state, const_cast(type)); + lua_pushvalue(state, -2); + lua_rawset(state, LUA_REGISTRYINDEX); // registry[type] = metatable + } +} + +void LuaWrapper::push_object_vector(lua_State *state, const type_identity *type, void *const *items, size_t count, bool addn) +{ + lua_createtable(state, (int)count, addn ? 1 : 0); + if (addn) + { + lua_pushinteger(state, (lua_Integer)count); + lua_setfield(state, -2, "n"); + } + + int result = lua_gettop(state); + + // Pinned slots for the current identity's metatable and ref cache, + // refreshed whenever the resolved element identity changes. + lua_pushnil(state); // result+1: metatable + lua_pushnil(state); // result+2: ref cache + int meta_slot = result + 1, cache_slot = result + 2; + + const type_identity *cur = NULL; + bool is_class = type && type->type() == IDTYPE_CLASS; + + for (size_t i = 0; i < count; i++) + { + void *ptr = items[i]; + if (!ptr) + { + lua_pushnil(state); + lua_rawseti(state, result, (lua_Integer)(i + 1)); + continue; + } + + const type_identity *id = type; + if (is_class) + { + if (const virtual_identity *vid = virtual_identity::get(virtual_ptr(ptr))) + id = vid; + } + + if (!id) + { + lua_pushlightuserdata(state, ptr); + lua_rawseti(state, result, (lua_Integer)(i + 1)); + continue; + } + + if (id != cur) + { + cur = id; + + push_metatable_for(state, id); + lua_replace(state, meta_slot); + + lua_pushvalue(state, meta_slot); + push_ref_cache(state); // [meta, cache] + lua_replace(state, cache_slot); // pin cache -> [meta] + lua_pop(state, 1); + } + + lua_pushlightuserdata(state, ptr); + lua_rawget(state, cache_slot); // -> ref|nil + + if (lua_isuserdata(state, -1)) + { + lua_rawseti(state, result, (lua_Integer)(i + 1)); + continue; + } + + lua_pop(state, 1); + + // Create the ref and publish it. + lua_pushvalue(state, meta_slot); + push_object_ref(state, ptr); // [ref] + lua_pushlightuserdata(state, ptr); + lua_pushvalue(state, -2); + lua_rawset(state, cache_slot); // cache[ptr] = ref -> [ref] + lua_rawseti(state, result, (lua_Integer)(i + 1)); + } + + lua_pop(state, 2); // pinned slots } static void fetch_container_details(lua_State *state, int meta, const type_identity **pitem, int *pcount) diff --git a/library/include/LuaTools.h b/library/include/LuaTools.h index f929c562f3..5c324e612d 100644 --- a/library/include/LuaTools.h +++ b/library/include/LuaTools.h @@ -39,6 +39,7 @@ distribution. #include "ColorText.h" #include "DataDefs.h" #include "DataIdentity.h" +#include "LuaWrapper.h" #include "df/coord.h" #include "df/coord2d.h" @@ -421,6 +422,15 @@ namespace DFHack::Lua { } } + // Fast path for vectors of df objects: hoists identity/metatable/ref-cache + // lookups out of the element loop (see LuaWrapper::push_object_vector). + template + void PushVector(lua_State *state, const std::vector &pvec, bool addn = false) + { + LuaWrapper::push_object_vector(state, df::identity_traits::get(), + reinterpret_cast(pvec.data()), pvec.size(), addn); + } + template void Push(lua_State *state, const std::vector &vec) { PushVector(state, vec); diff --git a/library/include/LuaWrapper.h b/library/include/LuaWrapper.h index 9c9c3d6ee7..50b30b2d10 100644 --- a/library/include/LuaWrapper.h +++ b/library/include/LuaWrapper.h @@ -143,8 +143,19 @@ namespace LuaWrapper { /* * If is_method is true, these use UPVAL_TYPETABLE to save a hash lookup. + * If cacheable is true (the default), the pushed ref may be a shared + * canonical ref for (ptr, identity) held in a weak cache; callers + * that write per-ref metadata (field_info/tag_*) into the returned + * header must pass cacheable=false or substitute a private ref. */ - void push_object_internal(lua_State *state, const type_identity *type, void *ptr, bool in_method = true); + void push_object_internal(lua_State *state, const type_identity *type, void *ptr, bool in_method = true, bool cacheable = true); + + /* + * Vectorized form of push_object_internal: materializes a run of + * same-declared-type object pointers as a fresh Lua array, reusing + * the per-identity ref cache described above. + */ + void push_object_vector(lua_State *state, const type_identity *type, void *const *items, size_t count, bool addn = false); DFHACK_EXPORT void *get_object_internal(lua_State *state, const type_identity *type, int val_index, bool exact_type, bool in_method = true); void push_adhoc_pointer(lua_State *state, void *ptr, const type_identity *target); diff --git a/test/library/items_fortress.lua b/test/library/items_fortress.lua new file mode 100644 index 0000000000..2a26fc21b3 --- /dev/null +++ b/test/library/items_fortress.lua @@ -0,0 +1,109 @@ +config.mode = 'fortress' +config.target = 'core' + +-- Dreamfort baselines (see devel/items-call-cost.lua for perf measurements) +local BARREL_ID = 695 -- item_barrelst +local BARREL_CHILD_IDS = {32088, 32126, 32178, 34230} -- all item_foodst +local BAG_ID = 679 -- item_bagst +local BAG_CHILD_IDS = {35257, 35352} -- item_seedsst +local PLANTS_BARREL_ID = 701 -- item_barrelst +local PLANTS_BARREL_CHILD_COUNT = 11 -- all item_plantst +local BIG_BAG_ID = 13733 -- item_bagst +local BIG_BAG_CHILD_COUNT = 80 -- item_seedsst + +function test.getContainedItems_empty() + local non_container = df.item.find(BARREL_CHILD_IDS[1]) + expect.table_eq(dfhack.items.getContainedItems(non_container), {}) +end + +function test.getContainedItems_baseline() + local barrel = df.item.find(BARREL_ID) + expect.eq(barrel._type, df.item_barrelst) + local children = dfhack.items.getContainedItems(barrel) + expect.eq(#children, #BARREL_CHILD_IDS) + for i, id in ipairs(BARREL_CHILD_IDS) do + expect.eq(children[i].id, id, ('child %d'):format(i)) + expect.eq(children[i]._type, df.item_foodst, ('child %d'):format(i)) + end +end + +function test.getContainedItems_bag_baseline() + local children = dfhack.items.getContainedItems(df.item.find(BAG_ID)) + expect.eq(#children, #BAG_CHILD_IDS) + for i, id in ipairs(BAG_CHILD_IDS) do + expect.eq(children[i].id, id, ('child %d'):format(i)) + expect.eq(children[i]._type, df.item_seedsst, ('child %d'):format(i)) + end +end + +function test.getContainedItems_sizes() + local cases = { + {PLANTS_BARREL_ID, PLANTS_BARREL_CHILD_COUNT, df.item_plantst}, + {BIG_BAG_ID, BIG_BAG_CHILD_COUNT, df.item_seedsst}, + } + for _, case in ipairs(cases) do + local children = dfhack.items.getContainedItems(df.item.find(case[1])) + expect.eq(#children, case[2], ('container %d'):format(case[1])) + for i, child in ipairs(children) do + expect.eq(child._type, case[3], + ('container %d child %d'):format(case[1], i)) + end + end +end + +-- Returned element refs are canonical: identical across calls and equal to +-- df.item.find() lookups. +function test.getContainedItems_ref_identity() + local a = dfhack.items.getContainedItems(df.item.find(BARREL_ID)) + local b = dfhack.items.getContainedItems(df.item.find(BARREL_ID)) + expect.eq(#a, #b) + for i = 1, #a do + expect.true_(rawequal(a[i], b[i]), ('child %d'):format(i)) + expect.true_(rawequal(a[i], df.item.find(a[i].id)), ('child %d'):format(i)) + end +end + +-- getGeneralRef returns the child-side contained_in_item ref; the container's +-- own general_refs elements are the container-side contains_item direction. +function test.getGeneralRef() + local r = dfhack.items.getGeneralRef(df.item.find(BARREL_CHILD_IDS[1]), + df.general_ref_type.CONTAINED_IN_ITEM) + expect.eq(r._type, df.general_ref_contained_in_itemst) + expect.eq(r.item_id, BARREL_ID) +end + +function test.getGeneralRef_identity() + local child = df.item.find(BARREL_CHILD_IDS[1]) + local a = dfhack.items.getGeneralRef(child, df.general_ref_type.CONTAINED_IN_ITEM) + local b = dfhack.items.getGeneralRef(child, df.general_ref_type.CONTAINED_IN_ITEM) + expect.true_(rawequal(a, b)) +end + +function test.general_refs_baseline() + local barrel = df.item.find(BARREL_ID) + expect.eq(#barrel.general_refs, #BARREL_CHILD_IDS) + for i = 0, #BARREL_CHILD_IDS - 1 do + local r = barrel.general_refs[i] + expect.eq(r._type, df.general_ref_contains_itemst, ('ref %d'):format(i)) + expect.eq(r.item_id, BARREL_CHILD_IDS[i + 1], ('ref %d'):format(i)) + end +end + +function test.general_refs_identity() + local barrel = df.item.find(BARREL_ID) + expect.true_(rawequal(barrel.general_refs[0], barrel.general_refs[0])) +end + +-- The child-side ref and the container-side ref are different objects and +-- must NOT collapse into one canonical ref. +function test.different_refs_not_identical() + local child_ref = dfhack.items.getGeneralRef( + df.item.find(BARREL_CHILD_IDS[1]), df.general_ref_type.CONTAINED_IN_ITEM) + local container_ref = df.item.find(BARREL_ID).general_refs[0] + expect.false_(rawequal(child_ref, container_ref)) +end + +function test.item_find_bogus() + expect.nil_(df.item.find(-1)) + expect.nil_(df.item.find(99999999)) +end diff --git a/test/structures/object_refs.lua b/test/structures/object_refs.lua new file mode 100644 index 0000000000..7e7d10d165 --- /dev/null +++ b/test/structures/object_refs.lua @@ -0,0 +1,71 @@ +config.target = 'core' + +local utils = require('utils') + +-- Object refs to the same underlying pointer and type are canonical: +-- repeated pushes return the identical Lua userdata, so they can be used +-- reliably as table keys and compared with rawequal(). +function test.global_ref_identity() + local a = df.global.gps + local b = df.global.gps + expect.eq(a, b) + expect.true_(rawequal(a, b)) +end + +function test.global_ref_table_key() + local t = {[df.global.gps] = 'marker'} + expect.eq(t[df.global.gps], 'marker') +end + +function test.global_ref_distinct() + expect.ne(df.global.gps, df.global.enabler) + expect.false_(rawequal(df.global.gps, df.global.enabler)) +end + +-- _field() refs carry private field metadata in their header, so they are +-- deliberately NOT shared: each call returns a fresh ref aliasing the same +-- memory. +function test.field_refs_are_private() + local a = df.global:_field('gps') + local b = df.global:_field('gps') + -- __eq compares the pointed-to field, so the refs compare equal + expect.eq(a, b) + -- but each call still returns distinct userdata (the refs are private) + expect.false_(rawequal(a, b)) + expect.eq(utils.addressof(a), utils.addressof(b)) +end + +function test.field_refs_different_fields() + expect.ne(utils.addressof(df.global:_field('gps')), + utils.addressof(df.global:_field('enabler'))) +end + +-- Reading a union-typed field produces a private ref that carries the active +-- tag; repeated reads are distinct userdata aliasing the same memory. +function test.tagged_union_field_refs_are_private() + dfhack.with_temp_object(df.unit_action:new(), function(action) + action.type = df.unit_action_type.SuckBlood + local a, b = action.data, action.data + expect.false_(rawequal(a, b)) + expect.eq(utils.addressof(a), utils.addressof(b)) + end) +end + +-- Union member reads produce ordinary shared refs; members carry no tag +-- state of their own. +function test.union_member_refs_are_shared() + dfhack.with_temp_object(df.unit_action:new(), function(action) + action.type = df.unit_action_type.SuckBlood + local a = action.data.suckblood + local b = action.data.suckblood + expect.true_(rawequal(a, b)) + expect.eq(utils.addressof(a), utils.addressof(b)) + end) +end + +-- Shared refs must remain valid and canonical across garbage collection. +function test.ref_identity_across_gc() + local a = df.global.gps + collectgarbage('collect') + expect.true_(rawequal(a, df.global.gps)) +end diff --git a/test/structures/object_refs_fortress.lua b/test/structures/object_refs_fortress.lua new file mode 100644 index 0000000000..5eea2abd74 --- /dev/null +++ b/test/structures/object_refs_fortress.lua @@ -0,0 +1,98 @@ +config.mode = 'fortress' +config.target = 'core' + +local utils = require('utils') + +-- Element refs from container access, static find() lookups, and repeated +-- pushes all resolve to the same canonical ref for a given (pointer, type). +function test.item_identity() + local items = df.global.world.items.all + expect.gt(#items, 0) + local a, b = items[0], items[0] + expect.true_(rawequal(a, b)) + expect.eq(a, b) + expect.true_(rawequal(a, df.item.find(a.id))) +end + +function test.item_table_key() + local it = df.global.world.items.all[0] + local t = {[it] = 'marker'} + expect.eq(t[df.global.world.items.all[0]], 'marker') + expect.eq(t[df.item.find(it.id)], 'marker') +end + +function test.item_distinct() + local items = df.global.world.items.all + expect.gt(#items, 1) + expect.false_(rawequal(items[0], items[1])) + expect.ne(items[0], items[1]) +end + +-- Every element of the polymorphic items.all vector resolves to its concrete +-- subclass via vtable -> virtual_identity resolution. +function test.item_concrete_types() + local items = df.global.world.items.all + for i = 0, #items - 1, 500 do + local it = items[i] + expect.ne(it._type, df.item, + ('items.all[%d] did not resolve a concrete type'):format(i)) + expect.true_(df.item:is_instance(it), + ('items.all[%d] not an item instance'):format(i)) + end +end + +-- Element refs stay canonical across separate container accesses. +function test.item_vector_canonicalization() + local items1 = df.global.world.items.all + local items2 = df.global.world.items.all + expect.true_(rawequal(items1[0], items2[0])) +end + +-- unit.actions elements are plain struct refs and are shared; the tagged +-- union .data field read is a private ref carrying the active tag. +function test.unit_action_refs() + local unit + for _, u in ipairs(df.global.world.units.active) do + if #u.actions > 0 then + unit = u + break + end + end + expect.ne(unit, nil, 'no unit with actions found') + if not unit then return end + + local a1, a2 = unit.actions[0], unit.actions[0] + expect.true_(rawequal(a1, a2)) + expect.eq(utils.addressof(a1), utils.addressof(a2)) + expect.eq(a1.type, a2.type) + + local d1, d2 = a1.data, a1.data + expect.false_(rawequal(d1, d2)) + expect.eq(utils.addressof(d1), utils.addressof(d2)) + + -- The active union member still tracks .type. + local name = df.unit_action_type[a1.type] + if name then + local tag = df.unit_action_type.attrs[name].tag + if tag then + expect.pairs_contains(a1.data, tag) + end + end +end + +-- _field() refs on real objects stay private per call. +function test.field_refs_are_private() + local it = df.global.world.items.all[0] + local a, b = it:_field('id'), it:_field('id') + expect.false_(rawequal(a, b)) + expect.eq(utils.addressof(a), utils.addressof(b)) + expect.eq(a.value, b.value) +end + +-- Shared refs must remain valid and canonical across garbage collection. +function test.ref_identity_across_gc() + local a = df.global.world.items.all[0] + collectgarbage('collect') + expect.true_(rawequal(a, df.global.world.items.all[0])) + expect.true_(rawequal(a, df.item.find(a.id))) +end From f5cd996b59096b522878a3ddea91a838ba8163f4 Mon Sep 17 00:00:00 2001 From: Kelly Kinkade Date: Fri, 4 Dec 2026 17:06:57 -0600 Subject: [PATCH 3/3] adjust tests my local copy of dreamfort is out of date relative to the one in CI --- test/library/items_fortress.lua | 159 ++++++++++++++++++++------------ 1 file changed, 102 insertions(+), 57 deletions(-) diff --git a/test/library/items_fortress.lua b/test/library/items_fortress.lua index 2a26fc21b3..e1ac7d0f89 100644 --- a/test/library/items_fortress.lua +++ b/test/library/items_fortress.lua @@ -1,61 +1,85 @@ config.mode = 'fortress' config.target = 'core' --- Dreamfort baselines (see devel/items-call-cost.lua for perf measurements) -local BARREL_ID = 695 -- item_barrelst -local BARREL_CHILD_IDS = {32088, 32126, 32178, 34230} -- all item_foodst -local BAG_ID = 679 -- item_bagst -local BAG_CHILD_IDS = {35257, 35352} -- item_seedsst -local PLANTS_BARREL_ID = 701 -- item_barrelst -local PLANTS_BARREL_CHILD_COUNT = 11 -- all item_plantst -local BIG_BAG_ID = 13733 -- item_bagst -local BIG_BAG_CHILD_COUNT = 80 -- item_seedsst +-- NOTE: fixtures are discovered at runtime rather than pinned to specific +-- item ids, since item ids vary across generated saves (including the CI +-- dreamfort). -function test.getContainedItems_empty() - local non_container = df.item.find(BARREL_CHILD_IDS[1]) - expect.table_eq(dfhack.items.getContainedItems(non_container), {}) +local _container, _children +local function find_item_with_children(min_children) + if _container and #_children >= min_children then + return _container, _children + end + local items = df.global.world.items.all + for i = 0, #items - 1 do + local it = items[i] + local children = dfhack.items.getContainedItems(it) + if #children >= min_children then + _container, _children = it, children + return it, children + end + end end -function test.getContainedItems_baseline() - local barrel = df.item.find(BARREL_ID) - expect.eq(barrel._type, df.item_barrelst) - local children = dfhack.items.getContainedItems(barrel) - expect.eq(#children, #BARREL_CHILD_IDS) - for i, id in ipairs(BARREL_CHILD_IDS) do - expect.eq(children[i].id, id, ('child %d'):format(i)) - expect.eq(children[i]._type, df.item_foodst, ('child %d'):format(i)) +local function find_non_container_item() + local items = df.global.world.items.all + for i = 0, #items - 1 do + local it = items[i] + if #dfhack.items.getContainedItems(it) == 0 then + return it + end end end -function test.getContainedItems_bag_baseline() - local children = dfhack.items.getContainedItems(df.item.find(BAG_ID)) - expect.eq(#children, #BAG_CHILD_IDS) - for i, id in ipairs(BAG_CHILD_IDS) do - expect.eq(children[i].id, id, ('child %d'):format(i)) - expect.eq(children[i]._type, df.item_seedsst, ('child %d'):format(i)) +local function find_largest_container() + local best, best_children + local items = df.global.world.items.all + for i = 0, #items - 1 do + local it = items[i] + local children = dfhack.items.getContainedItems(it) + if not best_children or #children > #best_children then + best, best_children = it, children + end end + return best, best_children end -function test.getContainedItems_sizes() - local cases = { - {PLANTS_BARREL_ID, PLANTS_BARREL_CHILD_COUNT, df.item_plantst}, - {BIG_BAG_ID, BIG_BAG_CHILD_COUNT, df.item_seedsst}, - } - for _, case in ipairs(cases) do - local children = dfhack.items.getContainedItems(df.item.find(case[1])) - expect.eq(#children, case[2], ('container %d'):format(case[1])) - for i, child in ipairs(children) do - expect.eq(child._type, case[3], - ('container %d child %d'):format(case[1], i)) - end +function test.getContainedItems_empty() + local item = find_non_container_item() + expect.ne(item, nil, 'no non-container item found') + if not item then return end + expect.table_eq(dfhack.items.getContainedItems(item), {}) +end + +function test.getContainedItems_baseline() + local container, children = find_item_with_children(2) + expect.ne(container, nil, 'no container with >=2 children found') + if not container then return end + -- result is stable across calls + expect.eq(#dfhack.items.getContainedItems(container), #children) + for i, child in ipairs(children) do + expect.eq(type(child), 'userdata', ('child %d'):format(i)) + -- every child resolves to a concrete item subclass + expect.ne(child._type, df.item, ('child %d'):format(i)) + expect.eq(type(child.id), 'number', ('child %d'):format(i)) end end +function test.getContainedItems_large() + local container, children = find_largest_container() + expect.ne(container, nil, 'no containers found') + if not container then return end + expect.gt(#children, 0) + expect.eq(#dfhack.items.getContainedItems(container), #children) +end + -- Returned element refs are canonical: identical across calls and equal to -- df.item.find() lookups. function test.getContainedItems_ref_identity() - local a = dfhack.items.getContainedItems(df.item.find(BARREL_ID)) - local b = dfhack.items.getContainedItems(df.item.find(BARREL_ID)) + local container, a = find_item_with_children(1) + expect.ne(container, nil, 'no containers found') + if not container then return end + local b = dfhack.items.getContainedItems(container) expect.eq(#a, #b) for i = 1, #a do expect.true_(rawequal(a[i], b[i]), ('child %d'):format(i)) @@ -63,43 +87,64 @@ function test.getContainedItems_ref_identity() end end --- getGeneralRef returns the child-side contained_in_item ref; the container's --- own general_refs elements are the container-side contains_item direction. +-- getGeneralRef returns the child-side contained_in_item ref pointing back +-- at the container. function test.getGeneralRef() - local r = dfhack.items.getGeneralRef(df.item.find(BARREL_CHILD_IDS[1]), + local container, children = find_item_with_children(1) + expect.ne(container, nil, 'no containers found') + if not container then return end + local r = dfhack.items.getGeneralRef(children[1], df.general_ref_type.CONTAINED_IN_ITEM) expect.eq(r._type, df.general_ref_contained_in_itemst) - expect.eq(r.item_id, BARREL_ID) + expect.eq(r.item_id, container.id) end function test.getGeneralRef_identity() - local child = df.item.find(BARREL_CHILD_IDS[1]) - local a = dfhack.items.getGeneralRef(child, df.general_ref_type.CONTAINED_IN_ITEM) - local b = dfhack.items.getGeneralRef(child, df.general_ref_type.CONTAINED_IN_ITEM) + local container, children = find_item_with_children(1) + expect.ne(container, nil, 'no containers found') + if not container then return end + local a = dfhack.items.getGeneralRef(children[1], + df.general_ref_type.CONTAINED_IN_ITEM) + local b = dfhack.items.getGeneralRef(children[1], + df.general_ref_type.CONTAINED_IN_ITEM) expect.true_(rawequal(a, b)) end +-- The container's own general_refs carry the contains_item direction, one +-- per contained child. function test.general_refs_baseline() - local barrel = df.item.find(BARREL_ID) - expect.eq(#barrel.general_refs, #BARREL_CHILD_IDS) - for i = 0, #BARREL_CHILD_IDS - 1 do - local r = barrel.general_refs[i] - expect.eq(r._type, df.general_ref_contains_itemst, ('ref %d'):format(i)) - expect.eq(r.item_id, BARREL_CHILD_IDS[i + 1], ('ref %d'):format(i)) + local container, children = find_item_with_children(1) + expect.ne(container, nil, 'no containers found') + if not container then return end + local contains = {} + for i = 0, #container.general_refs - 1 do + local r = container.general_refs[i] + if r._type == df.general_ref_contains_itemst then + contains[r.item_id] = true + end + end + for _, child in ipairs(children) do + expect.true_(contains[child.id], + ('missing contains_item ref for child %d'):format(child.id)) end end function test.general_refs_identity() - local barrel = df.item.find(BARREL_ID) - expect.true_(rawequal(barrel.general_refs[0], barrel.general_refs[0])) + local container = find_item_with_children(1) + expect.ne(container, nil, 'no containers found') + if not container then return end + expect.true_(rawequal(container.general_refs[0], container.general_refs[0])) end -- The child-side ref and the container-side ref are different objects and -- must NOT collapse into one canonical ref. function test.different_refs_not_identical() + local container, children = find_item_with_children(1) + expect.ne(container, nil, 'no containers found') + if not container then return end local child_ref = dfhack.items.getGeneralRef( - df.item.find(BARREL_CHILD_IDS[1]), df.general_ref_type.CONTAINED_IN_ITEM) - local container_ref = df.item.find(BARREL_ID).general_refs[0] + children[1], df.general_ref_type.CONTAINED_IN_ITEM) + local container_ref = container.general_refs[0] expect.false_(rawequal(child_ref, container_ref)) end