Path: redb/redb.Core/Utils/RedbHash.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/RedbHash.cs ---- using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Core.Attributes; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.Json.Serialization; namespace redb.Core.Utils { /// /// Utility for computing the MD5 hash of an object. _hash covers the WHOLE object row: /// the header canon (see ) together with the Props content; a /// non-generic RedbObject (or a typed one without Props) hashes its header alone. /// public static class RedbHash { /// Canon of a null header value - distinct from an empty string. private const string NullMark = "\0"; /// /// Canonical string of the object header: every column of the _objects row except /// the hash itself, the identity (id, scheme id) and the audit trio /// (date_create, date_modify, who_change). The audit trio is stamped /// on the database record AFTER the hash is computed and never written back into the /// object, so a hash carrying it could never be reproduced from a reloaded row - the /// cache and the ChangeTracking hash shortcut would be dead for every object. The scheme /// id is assigned after the batch recomputes hashes (every new object would miss its /// first hits), and the id is 0 until the save assigns it. Header dates canonicalise at /// second precision in UTC: sub-second digits do not survive every database (SQLite /// stores REAL Julian days, ~40 microseconds) and MSSQL keeps the offset while /// PostgreSQL returns UTC. /// public static string HeaderCanon(IRedbObject obj) { var inv = CultureInfo.InvariantCulture; var parts = new List(16) { obj.ParentId?.ToString(inv) ?? NullMark, obj.OwnerId.ToString(inv), Escape(obj.Name, HeaderSeparators) ?? NullMark, Escape(obj.Note, HeaderSeparators) ?? NullMark, obj.Key?.ToString(inv) ?? NullMark, obj.ValueLong?.ToString(inv) ?? NullMark, Escape(obj.ValueString, HeaderSeparators) ?? NullMark, obj.ValueGuid?.ToString("N") ?? NullMark, obj.ValueBool?.ToString(inv) ?? NullMark, obj.ValueDouble?.ToString("R", inv) ?? NullMark, obj.ValueNumeric?.ToString("G29", inv) ?? NullMark, DateCanon(obj.ValueDatetime), obj.ValueBytes != null ? Convert.ToBase64String(obj.ValueBytes) : NullMark, Escape(obj.ValueUnique, HeaderSeparators) ?? NullMark, DateCanon(obj.DateBegin), DateCanon(obj.DateComplete), }; return string.Join("|", parts); } private static string DateCanon(DateTimeOffset? value) => value?.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture) ?? NullMark; /// /// Hash of the header alone (Object schemes without Props): a non-generic RedbObject or a /// RedbObject{TProps} with Props=null. The same canon the typed hash starts from. /// public static Guid ComputeForBaseFields(IRedbObject obj) { return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(HeaderCanon(obj)))); } /// /// Hash of any IRedbObject: header canon plus Props content. /// Returns null if there are no Props to hash (the callers fall back to /// ). /// public static Guid? ComputeFor(IRedbObject obj) { // Find Props property via reflection var propertiesProperty = obj.GetType().GetProperty("Props"); if (propertiesProperty != null) { var propertiesValue = propertiesProperty.GetValue(obj); if (propertiesValue != null) { return Combine(obj, ComputeForObject(propertiesValue)); } } // If no Props - return null return null; } public static Guid? ComputeFor(RedbObject obj) where TProps : class, new() { return Combine(obj, ComputeForProps(obj.Props)); } /// Header canon and the Props hash into one object hash; null Props hash stays null. private static Guid? Combine(IRedbObject obj, Guid? propsHash) { if (propsHash is null) return null; var payload = HeaderCanon(obj) + "||" + propsHash.Value.ToString("N"); return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(payload))); } public static Guid? ComputeForProps(TProps props) where TProps : class, new() { return ComputeForObject(props); } /// /// Compute hash for arbitrary object via reflection. /// Returns null if object has no properties. /// private static Guid? ComputeForObject(object? obj) { // No object → no data to hash. The reflection-based ComputeFor(IRedbObject) // already returns null for a null Props (Props=null is a supported case — // see ComputeForBaseFields). This aligns the generic ComputeForProps path // with that contract instead of throwing NRE on obj.GetType(). if (obj is null) return null; // The objects on the way from the root to this one. Reached again on the same way, an object is a cycle: // the walk would never end and the stack overflow takes the process down. An object reached twice on // different ways (one instance shared by two properties) is no cycle and hashes as before, as two copies. var path = _walkPath ??= new HashSet(ReferenceEqualityComparer.Instance); if (!path.Add(obj)) throw new InvalidOperationException( $"The props of a redb object hold a reference cycle: an instance of '{obj.GetType().FullName}' is " + "reached again through its own properties. A nested class is stored as a tree of values and cannot " + "refer back to an object above it. Mark the back-reference [RedbIgnore], or link the objects as " + "RedbObject references, which are stored by id."); try { return ComputeForWalkedObject(obj); } finally { path.Remove(obj); } } /// The way of the current walk of ; the walk is synchronous. [ThreadStatic] private static HashSet? _walkPath; private static Guid? ComputeForWalkedObject(object obj) { // A collection passed as the root (collection base-row hashes above all): reflecting // over the collection type's OWN properties degenerates the canon - List exposed only // Capacity|Count, long[] only Length&Co, so same-sized collections with different // content hashed equal (found by the F2 short-circuit, pinned by // ArrayBaseHash_DependsOnElementContent). Format the collection through the same // canon branches a collection FIELD takes, and hash that string. if (obj is System.Collections.IDictionary rootDict) return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(FormatDictionaryCanon(rootDict)))); if (obj is System.Collections.IEnumerable rootSeq && obj is not string) return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(FormatEnumerableCanon(rootSeq)))); var properties = HashedProperties(obj.GetType()); // If no properties - no data for hashing if (properties.Length == 0) return null; var ordered = properties.Select(p => SafeGetValue(p, obj)); var payload = string.Join("|", ordered); var bytes = Encoding.UTF8.GetBytes(payload); var hash = RedbMd5.ComputeHash(bytes); return new Guid(hash); } /// The hashed properties of a type, in canon order; computed once per type. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable HashedPropertiesByType = new(); /// /// The properties a type contributes to the hash, in canon order: by , then by the /// property name, both ordinal. A weak table, so a type of an unloadable module does not stay alive through it. /// An indexer is not a field (the scheme sync and the value writer skip it) and has no value without an index. /// private static PropertyInfo[] HashedProperties(Type type) => HashedPropertiesByType.GetValue(type, static t => t .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.GetIndexParameters().Length == 0) .Where(p => !ShouldIgnoreForHash(p)) // Filter technical properties .OrderBy(HashSortKey, StringComparer.Ordinal) .ThenBy(p => p.Name, StringComparer.Ordinal) .ToArray()); /// /// The name a property sorts by in the hash canon: the name of its first /// (the first name of the property), the property name when it has none. A rename keeps the property where it /// sorted before, so the hashes stored before the rename stay valid after it; this is why the attribute stays /// on the property for good. A property without the attribute sorts by its name, exactly as before the /// attribute existed. The attributes are read in declaration order; the scheme sync checks the first one /// against the history the database keeps in _structures._renamed_from. /// internal static string HashSortKey(PropertyInfo property) => property.GetCustomAttributes(false).FirstOrDefault()?.OldName ?? property.Name; /// /// Checks if property should be ignored during hash calculation. /// private static bool ShouldIgnoreForHash(PropertyInfo property) { // Only RedbIgnore affects hash calculation. JsonIgnore is for JSON serialization. return property.GetCustomAttributes(typeof(RedbIgnoreAttribute), false).Length > 0; } /// /// The canon of one property value; recursively hashes nested objects and arrays. A getter's exception is not /// caught (owner decision 2026-09-15): an empty string standing in for it made the hash describe data the /// object does not have, and the save does not catch that getter either. /// private static string SafeGetValue(PropertyInfo property, object obj) { var value = property.GetValue(obj); if (value == null) return ""; var type = value.GetType(); // Primitives and simple types: the invariant canon (culture-free, milliseconds for temporal values) // A null property canonicalises to "" above, so an empty string takes a mark of its own. if (value is string { Length: 0 }) return EmptyTextMark; if (IsPrimitiveOrSimple(type)) return ScalarCanon(value, PropertySeparators); // V4 (L.2, LAZY plan §4.1): a nested RedbObject is a REFERENCE. The parent hashes // the reference's own persisted hash instead of walking its Props: walking would // (a) trigger lazy loading of the whole graph from inside a hash computation and // (b) make the eager and the lazy hash of the same parent differ (a stub carries // no Props). The hash field is present on stub and full object alike. if (value is IRedbObject nestedRef) return $"{nestedRef.Id}:{nestedRef.Hash?.ToString("N")}"; // id = identity, hash = content-at-write // O-1/B-3 (owner's verdict): _values stores the dictionary item IDENTIFIER, and the // hash canon is the id ONLY. ListItem content lives its own life (extension objects); // hashing the content would move the owner's hash whenever a value in _list_items // is renamed. if (value is IRedbListItem listItemRef) return listItemRef.Id.ToString(); // Dictionaries — hash by CONTENT, order-independent. A Dictionary is an UNORDERED set of // key/value pairs: {a:1,b:2} equals {b:2,a:1}, so equal maps must hash equally. .NET does // not guarantee enumeration order (and it changes after removals), and the same logical // map is rebuilt in a different order when materialized from _values than when first // created — hashing it in enumeration order desynchronizes _objects._hash vs the cache. // Canonicalize by sorting "key=valueHash" pairs before hashing. if (value is System.Collections.IDictionary dictionary) return FormatDictionaryCanon(dictionary); // Arrays and collections - hash each element (ORDER MATTERS here — lists/arrays are ordered) if (value is System.Collections.IEnumerable enumerable && type != typeof(string)) return FormatEnumerableCanon(enumerable); // Nested object (business class) - recursively hash! var nestedHash = ComputeForObject(value); return nestedHash?.ToString("N") ?? ""; } /// /// Canonical string of a dictionary - order-independent (sorted "key=valueCanon" pairs). /// A Dictionary is an UNORDERED set of key/value pairs: {a:1,b:2} equals {b:2,a:1}, so /// equal maps must hash equally regardless of enumeration order. /// private static string FormatDictionaryCanon(System.Collections.IDictionary dictionary) { var entries = new System.Collections.Generic.List(dictionary.Count); foreach (System.Collections.DictionaryEntry entry in dictionary) { // A key that is not a simple value (a tuple, a class) canonicalises through the serializer that writes // it into _array_index: culture-free, and distinct for distinct keys. Its ToString() was the canon // before: a class without its own ToString() gave the type name for every key, so a changed key kept // the hash, and a tuple of a double or a date followed the culture of the node. var keyStr = entry.Key == null ? "null" : IsPrimitiveOrSimple(entry.Key.GetType()) ? ScalarCanon(entry.Key, KeySeparators) : Escape(RedbKeySerializer.SerializeObject(entry.Key, entry.Key.GetType()), KeySeparators)!; string valStr; if (entry.Value == null) valStr = "null"; else if (entry.Value is "null") valStr = NullTextMark; // a null value canonicalises to "null" else if (IsPrimitiveOrSimple(entry.Value.GetType())) valStr = ScalarCanon(entry.Value, ElementSeparators); else if (entry.Value is IRedbObject dictRef) valStr = $"{dictRef.Id}:{dictRef.Hash?.ToString("N")}"; // V4 (L.2): reference by its hash else if (entry.Value is IRedbListItem dictListItem) valStr = dictListItem.Id.ToString(); // O-1: ListItem canon is the id only else valStr = ComputeForObject(entry.Value)?.ToString("N") ?? "null"; entries.Add($"{keyStr}={valStr}"); } entries.Sort(StringComparer.Ordinal); return $"{{{string.Join(",", entries)}}}"; } /// /// Canonical string of an ordered collection - element canons joined IN ORDER /// (lists/arrays are ordered, so reorder changes the canon). /// private static string FormatEnumerableCanon(System.Collections.IEnumerable enumerable) { var elementHashes = new System.Collections.Generic.List(); foreach (var item in enumerable) { if (item == null) { elementHashes.Add("null"); } else if (item is "null") { elementHashes.Add(NullTextMark); // a null element canonicalises to "null" } else if (item is string { Length: 0 }) { elementHashes.Add(EmptyTextMark); // "[]" is the canon of an empty collection } else if (IsPrimitiveOrSimple(item.GetType())) { elementHashes.Add(ScalarCanon(item, ElementSeparators)); } else if (item is IRedbObject itemRef) { elementHashes.Add($"{itemRef.Id}:{itemRef.Hash?.ToString("N")}"); // V4 (L.2) } else if (item is IRedbListItem itemListItem) { elementHashes.Add(itemListItem.Id.ToString()); // O-1: ListItem canon is the id only } else { // Recursively hash nested object var itemHash = ComputeForObject(item); elementHashes.Add(itemHash?.ToString("N") ?? "null"); } } return $"[{string.Join(",", elementHashes)}]"; } /// /// The canon of a primitive or simple value. Invariant: the process culture never takes part (a decimal /// separator or a date format of one node must not move the hash on another), and a temporal value is /// canonicalised in UTC at MILLISECOND precision - the precision every database keeps (SQLite stores an /// OLE date, truncated to milliseconds by .NET; PostgreSQL keeps microseconds; SQL Server 100 ns), so the /// hash the save stores is the hash the reloaded object recomputes. A change below one millisecond is /// not a change: the databases do not keep it. A DateTime hashes by its clock reading whatever its Kind, /// exactly as it is stored (DateTimeConverter.NormalizeForStorage stamps Kind=Utc without converting). /// Before this canon the values went through ToString(): sub-second digits were lost, so a save under /// ChangeTracking skipped a temporal property changed within the same second (BR-11, 2026-09-16). /// private static string ScalarCanon(object value, char[] separators) { var inv = CultureInfo.InvariantCulture; switch (value) { case string text: return Escape(text, separators)!; case char symbol: return Escape(symbol.ToString(), separators)!; case decimal d: // Strip trailing zeros (6450.000 == 6450.000000000000000000) return d.ToString("G29", inv); case double d: return d.ToString("R", inv); case float f: return f.ToString("R", inv); case DateTimeOffset dto: return TemporalCanon(dto.UtcTicks); case DateTime dt: return TemporalCanon(dt.Ticks); case DateOnly day: return day.ToString("yyyy-MM-dd", inv); case TimeOnly time: return new TimeOnly(time.Ticks - time.Ticks % TimeSpan.TicksPerMillisecond).ToString("HH:mm:ss.fff", inv); case TimeSpan span: return span.ToString("c", inv); case IFormattable formattable: return formattable.ToString(null, inv); default: return value.ToString() ?? ""; } } /// /// The escape character of the canon: inside a string it precedes a separator or itself. A control character /// (U+0001), not a backslash: a hash stored before the escaping was computed over the plain string, so a /// value that held the escaped form as text ("a\,b") would hash, with a backslash, like the new value it was /// changed to ("a,b"), and the change would be skipped. Business text does not hold U+0001, so the canon of /// an escaped string matches no canon stored before, and a string with a backslash keeps its canon. /// private const char EscapeChar = '\u0001'; /// /// The canon of an empty string where "" already stands for something else: a null class property /// canonicalises to "", and a collection of one empty string would read "[]" like an empty one. An escaped /// string never holds the escape character before anything but a separator or itself, so the mark is unique. /// private const string EmptyTextMark = "\u0001e"; /// /// The canon of the string "null" where "null" stands for a null value: an element of a collection and a /// dictionary value. Unique for the same reason as . /// private const string NullTextMark = "\u0001n"; /// Separators a string meets in the header canon: '|' joins the parts. private static readonly char[] HeaderSeparators = { EscapeChar, '|' }; /// Separators a string meets as a class property value: '|' joins the properties. private static readonly char[] PropertySeparators = { EscapeChar, '|' }; /// /// Separators a string meets as an element of a collection or a dictionary value: ',' joins the elements and /// the entries, '|' the properties of the class that holds the collection. /// private static readonly char[] ElementSeparators = { EscapeChar, '|', ',' }; /// Separators a dictionary key meets: those of an element and '=' between the key and its value. private static readonly char[] KeySeparators = { EscapeChar, '|', ',', '=' }; /// /// A string as it enters the canon: each separator of its place and the escape character itself get the escape /// character in front. The canon joins values with separators and does not quote them, so before the escaping /// "x|y" and "" hashed like "x" and "y|", and a ChangeTracking save of one over the other was skipped as /// unchanged. A string with no separator of its place and no escape character is returned as it is: its canon, /// and the hashes stored for it, stay what they were. Each place escapes only the separators that can split it, /// so a comma in a class property keeps its canon. /// private static string? Escape(string? text, char[] separators) { if (text is null || text.IndexOfAny(separators) < 0) return text; var escaped = new StringBuilder(text.Length + 8); foreach (var symbol in text) { if (Array.IndexOf(separators, symbol) >= 0) escaped.Append(EscapeChar); escaped.Append(symbol); } return escaped.ToString(); } private static string TemporalCanon(long ticks) => new DateTime(ticks - ticks % TimeSpan.TicksPerMillisecond, DateTimeKind.Unspecified) .ToString("yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture); /// /// Checks if type is primitive or simple (does not require recursion). /// private static bool IsPrimitiveOrSimple(Type type) { return type.IsPrimitive || type.IsEnum || type == typeof(string) || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(TimeSpan) || type == typeof(DateOnly) || type == typeof(TimeOnly) || type == typeof(Guid) || Nullable.GetUnderlyingType(type) != null; } /// /// Combines multiple hashes into single hash. /// Used for computing array hash from its element hashes. /// public static Guid CombineHashes(System.Collections.Generic.List hashes) { if (hashes == null || !hashes.Any()) return Guid.Empty; // Combine all hashes into string and compute MD5 var payload = string.Join("|", hashes.Select(h => h.ToString("N"))); var bytes = Encoding.UTF8.GetBytes(payload); var hash = RedbMd5.ComputeHash(bytes); return new Guid(hash); } } }