diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aa00c193..8c85016a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -289,6 +289,7 @@ jobs: --configuration Release \ --lane age \ --no-build \ + --coverage \ --disable-diff-engine \ --report-trx \ --results-directory "TestResults/age-${{ matrix.age }}" diff --git a/docs/provider-implementers-guide.md b/docs/provider-implementers-guide.md index 59340e75..8402123c 100644 --- a/docs/provider-implementers-guide.md +++ b/docs/provider-implementers-guide.md @@ -313,6 +313,15 @@ any other result map. A backend that cannot persist a map-valued entity property assembly-qualified name as a scalar under the same reserved property; the materializer accepts both forms. +The shared result processor caches successful metadata resolutions only in the default reflection +context. A non-default contextual reflection scope resolves the name independently, since the same +assembly identity can denote a different CLR type in another load context. Missing names are not +cached, so a later assembly load can make them resolvable. Result-discovery caches and their +instrumentation must not retain collectible types, including constructed generic types with +collectible arguments. Assembly-load generations and their discovered type arrays are published as +one snapshot. These are result-cache guarantees; a host must separately release its entity, +serializer and schema references before expecting an entire plugin to unload. + Relationship updates must treat the authoritative storage/logical type and exact concrete CLR type as immutable identity. Compare both before replacing any properties, and keep the comparison in the same guarded mutation as the write (or repeat it in the write predicate after a lookup). A failed diff --git a/src/Graph.CompatibilityTests/IAggregationTests.cs b/src/Graph.CompatibilityTests/IAggregationTests.cs index d8141ec9..6dff39f8 100644 --- a/src/Graph.CompatibilityTests/IAggregationTests.cs +++ b/src/Graph.CompatibilityTests/IAggregationTests.cs @@ -22,6 +22,41 @@ public record PersonWithNumbers : Node public Guid TrackingId { get; set; } } + /// Certifies synchronous terminals across hierarchy, duplicate elimination and paging. + [Fact] + public async Task SynchronousCounts_RespectHierarchyDistinctAndPaging() + { + var ct = TestContext.Current.CancellationToken; + var marker = $"sync-count-{Guid.NewGuid():N}"; + Person[] people = + [ + new Person { FirstName = marker, Age = 10 }, + new Person { FirstName = marker, Age = 10 }, + new Person { FirstName = marker, Age = 20 }, + new Manager { FirstName = marker, Age = 20 }, + new Manager { FirstName = marker, Age = 30 }, + ]; + foreach (var person in people) + { + await Graph.CreateNodeAsync(person, null, ct); + } + + var source = Graph.Nodes().Where(person => person.FirstName == marker); + Assert.Equal(5, Queryable.Count(source)); + Assert.Equal(5L, Queryable.LongCount(source)); + Assert.Equal(3, Queryable.Count(source, person => person.Age >= 20)); + Assert.Equal(3L, Queryable.LongCount(source, person => person.Age >= 20)); + + var distinct = source.Select(person => person.Age).Distinct(); + Assert.Equal(3, Queryable.Count(distinct)); + Assert.Equal(3L, Queryable.LongCount(distinct)); + var page = source.OrderBy(person => person.Age).ThenBy(person => person.TestKey).Skip(1).Take(2); + Assert.Equal(2, Queryable.Count(page)); + Assert.Equal(2L, Queryable.LongCount(page)); + Assert.Equal(0, Queryable.Count(source, person => person.Age < 0)); + Assert.Equal(0L, Queryable.LongCount(source, person => person.Age < 0)); + } + [Fact] public async Task CanCountDistinctQuery() { diff --git a/src/Graph.CompatibilityTests/IGraphCommandTests.cs b/src/Graph.CompatibilityTests/IGraphCommandTests.cs index 663912a1..094cb411 100644 --- a/src/Graph.CompatibilityTests/IGraphCommandTests.cs +++ b/src/Graph.CompatibilityTests/IGraphCommandTests.cs @@ -940,6 +940,49 @@ await Assert.ThrowsAsync(() => Graph.FindNodeByTestKe cancellationToken: TestContext.Current.CancellationToken); } + /// Certifies atomic preflight and exact cascade counts for overlapping incident edges. + [Fact] + public async Task SetBasedNodeDelete_PreflightsSelfLoopsAndEdgesBetweenSelectedNodes() + { + var ct = TestContext.Current.CancellationToken; + var marker = $"overlap-delete-{Guid.NewGuid():N}"; + var first = new Person { FirstName = "first", LastName = marker }; + var second = new Person { FirstName = "second", LastName = marker }; + var outside = new Person { FirstName = "outside" }; + foreach (var person in new[] { first, second, outside }) + { + await Graph.CreateNodeAsync(person, null, ct); + } + + var selfLoop = new Knows(); + var selectedEdge = new Knows(); + var incoming = new Knows(); + var outsideLoop = new Knows(); + await Graph.ConnectAsync(first, selfLoop, first, cancellationToken: ct); + await Graph.ConnectAsync(first, selectedEdge, second, cancellationToken: ct); + await Graph.ConnectAsync(outside, incoming, second, cancellationToken: ct); + await Graph.ConnectAsync(outside, outsideLoop, outside, cancellationToken: ct); + var targets = Graph.Nodes().Where(person => person.LastName == marker); + + await Assert.ThrowsAsync(() => GraphCommandExtensions.DeleteAsync( + targets, cascadeDelete: false, ct)); + Assert.Equal(2, await targets.CountAsync(ct)); + foreach (var relationship in new[] { selfLoop, selectedEdge, incoming, outsideLoop }) + { + _ = await Graph.FindRelationshipByTestKeyAsync(relationship.TestKey, null, ct); + } + + Assert.Equal(2, await GraphCommandExtensions.DeleteAsync(targets, cascadeDelete: true, ct)); + Assert.Equal(0, await targets.CountAsync(ct)); + foreach (var relationship in new[] { selfLoop, selectedEdge, incoming }) + { + Assert.Null(await Graph.RelationshipsByTestKey(relationship.TestKey).SingleOrDefaultAsync(ct)); + } + + _ = await Graph.FindNodeByTestKeyAsync(outside.TestKey, null, ct); + _ = await Graph.FindRelationshipByTestKeyAsync(outsideLoop.TestKey, null, ct); + } + [Fact] public async Task ExactOneEndpointSelection_ThrowsRoleSpecificCardinalityFailures() { diff --git a/src/Graph.Serialization/Results/GraphResultProcessor.cs b/src/Graph.Serialization/Results/GraphResultProcessor.cs index b3aae1a5..f89541c1 100644 --- a/src/Graph.Serialization/Results/GraphResultProcessor.cs +++ b/src/Graph.Serialization/Results/GraphResultProcessor.cs @@ -28,8 +28,7 @@ public sealed class GraphResultProcessor private static readonly ConcurrentDictionary LabelsProperties = new(); private static readonly ConcurrentDictionary LabelIndexBuildsForTests = new(); private static long _assemblyVersion; - private static Type[]? _knownConcreteTypes; - private static long _knownConcreteTypesVersion = -1; + private static ConcreteTypesSnapshot? _knownConcreteTypes; static GraphResultProcessor() { @@ -38,6 +37,7 @@ static GraphResultProcessor() } private sealed record LabelIndex(long Version, Dictionary ByLabel); + private sealed record ConcreteTypesSnapshot(long Version, Type[] Types); private static readonly List NoComplexProperties = []; @@ -1144,7 +1144,7 @@ private static void AddNodeLabelsProperty( Type actualType, IReadOnlyList labels) { - var labelsProperty = actualType.Assembly.IsCollectible + var labelsProperty = actualType.IsCollectible ? actualType.GetProperty(nameof(Graph.INode.Labels)) : LabelsProperties.GetOrAdd( actualType, @@ -1331,7 +1331,9 @@ private static Dictionary GetLabelIndex(Type targetType, bool rela if (cache.TryGetValue(targetType, out var cached) && cached.Version == version) return cached.ByLabel; - LabelIndexBuildsForTests.AddOrUpdate(targetType, 1, static (_, count) => count + 1); + // Test instrumentation must obey the same lifetime boundary as the cache it measures. + if (!targetType.IsCollectible) + LabelIndexBuildsForTests.AddOrUpdate(targetType, 1, static (_, count) => count + 1); var byLabel = BuildLabelIndex(targetType, relationships); // Never retain types from a collectible AssemblyLoadContext: the cache would keep that @@ -1403,17 +1405,18 @@ private static Type[] GetKnownConcreteTypes() // changes the version and forces a rebuild on the next call instead of pinning a partial scan. var version = Volatile.Read(ref _assemblyVersion); var assemblies = AppDomain.CurrentDomain.GetAssemblies(); - if (Volatile.Read(ref _knownConcreteTypesVersion) == version && - Volatile.Read(ref _knownConcreteTypes) is { } cached) + var cached = Volatile.Read(ref _knownConcreteTypes); + if (cached is not null && cached.Version == version) { - return cached; + return cached.Types; } var types = ScanConcreteTypes(assemblies); if (AreAllAssembliesCacheable(assemblies)) { - Volatile.Write(ref _knownConcreteTypesVersion, version); - Volatile.Write(ref _knownConcreteTypes, types); + // Publish the generation and its types together so a reader cannot pair a new + // generation with the previous scan and cache an incomplete label map indefinitely. + Volatile.Write(ref _knownConcreteTypes, new ConcreteTypesSnapshot(version, types)); } return types; diff --git a/src/Graph.Serialization/Results/GraphValueConverter.cs b/src/Graph.Serialization/Results/GraphValueConverter.cs index a95ea2ed..e751878e 100644 --- a/src/Graph.Serialization/Results/GraphValueConverter.cs +++ b/src/Graph.Serialization/Results/GraphValueConverter.cs @@ -5,6 +5,7 @@ using System.Collections.Concurrent; using System.Globalization; using System.Reflection; +using System.Runtime.Loader; namespace Cvoya.Graph.Serialization.Results; @@ -13,9 +14,9 @@ internal static class GraphValueConverter internal const string MetadataPropertyName = "__metadata__"; private const string TypeNameKey = "type"; - // Successful metadata resolutions are stable for the life of the process: a Type that - // Type.GetType already resolved cannot become a different Type after another assembly loads. - // Cache only successes so an unresolved name can still resolve after a later assembly load. + // Successful metadata resolutions in the default reflection context remain stable after + // another assembly loads. Cache only successes so a missing name can resolve after a later load; + // non-default contextual reflection must resolve independently of these process-wide entries. private static readonly ConcurrentDictionary ResolvedMetadataTypes = new(StringComparer.Ordinal); public static object? ConvertTo(object? value, Type targetType) @@ -211,16 +212,24 @@ GraphValueKind.Map when metadata.Entries.TryGetValue(TypeNameKey, out var value) return null; } + // The same assembly-qualified name can identify a different Type in another context. + // Such a resolution must neither consume nor populate the default-context success cache. + if (AssemblyLoadContext.CurrentContextualReflectionContext is { } context && + context != AssemblyLoadContext.Default) + { + return Type.GetType(typeName); + } + if (ResolvedMetadataTypes.TryGetValue(typeName, out var cached)) { return cached; } var resolved = Type.GetType(typeName); - if (resolved != null && !resolved.Assembly.IsCollectible) + if (resolved != null && !resolved.IsCollectible) { - // A collectible type must not be retained by a process-wide cache; it would keep its - // AssemblyLoadContext alive and defeat runtime unload. + // IsCollectible also covers a permanent generic definition whose arguments come from + // a collectible context. Retaining that constructed type would prevent unload. ResolvedMetadataTypes.TryAdd(typeName, resolved); } diff --git a/tests/Graph.Age.Tests/GraphTests/AgeDeclaredIndexNamingIntegrationTests.cs b/tests/Graph.Age.Tests/GraphTests/AgeDeclaredIndexNamingIntegrationTests.cs index aac298d4..da98fa5f 100644 --- a/tests/Graph.Age.Tests/GraphTests/AgeDeclaredIndexNamingIntegrationTests.cs +++ b/tests/Graph.Age.Tests/GraphTests/AgeDeclaredIndexNamingIntegrationTests.cs @@ -133,6 +133,17 @@ await store.Graph.CreateRelationshipAsync( () => store.EnsureIndexesAsync(cancellationToken)); Assert.Contains("already has a label named", exception.Message, StringComparison.Ordinal); Assert.Contains(Label + "__idx", exception.Message, StringComparison.Ordinal); + + // The catalog is created before label provisioning. Failure must roll that DDL back, + // preserve the colliding user relationship and leave ordinary CRUD usable. + Assert.Equal(0, await TableCountAsync( + dataSource, graphName, AgeIndexMaintenance.CatalogTableName, cancellationToken)); + Assert.Equal(2, await store.Graph.Nodes().CountAsync(cancellationToken)); + Assert.Equal(1, await store.Graph.Relationships().CountAsync(cancellationToken)); + await store.Graph.CreateNodeAsync( + new NamingWidget { Name = "c", Region = "EU", Amount = 300 }, + cancellationToken: cancellationToken); + Assert.Equal(3, await store.Graph.Nodes().CountAsync(cancellationToken)); } [Fact] diff --git a/tests/Graph.Age.Tests/GraphTests/AgeNumericAggregateIntegrationTests.cs b/tests/Graph.Age.Tests/GraphTests/AgeNumericAggregateIntegrationTests.cs index f4b059b6..f2fa833e 100644 --- a/tests/Graph.Age.Tests/GraphTests/AgeNumericAggregateIntegrationTests.cs +++ b/tests/Graph.Age.Tests/GraphTests/AgeNumericAggregateIntegrationTests.cs @@ -96,6 +96,64 @@ await ScalarAsync( Assert.Equal(":2:450:400:500;aktiv:1:500:500:500;inaktiv:1:200:200:200;neu:1:700:700:700;", Format(afterCreate)); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DeclaredDerivedStateSharesTheCallerTransaction(bool commit) + { + var ct = TestContext.Current.CancellationToken; + await using var dataSource = CreateDataSource(); + var graphName = graphCleanup.CreateGraphName("cvoya_agg_transaction"); + await using var store = new AgeGraphStore(dataSource, graphName, CreateRegistry()); + await store.CreateGraphIfNotExistsAsync(ct); + graphCleanup.MarkGraphCreated(graphName); + var first = new Nul72AggWidget { Name = "a", Status = "old", Kaufpreis = 100 }; + var second = new Nul72AggWidget { Name = "b", Status = "old", Kaufpreis = 200 }; + await store.Graph.CreateNodeAsync(first, cancellationToken: ct); + await store.Graph.CreateNodeAsync(second, cancellationToken: ct); + await CreateAsync(store, "c", null, 300); + _ = await store.EnsureIndexesAsync(ct); + var before = Format(await StatsAsync(store.Graph, ct)); + Assert.Equal(":1:300:300:300;old:2:150:100:200;", before); + + await using (var transaction = await store.Graph.GetTransactionAsync(ct)) + { + Assert.Equal(1, await store.Graph.Nodes(transaction).Where(widget => widget.Name == first.Name).UpdateAsync( + setters => setters + .SetProperty(widget => widget.Status, "new") + .SetProperty(widget => widget.Kaufpreis, 400L), ct)); + Assert.Equal(1, await store.Graph.Nodes(transaction).Where(widget => widget.Name == second.Name).DeleteAsync(cancellationToken: ct)); + await store.Graph.CreateNodeAsync( + new Nul72AggWidget { Name = "d", Status = "new", Kaufpreis = 600 }, transaction, ct); + + Assert.Equal( + ":1:300:300:300;new:2:500:400:600;", + Format(await StatsAsync(store.Graph, ct, transaction))); + // A second connection must see the committed base rows and derived rows together. + Assert.Equal(before, Format(await StatsAsync(store.Graph, ct))); + if (commit) + { + await transaction.CommitAsync(); + } + else + { + await transaction.RollbackAsync(); + } + } + + var expected = commit ? ":1:300:300:300;new:2:500:400:600;" : before; + Assert.Equal(expected, Format(await StatsAsync(store.Graph, ct))); + var names = await store.Graph.Nodes() + .OrderBy(widget => widget.Name).Select(widget => widget.Name).ToListAsync(ct); + string[] expectedNames = commit ? ["a", "c", "d"] : ["a", "b", "c"]; + Assert.Equal(expectedNames, names); + Assert.Equal(commit ? 1300L : 600L, await ScalarAsync( + dataSource, $"SELECT sum(sum_value) FROM {graphName}.\"{AggregateTable}\"", ct)); + + _ = await store.DropIndexesAsync(ct); + Assert.Equal(expected, Format(await StatsAsync(store.Graph, ct))); + } + [Fact] public async Task TypeSafeAggregateDeclarationExecutesGroupedAggregate() { @@ -161,21 +219,22 @@ await store.Graph.CreateNodeAsync( private static async Task> StatsAsync( IGraph graph, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + IGraphTransaction? transaction = null) { - var counts = await graph.Nodes() + var counts = await graph.Nodes(transaction) .GroupBy(widget => widget.Status) .Select(group => new { group.Key, Count = group.Count() }) .ToListAsync(cancellationToken); - var averages = await graph.Nodes() + var averages = await graph.Nodes(transaction) .GroupBy(widget => widget.Status) .Select(group => new { group.Key, Value = group.Average(widget => widget.Kaufpreis) }) .ToListAsync(cancellationToken); - var minimums = await graph.Nodes() + var minimums = await graph.Nodes(transaction) .GroupBy(widget => widget.Status) .Select(group => new { group.Key, Value = group.Min(widget => widget.Kaufpreis) }) .ToListAsync(cancellationToken); - var maximums = await graph.Nodes() + var maximums = await graph.Nodes(transaction) .GroupBy(widget => widget.Status) .Select(group => new { group.Key, Value = group.Max(widget => widget.Kaufpreis) }) .ToListAsync(cancellationToken); diff --git a/tests/Graph.CompatibilityTests.Tests/ComplianceInventoryTests.cs b/tests/Graph.CompatibilityTests.Tests/ComplianceInventoryTests.cs index 1170ee66..1765d574 100644 --- a/tests/Graph.CompatibilityTests.Tests/ComplianceInventoryTests.cs +++ b/tests/Graph.CompatibilityTests.Tests/ComplianceInventoryTests.cs @@ -98,7 +98,8 @@ public sealed class ComplianceInventoryTests // domain data, external native rows, and read-only no-provision behavior. // +1 for NUL-75: deleting a node that only has an incoming user relationship must preflight // both directions (AGE 1.8 regression from the NUL-73 unidirectional fix). - private const int ExpectedTotalTestMethods = 502; + // +2: synchronous hierarchy/count composition and overlapping-edge delete preflight. + private const int ExpectedTotalTestMethods = 504; [Fact] public void TotalTestMethods_MatchesKnownSuiteSize() diff --git a/tests/Graph.Core.Tests/SerializationCacheFixtureAssembly.cs b/tests/Graph.Core.Tests/SerializationCacheFixtureAssembly.cs new file mode 100644 index 00000000..3c944ae3 --- /dev/null +++ b/tests/Graph.Core.Tests/SerializationCacheFixtureAssembly.cs @@ -0,0 +1,70 @@ +// Copyright CVOYA LLC. Licensed under the Apache License, Version 2.0. +// See LICENSE in the project root for full license terms. + +namespace Cvoya.Graph.Core.Tests; + +using System.Runtime.CompilerServices; +using System.Runtime.Loader; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +internal static class SerializationCacheFixtureAssembly +{ + private static readonly Lazy References = new(BuildReferences); + + internal static (byte[] Image, string AssemblyIdentity) Compile(string source) + { + var compilation = CSharpCompilation.Create( + $"SerializationCacheFixture_{Guid.NewGuid():N}", + [CSharpSyntaxTree.ParseText(source)], + References.Value, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + using var stream = new MemoryStream(); + var result = compilation.Emit(stream); + Assert.True(result.Success, string.Join('\n', result.Diagnostics)); + return (stream.ToArray(), compilation.Assembly.Identity.GetDisplayName()); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + internal static WeakReference LoadAndRun(byte[] image, Action action) + { + var context = new AssemblyLoadContext(name: null, isCollectible: true); + try + { + using var stream = new MemoryStream(image); + action(context, context.LoadFromStream(stream)); + } + finally + { + context.Unload(); + } + + return new WeakReference(context); + } + + internal static void AssertUnloaded(WeakReference contextReference) + { + // The loading/action frame has returned. Do not clear production caches: their lifetime is + // exactly what these tests exercise, rather than the factory/schema/serializer registries. + for (var attempt = 0; contextReference.IsAlive && attempt < 10; attempt++) + { + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); + GC.WaitForPendingFinalizers(); + } + + Assert.False(contextReference.IsAlive, "The result-materialization caches retained the collectible fixture."); + } + + private static MetadataReference[] BuildReferences() + { + var trustedAssemblies = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator); + return [ + .. trustedAssemblies + .Where(path => Path.GetFileName(path) is + "System.Private.CoreLib.dll" or "System.Runtime.dll" or "netstandard.dll") + .Select(path => (MetadataReference)MetadataReference.CreateFromFile(path)), + MetadataReference.CreateFromFile(typeof(Node).Assembly.Location), + ]; + } +} diff --git a/tests/Graph.Core.Tests/SerializationCacheIsolation.cs b/tests/Graph.Core.Tests/SerializationCacheIsolation.cs new file mode 100644 index 00000000..0edf0bb2 --- /dev/null +++ b/tests/Graph.Core.Tests/SerializationCacheIsolation.cs @@ -0,0 +1,11 @@ +// Copyright CVOYA LLC. Licensed under the Apache License, Version 2.0. +// See LICENSE in the project root for full license terms. + +namespace Cvoya.Graph.Core.Tests; + +// Loaded fixture types must disappear before another test's process-wide schema scan can see them. +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class SerializationCacheIsolation +{ + public const string Name = "SerializationCache"; +} diff --git a/tests/Graph.Core.Tests/SerializationCacheTests.cs b/tests/Graph.Core.Tests/SerializationCacheTests.cs new file mode 100644 index 00000000..c3ed3b48 --- /dev/null +++ b/tests/Graph.Core.Tests/SerializationCacheTests.cs @@ -0,0 +1,258 @@ +// Copyright CVOYA LLC. Licensed under the Apache License, Version 2.0. +// See LICENSE in the project root for full license terms. + +namespace Cvoya.Graph.Core.Tests; + +using System.Runtime.CompilerServices; +using System.Runtime.Loader; +using Cvoya.Graph.Serialization; +using Cvoya.Graph.Serialization.Results; + +[Collection(SerializationCacheIsolation.Name)] +public class SerializationCacheTests +{ + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void MetadataResolution_DoesNotRetainCollectibleGenericArguments(bool wireEntries, bool mapMetadata) + { + var fixture = SerializationCacheFixtureAssembly.Compile("public sealed class Payload;"); + var contextReference = SerializationCacheFixtureAssembly.LoadAndRun(fixture.Image, (context, assembly) => + { + var closedType = typeof(List<>).MakeGenericType(assembly.GetType("Payload", throwOnError: true)!); + Assert.False(closedType.Assembly.IsCollectible); + Assert.True(closedType.IsCollectible); + using var scope = context.EnterContextualReflection(); + for (var pass = 0; pass < 3; pass++) + { + Assert.Same(closedType, ResolveMetadata(closedType.AssemblyQualifiedName!, wireEntries, mapMetadata)); + } + }); + + SerializationCacheFixtureAssembly.AssertUnloaded(contextReference); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void MetadataResolution_RespectsContextAfterDefaultCacheWarmup(bool wireEntries, bool mapMetadata) + { + var fixture = SerializationCacheFixtureAssembly.Compile("public sealed class ContextualPayload;"); + using var defaultScope = AssemblyLoadContext.Default.EnterContextualReflection(); + using var stream = new MemoryStream(fixture.Image); + var defaultAssembly = AssemblyLoadContext.Default.LoadFromStream(stream); + var defaultType = defaultAssembly.GetType("ContextualPayload", throwOnError: true)!; + var typeName = defaultType.AssemblyQualifiedName!; + Assert.Same(defaultType, ResolveMetadata(typeName, wireEntries, mapMetadata)); + + var contextReference = SerializationCacheFixtureAssembly.LoadAndRun(fixture.Image, (context, assembly) => + { + var expected = assembly.GetType("ContextualPayload", throwOnError: true)!; + using var scope = context.EnterContextualReflection(); + Assert.NotSame(defaultType, expected); + Assert.Same(expected, Type.GetType(typeName)); + for (var pass = 0; pass < 3; pass++) + { + Assert.Same(expected, ResolveMetadata(typeName, wireEntries, mapMetadata)); + } + }); + + SerializationCacheFixtureAssembly.AssertUnloaded(contextReference); + Assert.Same(defaultType, ResolveMetadata(typeName, wireEntries, mapMetadata)); + } + + [Fact] + public void NodeProcessing_DoesNotRetainCollectibleGenericArguments() + { + var fixture = SerializationCacheFixtureAssembly.Compile("public sealed class Payload;"); + var contextReference = SerializationCacheFixtureAssembly.LoadAndRun(fixture.Image, (context, assembly) => + { + var closedType = typeof(SerializationCacheNode<>).MakeGenericType(assembly.GetType("Payload", throwOnError: true)!); + using var scope = context.EnterContextualReflection(); + var record = NodeRecord("GenericNode", new Dictionary + { + ["__metadata__"] = GraphValue.Scalar(closedType.AssemblyQualifiedName), + }); + var info = Process(record, typeof(Node)); + + Assert.Same(closedType, info.ActualType); + Assert.Contains(nameof(INode.Labels), info.SimpleProperties.Keys); + }); + + SerializationCacheFixtureAssembly.AssertUnloaded(contextReference); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void LabelDiscovery_DoesNotRetainCollectibleTargetTypes(bool genericTarget) + { + var fixture = SerializationCacheFixtureAssembly.Compile(""" + using Cvoya.Graph; + public sealed class Payload; + public sealed record LoadedNode : Node; + """); + var contextReference = SerializationCacheFixtureAssembly.LoadAndRun(fixture.Image, (_, assembly) => + { + var targetType = genericTarget + ? typeof(SerializationCacheNode<>).MakeGenericType(assembly.GetType("Payload", throwOnError: true)!) + : assembly.GetType("LoadedNode", throwOnError: true)!; + var info = Process(NodeRecord("LoadedNode"), targetType); + + Assert.Same(targetType, info.ActualType); + Assert.Contains(nameof(INode.Labels), info.SimpleProperties.Keys); + }); + + SerializationCacheFixtureAssembly.AssertUnloaded(contextReference); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void LabelDiscovery_RecoversAfterAssemblyLoads(bool relationship) + { + var label = $"SerializationCache_{Guid.NewGuid():N}"; + var fixture = SerializationCacheFixtureAssembly.Compile($$""" + using Cvoya.Graph; + [Node("{{label}}")] public sealed record LoadedNode : Node; + [Relationship("{{label}}")] public sealed record LoadedRelationship : Relationship; + """); + var targetType = relationship ? typeof(Relationship) : typeof(Node); + var record = relationship ? RelationshipRecord(label) : NodeRecord(label); + Assert.Same(targetType, Process(record, targetType).ActualType); + Assert.Same(targetType, Process(record, targetType).ActualType); + + var contextReference = SerializationCacheFixtureAssembly.LoadAndRun(fixture.Image, (_, assembly) => + { + var expected = assembly.GetType(relationship ? "LoadedRelationship" : "LoadedNode", throwOnError: true)!; + Assert.Same(expected, Process(record, targetType).ActualType); + Assert.Same(expected, Process(record, targetType).ActualType); + }); + + SerializationCacheFixtureAssembly.AssertUnloaded(contextReference); + Assert.Same(targetType, Process(record, targetType).ActualType); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WarmLabelDiscovery_ReusesSuccessfulIndexes(bool relationship) + { + var targetType = relationship ? typeof(Relationship) : typeof(Node); + var expectedType = relationship ? typeof(WarmRelationship) : typeof(WarmNode); + var record = relationship ? RelationshipRecord(expectedType.Name) : NodeRecord(expectedType.Name); + Assert.Same(expectedType, Process(record, targetType).ActualType); + Assert.Same(expectedType, Process(record, targetType).ActualType); + var buildsBefore = GraphResultProcessor.LabelIndexBuildCountForTesting(targetType); + + var assemblyLoads = 0; + AssemblyLoadEventHandler onAssemblyLoad = (_, _) => Interlocked.Increment(ref assemblyLoads); + AppDomain.CurrentDomain.AssemblyLoad += onAssemblyLoad; + try + { + for (var pass = 0; pass < 100; pass++) + { + Assert.Same(expectedType, Process(record, targetType).ActualType); + } + } + finally + { + AppDomain.CurrentDomain.AssemblyLoad -= onAssemblyLoad; + } + + // A warm-up can itself load an assembly and invalidate its index. After that first rebuild, + // each further rebuild must be justified by an observed assembly load, never by node count. + Assert.InRange( + GraphResultProcessor.LabelIndexBuildCountForTesting(targetType) - buildsBefore, + 0, + Volatile.Read(ref assemblyLoads) + 1); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void MetadataMiss_RecoversAfterAssemblyLoads(bool wireEntries, bool mapMetadata) + { + var fixture = SerializationCacheFixtureAssembly.Compile("public sealed class LoadedType;"); + var contextReference = ResolveMissingThenLoadedMetadata(fixture.Image, fixture.AssemblyIdentity, wireEntries, mapMetadata); + + SerializationCacheFixtureAssembly.AssertUnloaded(contextReference); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference ResolveMissingThenLoadedMetadata(byte[] image, string assemblyIdentity, bool wireEntries, bool mapMetadata) + { + var context = new AssemblyLoadContext(name: null, isCollectible: true); + try + { + using var scope = context.EnterContextualReflection(); + using var stream = new MemoryStream(image); + var typeName = $"LoadedType, {assemblyIdentity}"; + Assert.Null(ResolveMetadata(typeName, wireEntries, mapMetadata)); + Assert.Null(ResolveMetadata(typeName, wireEntries, mapMetadata)); + stream.Position = 0; + var assembly = context.LoadFromStream(stream); + var expected = assembly.GetType("LoadedType", throwOnError: true)!; + Assert.Same(expected, ResolveMetadata(typeName, wireEntries, mapMetadata)); + Assert.Same(expected, ResolveMetadata(typeName, wireEntries, mapMetadata)); + } + finally + { + context.Unload(); + } + + return new WeakReference(context); + } + + private static Type? ResolveMetadata(string typeName, bool wireEntries, bool mapMetadata) + { + if (wireEntries) + { + return GraphValueConverter.GetTypeFromMetadata(new Dictionary + { + ["__metadata__"] = mapMetadata + ? GraphValue.Map(new Dictionary { ["type"] = GraphValue.Scalar(typeName) }) + : GraphValue.Scalar(typeName), + }); + } + + return GraphValueConverter.GetTypeFromMetadata(new Dictionary + { + ["__metadata__"] = mapMetadata + ? new Dictionary { ["type"] = typeName } + : typeName, + }); + } + + private static GraphRecord NodeRecord(string label, Dictionary? properties = null) => + new(new Dictionary + { + ["Node"] = GraphValue.Map(new Dictionary + { + ["Node"] = GraphValue.Node("node", [label], properties ?? []), + ["ComplexProperties"] = GraphValue.List([]), + }), + }); + + private static GraphRecord RelationshipRecord(string label) => + new(new Dictionary + { + ["Relationship"] = GraphValue.Relationship("relationship", label, "start", "end", new Dictionary()), + }); + + private static EntityInfo Process(GraphRecord record, Type targetType) => + Assert.Single(new GraphResultProcessor(new EntityFactory()) + .ProcessAsync([record], targetType, TestContext.Current.CancellationToken).GetAwaiter().GetResult()); + + private sealed record WarmNode : Node; + + private sealed record WarmRelationship : Relationship; +} + +internal sealed record SerializationCacheNode : Node;