Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ jobs:
--configuration Release \
--lane age \
--no-build \
--coverage \
--disable-diff-engine \
--report-trx \
--results-directory "TestResults/age-${{ matrix.age }}"
Expand Down
9 changes: 9 additions & 0 deletions docs/provider-implementers-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions src/Graph.CompatibilityTests/IAggregationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,41 @@ public record PersonWithNumbers : Node
public Guid TrackingId { get; set; }
}

/// <summary>Certifies synchronous terminals across hierarchy, duplicate elimination and paging.</summary>
[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<Person>().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()
{
Expand Down
43 changes: 43 additions & 0 deletions src/Graph.CompatibilityTests/IGraphCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -940,6 +940,49 @@ await Assert.ThrowsAsync<InvalidOperationException>(() => Graph.FindNodeByTestKe
cancellationToken: TestContext.Current.CancellationToken);
}

/// <summary>Certifies atomic preflight and exact cascade counts for overlapping incident edges.</summary>
[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<Person>().Where(person => person.LastName == marker);

await Assert.ThrowsAsync<GraphException>(() => 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<Knows>(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<Knows>(relationship.TestKey).SingleOrDefaultAsync(ct));
}

_ = await Graph.FindNodeByTestKeyAsync<Person>(outside.TestKey, null, ct);
_ = await Graph.FindRelationshipByTestKeyAsync<Knows>(outsideLoop.TestKey, null, ct);
}

[Fact]
public async Task ExactOneEndpointSelection_ThrowsRoleSpecificCardinalityFailures()
{
Expand Down
21 changes: 12 additions & 9 deletions src/Graph.Serialization/Results/GraphResultProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ public sealed class GraphResultProcessor
private static readonly ConcurrentDictionary<Type, PropertyInfo?> LabelsProperties = new();
private static readonly ConcurrentDictionary<Type, int> LabelIndexBuildsForTests = new();
private static long _assemblyVersion;
private static Type[]? _knownConcreteTypes;
private static long _knownConcreteTypesVersion = -1;
private static ConcreteTypesSnapshot? _knownConcreteTypes;

static GraphResultProcessor()
{
Expand All @@ -38,6 +37,7 @@ static GraphResultProcessor()
}

private sealed record LabelIndex(long Version, Dictionary<string, Type> ByLabel);
private sealed record ConcreteTypesSnapshot(long Version, Type[] Types);

private static readonly List<ComplexProperty> NoComplexProperties = [];

Expand Down Expand Up @@ -1144,7 +1144,7 @@ private static void AddNodeLabelsProperty(
Type actualType,
IReadOnlyList<string> labels)
{
var labelsProperty = actualType.Assembly.IsCollectible
var labelsProperty = actualType.IsCollectible
? actualType.GetProperty(nameof(Graph.INode.Labels))
: LabelsProperties.GetOrAdd(
actualType,
Expand Down Expand Up @@ -1331,7 +1331,9 @@ private static Dictionary<string, Type> 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
Expand Down Expand Up @@ -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;
Expand Down
21 changes: 15 additions & 6 deletions src/Graph.Serialization/Results/GraphValueConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Collections.Concurrent;
using System.Globalization;
using System.Reflection;
using System.Runtime.Loader;

namespace Cvoya.Graph.Serialization.Results;

Expand All @@ -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<string, Type> ResolvedMetadataTypes = new(StringComparer.Ordinal);

public static object? ConvertTo(object? value, Type targetType)
Expand Down Expand Up @@ -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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<NamingWidget>().CountAsync(cancellationToken));
Assert.Equal(1, await store.Graph.Relationships<NamingWidgetCollidingRelationship>().CountAsync(cancellationToken));
await store.Graph.CreateNodeAsync(
new NamingWidget { Name = "c", Region = "EU", Amount = 300 },
cancellationToken: cancellationToken);
Assert.Equal(3, await store.Graph.Nodes<NamingWidget>().CountAsync(cancellationToken));
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,64 @@ await ScalarAsync(
Assert.Equal("<null>: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("<null>: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<Nul72AggWidget>(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<Nul72AggWidget>(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(
"<null>: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 ? "<null>: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<Nul72AggWidget>()
.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()
{
Expand Down Expand Up @@ -161,21 +219,22 @@ await store.Graph.CreateNodeAsync(

private static async Task<Dictionary<string, GroupStats>> StatsAsync(
IGraph graph,
CancellationToken cancellationToken)
CancellationToken cancellationToken,
IGraphTransaction? transaction = null)
{
var counts = await graph.Nodes<Nul72AggWidget>()
var counts = await graph.Nodes<Nul72AggWidget>(transaction)
.GroupBy(widget => widget.Status)
.Select(group => new { group.Key, Count = group.Count() })
.ToListAsync(cancellationToken);
var averages = await graph.Nodes<Nul72AggWidget>()
var averages = await graph.Nodes<Nul72AggWidget>(transaction)
.GroupBy(widget => widget.Status)
.Select(group => new { group.Key, Value = group.Average(widget => widget.Kaufpreis) })
.ToListAsync(cancellationToken);
var minimums = await graph.Nodes<Nul72AggWidget>()
var minimums = await graph.Nodes<Nul72AggWidget>(transaction)
.GroupBy(widget => widget.Status)
.Select(group => new { group.Key, Value = group.Min(widget => widget.Kaufpreis) })
.ToListAsync(cancellationToken);
var maximums = await graph.Nodes<Nul72AggWidget>()
var maximums = await graph.Nodes<Nul72AggWidget>(transaction)
.GroupBy(widget => widget.Status)
.Select(group => new { group.Key, Value = group.Max(widget => widget.Kaufpreis) })
.ToListAsync(cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading
Loading