Path: redb/redb.Core/Utils/LazyReferenceInstaller.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Utils/LazyReferenceInstaller.cs ---- using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using redb.Core.Models.Contracts; using redb.Core.Providers; namespace redb.Core.Utils; /// /// V4 (L.3, LAZY plan §3.5): after deserialization every UNLOADED reference stub in a Props graph gets the lazy loader /// attached, so the first access to its Props loads exactly that object — whose own references are again stubs (the /// loader passes depth 1, §4.7). The walk descends only into LOADED objects via their raw Props (never through the getter, /// which would trigger loading), mirrors the shape of CacheNestedObjects, and tracks visited instances against /// cycles. /// /// A data object owns no connection. A /// loader bound to one scope is never installed on a stub: the stub gets the scope-free loader of that loader's database, /// which loads on the scope current for the reader, else on the materializing scope (the origin) while it lives. List items /// are bound the same way. A cache marks its graph shared: its stubs and items lose the origin and load on the reader's /// scope only. /// /// public static class LazyReferenceInstaller { /// /// V4 (review): after deserialization, every RedbObject<T> in the graph whose Props are /// null is marked NOT loaded. The Props setter marks any assignment as loaded, so a stub written /// by a foreign serializer as "properties": null would otherwise come back as a loaded /// object with nothing in it - and a parent save would write it as such (values deleted). The /// reader deserializes the whole subtree with the default converter, so the rule is applied by /// one walk from the root; it descends through loaded objects only, via their raw Props. /// public static void MarkUnloadedWherePropsAreNull(object? root) { if (root == null) return; var visited = new HashSet(ReferenceEqualityComparer.Instance); MarkInto(root, visited); } private static void MarkInto(object? node, HashSet visited) { if (node == null) return; var type = node.GetType(); if (type.IsPrimitive || type.IsValueType || node is string) return; if (IsWalkLeaf(node)) return; if (!visited.Add(node)) return; if (node is Models.Entities.RedbObject) { var props = type.GetMethod("GetPropsDirectly")?.Invoke(node, null); if (props == null) { // The non-generic RedbObject has no such field; the probe is null-safe. type.GetField("_propsLoaded")?.SetValue(node, false); return; } MarkInto(props, visited); return; } if (node is IDictionary dict) { foreach (DictionaryEntry e in dict) MarkInto(e.Value, visited); return; } if (node is IEnumerable seq) { foreach (var item in seq) MarkInto(item, visited); return; } if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) return; foreach (var p in WalkedProperties(type)) { var value = p.GetValue(node); MarkInto(value, visited); } } /// /// Attach the loader of 's database to every unloaded reference stub under /// , and bind every list item under it to that database and origin. /// public static void Install(IRedbObject? root, ILazyPropsLoader? loader) { if (root == null || loader == null) return; var visited = new HashSet(ReferenceEqualityComparer.Instance); InstallInto(root, ForStubs(loader), visited); } /// /// Same walk from an arbitrary node - a Props object, a collection, a list item - for callers that hold no root. /// public static void InstallInto(object? node, ILazyPropsLoader? loader) { if (node == null || loader == null) return; var visited = new HashSet(ReferenceEqualityComparer.Instance); InstallInto(node, ForStubs(loader), visited); } /// /// Marks a graph handed to a cache as shared by every scope: the objects, the stubs and the list items in it. A shared /// instance loads lazily on the reader's scope only - its stubs and items lose their origin - and, inside the reader's /// transaction, keeps nothing (owner decision 2026-09-15). Descends through loaded objects via their raw Props. /// public static void MarkShared(object? root) { if (root == null) return; MarkSharedInto(root, new HashSet(ReferenceEqualityComparer.Instance), null); } /// /// The same walk as , and the loaded objects it passed are returned: one pass serves both /// the shared mark and the cache entries of the graph, which used to be two walks of the same Props. A stub is /// marked only; a list item is marked and its already loaded object is visited, never loaded by the walk. /// public static List MarkSharedAndCollect(object? root) { var collected = new List(); if (root == null) return collected; MarkSharedInto(root, new HashSet(ReferenceEqualityComparer.Instance), collected); return collected; } private static void MarkSharedInto(object? node, HashSet visited, List? collected) { if (node == null) return; var type = node.GetType(); if (type.IsPrimitive || type.IsValueType || node is string) return; if (node is Models.Entities.RedbListItem item) { item._isShared = true; item._origin = null; // The object the item already carries is shared with it. MarkSharedInto(item.LoadedObject, visited, collected); return; } if (IsWalkLeaf(node)) return; if (!visited.Add(node)) return; if (node is Models.Entities.RedbObject obj) { obj._isShared = true; if (!obj.IsPropsLoaded) { var field = type.GetField("_lazyLoader"); if (field?.GetValue(node) is AmbientLazyPropsLoader ambient) field.SetValue(node, ambient.Shared); return; } // The nested entries SetNested used to write in a second walk: a loaded object with a hash // of its own is served by id directly. if (collected != null && obj is IRedbObject { Hash: not null } loaded) collected.Add(loaded); MarkSharedInto(type.GetMethod("GetPropsDirectly")?.Invoke(node, null), visited, collected); return; } if (node is IDictionary dict) { foreach (DictionaryEntry e in dict) MarkSharedInto(e.Value, visited, collected); return; } if (node is IEnumerable seq) { foreach (var element in seq) MarkSharedInto(element, visited, collected); return; } if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) return; foreach (var p in WalkedProperties(type)) { MarkSharedInto(p.GetValue(node), visited, collected); } } /// /// True for a collection that can hold no reference at all - an array or a System generic /// collection whose element types are primitives, value types or strings (a byte[] /// payload above all). Walking such a collection element by element boxes every item for /// nothing; both graph walkers (this installer and the Pro stub collector) skip it. /// public static bool IsLeafCollection(object node) { var type = node.GetType(); if (type.IsArray) return IsLeafType(type.GetElementType()); if (type.IsGenericType && type.Namespace?.StartsWith("System.Collections", StringComparison.Ordinal) == true) { foreach (var arg in type.GetGenericArguments()) if (!IsLeafType(arg)) return false; return true; } return false; } /// /// True for a node no reflective walk of a loaded graph may descend into: a /// or a list item. A list item's lazy Object getter LOADS /// on read, so walking its properties fired a database load per linked item on every /// materialization of an object with list-item fields (~150 phantom loads a second on a /// production stand, 2026-09-09 - with not a single explicit .Object in the application). /// Every walker over loaded Props (this installer, the props-cache dirty guard, the cache /// collector, the Pro materialization walks) asks this one predicate, so the rule cannot drift. /// public static bool IsWalkLeaf(object node) => node is Models.Contracts.IRedbListItem || IsLeafCollection(node); /// /// True for a property a walk of a loaded graph reads: the set the scheme and the save take - public, not an /// indexer, not [RedbIgnore]. A getter's exception is not caught, as the save does not catch it (owner /// decision 2026-09-15); a computed property that is not data belongs under [RedbIgnore]. /// public static bool IsWalkedProperty(PropertyInfo property) => property.CanRead && property.GetIndexParameters().Length == 0 && !Extensions.PropertyInfoExtensions.ShouldIgnoreForRedb(property); // The walked properties of a type (public instance, IsWalkedProperty), once per type. Each walk of each node read // the properties of its type again and the [RedbIgnore] attribute of each of them. Keyed weakly: a Props type of a // module in a collectible AssemblyLoadContext must not keep that context alive. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable WalkedPropertyCache = new(); private static PropertyInfo[] WalkedProperties(Type type) => WalkedPropertyCache.GetValue(type, static t => { var walked = new List(); foreach (var p in t.GetProperties(BindingFlags.Public | BindingFlags.Instance)) if (IsWalkedProperty(p)) walked.Add(p); return walked.ToArray(); }); private static bool IsLeafType(Type? t) => t != null && (t.IsPrimitive || t.IsValueType || t == typeof(string) || t == typeof(byte[])); // A loader that names its database is bound to one scope: the stub gets that database's scope-free loader, with the // service of that scope as its origin - or the captive service that scope was lent to (RedbServiceBase.AsOrigin). private static ILazyPropsLoader ForStubs(ILazyPropsLoader loader) => loader is not AmbientLazyPropsLoader && loader.CacheDomain is { } domain ? AmbientLazyPropsLoader.For(domain, RedbServiceBase.ServiceOf(loader.ScopeContext)?.AsOrigin) : loader; private static void InstallInto(object? node, ILazyPropsLoader loader, HashSet visited) { if (node == null) return; var type = node.GetType(); if (type.IsPrimitive || type.IsValueType || node is string) return; if (node is Models.Entities.RedbListItem item) { // Bound once: an item never moves to another database. Its Object is never read here. if (loader.CacheDomain is { } domain) item._cacheDomain ??= domain; if (!item._isShared && loader is AmbientLazyPropsLoader { Origin: { } origin }) item._origin ??= origin; return; } if (IsWalkLeaf(node)) return; // byte[], int[], List: nothing to attach, no walk if (!visited.Add(node)) return; if (node is Models.Entities.RedbObject baseObj && node is IRedbObject redbObj) { // RedbObject and TreeRedbObject alike: the public _lazyLoader field and // GetPropsDirectly are inherited, so Type.GetField/GetMethod see them on the derived // type. The non-generic RedbObject has neither, and both probes are null-safe. if (!baseObj.IsPropsLoaded && redbObj.Id > 0) { // The stub: attach the loader, do not descend — there is nothing loaded to walk. A shared stub never // regains an origin. var installed = baseObj._isShared && loader is AmbientLazyPropsLoader ambient ? ambient.Shared : loader; type.GetField("_lazyLoader")?.SetValue(node, installed); return; } // A loaded object: walk its raw Props for deeper stubs. Raw access only — // the Props getter of a stub is a load. var props = type.GetMethod("GetPropsDirectly")?.Invoke(node, null); InstallInto(props, loader, visited); return; } if (node is IDictionary dict) { foreach (DictionaryEntry e in dict) InstallInto(e.Value, loader, visited); return; } if (node is IEnumerable seq) { foreach (var element in seq) InstallInto(element, loader, visited); return; } // A business class (the Props object itself or a nested class): walk its properties. if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) return; foreach (var p in WalkedProperties(type)) { var value = p.GetValue(node); InstallInto(value, loader, visited); } } }