Skip to content

Commit acc8e6a

Browse files
committed
Use native Orleans deep copies for owned command snapshots
Consume the verified published Communication 10.3.21 ownership repair. Replace the command snapshot binary round trip with the generated deep copier and validate the owned input once. Strengthen exact-byte and mutable-metadata ownership checks; retain original canonical case classifications and compiled source ranges. Add bounded real SDK mixed read/update phases and final complete body/revision checks. Preserve the physical read-cut contract and all journal acknowledgement guarantees. Validation: Debug solution build -warnaserror, format verification, governance and exact-source discovery of 3316 cases/five groups pass. Serialization 155, authorization 76, grouped commits 6 and queries 368 pass. Both two-host copy cases pass in later isolated/coupled runs; one initial hold-arrival timeout remains an open qualification issue with bounded counters. Query scope retains 12 unobserved ObjectDisposedException notices. Local 50k single-node and 20k three-node SDK scenarios pass. Matched zero-drop 2-second traces roughly halve snapshot-associated allocation weights; overall mixed throughput changes only about 2 percent and global allocation weights do not improve. No competitor win, Linux qualification, image or public benchmark claim.
1 parent 7265fd0 commit acc8e6a

11 files changed

Lines changed: 135 additions & 26 deletions

File tree

‎Directory.Packages.props‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010
<PackageVersion Include="ZoneTree" Version="2.0.6" />
1111
<PackageVersion Include="ZoneTree.Analytics" Version="1.0.2" />
1212
<PackageVersion Include="ZoneTree.FullTextSearch" Version="1.1.0" />
13-
<PackageVersion Include="ManagedCode.Communication" Version="10.3.20" />
14-
<PackageVersion Include="ManagedCode.Communication.AspNetCore" Version="10.3.20" />
15-
<PackageVersion Include="ManagedCode.Communication.Orleans" Version="10.3.20" />
13+
<PackageVersion Include="ManagedCode.Communication" Version="10.3.21" />
14+
<PackageVersion Include="ManagedCode.Communication.AspNetCore" Version="10.3.21" />
15+
<PackageVersion Include="ManagedCode.Communication.Orleans" Version="10.3.21" />
1616
<PackageVersion Include="ManagedCode.TimeSeries" Version="10.1.2" />
1717
<PackageVersion Include="ManagedCode.Storage.FileSystem" Version="10.1.7" />
1818
<PackageVersion Include="ManagedCode.Storage.Server" Version="10.1.7" />

‎docs/Features/InternalSerialization.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ selection, per-assembly provider cache, wire walker or field inspection codec.
1616
surrogate. All other active attributed DTOs use generated binary codecs.
1717

1818
Core owns model validation, canonical identity and persisted command outcomes.
19+
In-memory command snapshots use the native Orleans generated deep copier, with
20+
contract validation before and after copying. The owned encoded operation input
21+
is decoded once for its type and public-element validation. Mutable payload bytes
22+
and metadata remain independent of the caller; copying does not encode a new
23+
transport envelope or change persisted bytes, field IDs or aliases.
1924
Storage.ZoneTree owns physical metadata, WAL and file recovery. Orleans carries
2025
grain calls. ClientApi owns actual public JSON and authorized admission. MCP
2126
checks its actual decoded principal and projection limits rather than parsing

‎scripts/Features/CodeQuality/functional-coverage.unit-test-inventory.json‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22867,9 +22867,9 @@
2286722867
"methodName": "VerifiedSnapshotSurvivesCallerBufferMutationAndAppliesItsOriginalBody",
2286822868
"instanceName": "VerifiedSnapshotSurvivesCallerBufferMutationAndAppliesItsOriginalBody",
2286922869
"sourcePath": "tests/KeyLoad.FunctionalTests/InternalSerialization/Cases/RuntimeOperation/OperationOwnershipTests.cs",
22870-
"sourceSha256": "96c20b2d55db0a7fcdfc8a416906d1593ffe2b62d2c04a4b98908f1c7b648366",
22870+
"sourceSha256": "70f4c7a15e93ec2bcd4a2951c6e9ac10971d768236cdad816a50f996564ca227",
2287122871
"lineNumber": 5,
22872-
"endLineNumber": 31,
22872+
"endLineNumber": 40,
2287322873
"classification": "functional",
2287422874
"exclusionReason": null,
2287522875
"requirements": [
@@ -59774,9 +59774,9 @@
5977459774
"methodName": "OwnedSnapshotPreservesIndependentMetadataAndBusinessTime",
5977559775
"instanceName": "OwnedSnapshotPreservesIndependentMetadataAndBusinessTime",
5977659776
"sourcePath": "tests/KeyLoad.FunctionalTests/InternalSerialization/Cases/RuntimeOperation/OperationOwnershipTests.cs",
59777-
"sourceSha256": "96c20b2d55db0a7fcdfc8a416906d1593ffe2b62d2c04a4b98908f1c7b648366",
59778-
"lineNumber": 33,
59779-
"endLineNumber": 45,
59777+
"sourceSha256": "70f4c7a15e93ec2bcd4a2951c6e9ac10971d768236cdad816a50f996564ca227",
59778+
"lineNumber": 42,
59779+
"endLineNumber": 54,
5978059780
"classification": "required-non-contributor",
5978159781
"exclusionReason": null,
5978259782
"requirements": [

‎src/KeyLoad.Abstractions/InternalSerialization/Serialization/OrleansSerialization.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public static class OrleansSerialization
1313
{
1414
private static readonly ServiceProvider Services = CreateServices();
1515
internal static Serializer Serializer { get; } = Services.GetRequiredService<Serializer>();
16+
private static DeepCopier Copier { get; } = Services.GetRequiredService<DeepCopier>();
1617

1718
/// <summary>Encodes one nonnull owned value through the generated Orleans codec.</summary>
1819
/// <typeparam name="T">The attributed contract or scalar type.</typeparam>
@@ -26,6 +27,14 @@ internal static byte[] Serialize<T>(T value, ValidationProfile profile)
2627
return Serializer.SerializeToArray(new RuntimePayload { Version = PayloadVersion.Current, Value = value });
2728
}
2829

30+
internal static T Copy<T>(T value)
31+
{
32+
ContractValidation.Validate(value);
33+
var owned = Copier.Copy(value);
34+
ContractValidation.Validate(owned);
35+
return owned!;
36+
}
37+
2938
/// <summary>Encodes one owned value into a caller-owned bounded stream.</summary>
3039
/// <typeparam name="T">The attributed contract or scalar type.</typeparam>
3140
/// <param name="value">The nonnull value to encode.</param>

‎src/KeyLoad.Core/CommandExecution/Identity/CommandExecutionIdentity.cs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,26 @@ public static Command<DatabaseCommand> OwnCommand(this DatabaseEngine engine, Co
2323
internal static Command<DatabaseCommand> SnapshotCommand(Command<DatabaseCommand> operation)
2424
{
2525
ArgumentNullException.ThrowIfNull(operation);
26-
ValidateDatabaseCommand(operation);
27-
var owned = OrleansSerialization.Deserialize<Command<DatabaseCommand>>(OrleansSerialization.Serialize(operation));
26+
ValidateDatabaseCommandIdentity(operation);
27+
var owned = OrleansSerialization.Copy(operation);
2828
ValidateDatabaseCommand(owned);
2929
return owned;
3030
}
3131

3232
internal static void ValidateDatabaseCommand(Command<DatabaseCommand> operation)
33+
{
34+
ValidateDatabaseCommandIdentity(operation);
35+
var input = operation.Value!;
36+
_ = OrleansSerialization.Deserialize(input.Input.Span, (DatabaseCommandInputTypes.OperationPayloadType(input.Kind)).Value ?? throw Errors.Fail(ErrorCode.UnsupportedCapability, CommandExecutionValidation.UnsupportedDatabaseCommand), ValidationProfile.PublicInputElements);
37+
}
38+
39+
private static void ValidateDatabaseCommandIdentity(Command<DatabaseCommand> operation)
3340
{
3441
var input = operation.Value;
3542
if (operation.CommandId == Guid.Empty || string.IsNullOrWhiteSpace(operation.UserId) || operation.CommandType != DatabaseCommandType || operation.Timestamp.Kind != DateTimeKind.Utc || input is null || input.Input.IsEmpty || !Enum.IsDefined(input.Kind) || string.IsNullOrEmpty(input.Fingerprint) || input.Fingerprint.Length != FingerprintCharacters || input.Fingerprint.Any(character => !char.IsAsciiHexDigitLower(character)))
3643
{
3744
throw Errors.Fail(ErrorCode.Validation, InvalidDatabaseCommand);
3845
}
39-
40-
_ = OrleansSerialization.Deserialize(input.Input.Span, (DatabaseCommandInputTypes.OperationPayloadType(input.Kind)).Value ?? throw Errors.Fail(ErrorCode.UnsupportedCapability, CommandExecutionValidation.UnsupportedDatabaseCommand), ValidationProfile.PublicInputElements);
4146
}
4247

4348
internal static Command<DatabaseCommand> CreatePreparedCommand(this DatabaseEngine engine, OperationKind kind, Guid id, string principalId, DateTimeOffset evaluatedAt, ReadOnlyMemory<byte> input, string fingerprint, ReadExecutionBudget? work, IKeyValueView? admissionView = null)

‎tests/KeyLoad.ClusterTests/DocumentStorage/Fixtures/Diagnostics/DocumentPathDiagnosticCorpus.cs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,25 @@ internal static class DocumentPathDiagnosticCorpus
1010
internal const int ReadStride = 7919;
1111
private const int PayloadCharacters = 900;
1212
private static readonly string Payload = new('x', PayloadCharacters);
13+
private static readonly string UpdatedPayload = new('y', PayloadCharacters);
1314

1415
internal static string Id(int ordinal) => ordinal.ToString("D10", CultureInfo.InvariantCulture);
1516

1617
internal static string Json(int ordinal)
17-
=> string.Create(CultureInfo.InvariantCulture, $"{{\"number\":{ordinal},\"payload\":\"{Payload}\"}}");
18+
=> Body(ordinal, Payload);
19+
20+
internal static string UpdatedJson(int ordinal) => Body(ordinal, UpdatedPayload);
21+
22+
private static string Body(int ordinal, string payload)
23+
=> string.Create(CultureInfo.InvariantCulture, $"{{\"number\":{ordinal},\"payload\":\"{payload}\"}}");
1824

1925
internal static PartitionRef Partition() => new("diagnostic-" + Guid.NewGuid().ToString("N"),
2026
"documents", "documents", Guid.NewGuid().ToString("N"));
2127

22-
internal static void Require(string id, string json, int ordinal)
28+
internal static void Require(string id, string json, long revision, int ordinal, bool updated)
2329
{
24-
if (id != Id(ordinal) || json != Json(ordinal))
30+
if (id != Id(ordinal) || json != (updated ? UpdatedJson(ordinal) : Json(ordinal))
31+
|| revision != (updated ? 2L : 1L))
2532
{
2633
throw new InvalidOperationException("The diagnostic operation returned a different document identity or complete body.");
2734
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
using KeyLoad.Client;
2+
using KeyLoad.ClusterTests.StorageReplication;
3+
4+
namespace KeyLoad.ClusterTests.DocumentStorage;
5+
6+
internal static class DocumentPathDiagnosticMixed
7+
{
8+
private const int Pair = 2;
9+
private const long InitialRevision = 1;
10+
private const long UpdatedRevision = 2;
11+
12+
internal static Task ExecuteAsync(KeyLoadClient sdk, PartitionRef partition, int records, int nodes,
13+
CancellationToken token)
14+
=> Parallel.ForEachAsync(Enumerable.Range(0, records), Parallelism(token), async (operation, cancellation) =>
15+
{
16+
var ordinal = (int)((long)operation * DocumentPathDiagnosticCorpus.ReadStride % records);
17+
if (ordinal % Pair != 0)
18+
{
19+
await ReadAsync(sdk, partition, ordinal, updated: false, cancellation);
20+
return;
21+
}
22+
var id = DocumentPathDiagnosticCorpus.Id(ordinal);
23+
var receipt = ClusterReplicationTestSupport.Success(await sdk.CommitAsync(new(Guid.NewGuid(), partition,
24+
[new PutDocument(DocumentPathDiagnosticCorpus.Collection, id,
25+
DocumentPathDiagnosticCorpus.UpdatedJson(ordinal), InitialRevision)]), cancellation));
26+
if (receipt.PersistedCopies != nodes || receipt.Durability != DurabilityProfile.ProcessDurable
27+
|| receipt.Mutations is not [{ Kind: "putDocument", Revision: UpdatedRevision } mutation]
28+
|| mutation.Id != id || mutation.Resource != DocumentPathDiagnosticCorpus.Collection)
29+
{
30+
throw new InvalidOperationException("The diagnostic mixed acknowledgement changed its update or durable copies.");
31+
}
32+
});
33+
34+
internal static Task VerifyAsync(KeyLoadClient sdk, PartitionRef partition, int records, CancellationToken token)
35+
=> Parallel.ForEachAsync(Enumerable.Range(0, records), Parallelism(token), async (ordinal, cancellation) =>
36+
await ReadAsync(sdk, partition, ordinal, ordinal % Pair == 0, cancellation));
37+
38+
private static async Task ReadAsync(KeyLoadClient sdk, PartitionRef partition, int ordinal, bool updated,
39+
CancellationToken token)
40+
{
41+
var reference = new EntityRef(partition, DocumentPathDiagnosticCorpus.Collection, DocumentPathDiagnosticCorpus.Id(ordinal));
42+
var result = ClusterReplicationTestSupport.Success(await sdk.GetAsync(reference, token));
43+
var document = result.Document ?? throw new InvalidOperationException("An acknowledged mixed diagnostic document is missing.");
44+
DocumentPathDiagnosticCorpus.Require(document.Reference.Id, document.Json, document.Revision, ordinal, updated);
45+
}
46+
47+
private static ParallelOptions Parallelism(CancellationToken token)
48+
=> new() { MaxDegreeOfParallelism = DocumentPathDiagnosticCorpus.Clients, CancellationToken = token };
49+
}

‎tests/KeyLoad.ClusterTests/DocumentStorage/Fixtures/Diagnostics/DocumentPathDiagnosticScenario.cs‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ await ServerFailureObserver.ObserveAsync(async () =>
3131

3232
private static async Task ExecuteAsync(FunctionalGateFixture fixture, int records, int nodes, CancellationToken token)
3333
{
34+
var output = Path.Combine(AppContext.BaseDirectory, "performance-investigation",
35+
"documents-" + records + "-n" + nodes + "-" + Guid.NewGuid().ToString("N"));
36+
Directory.CreateDirectory(output);
37+
await Console.Out.WriteLineAsync("Local SDK diagnostic evidence: " + output);
3438
using var http = McpCallerHttp.Create(fixture.App, fixture.NodeNames[0]);
3539
http.DefaultRequestVersion = System.Net.HttpVersion.Version20;
3640
http.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
@@ -43,18 +47,18 @@ private static async Task ExecuteAsync(FunctionalGateFixture fixture, int record
4347
var failures = new List<Exception>();
4448
await ServerFailureObserver.ObserveAsync(async () =>
4549
{
46-
await MeasureAsync(phases, "bulk-create", records, () => LoadAsync(sdk, partition, records, nodes, token));
47-
await MeasureAsync(phases, "random-point-read", records, () => ReadAsync(sdk, partition, records, token));
48-
await MeasureAsync(phases, "point-predicate-query", QueryOperations,
50+
await MeasureAsync(output, phases, "bulk-create", records, () => LoadAsync(sdk, partition, records, nodes, token));
51+
await MeasureAsync(output, phases, "random-point-read", records, () => ReadAsync(sdk, partition, records, token));
52+
await MeasureAsync(output, phases, "point-predicate-query", QueryOperations,
4953
() => QueryAsync(sdk, partition, records, token));
54+
await MeasureAsync(output, phases, "mixed-point-read-update", records,
55+
() => DocumentPathDiagnosticMixed.ExecuteAsync(sdk, partition, records, nodes, token));
56+
await DocumentPathDiagnosticMixed.VerifyAsync(sdk, partition, records, token);
5057
}, failures);
5158
await ServerFailureObserver.ObserveAsync(async () =>
5259
{
53-
var output = Path.Combine(AppContext.BaseDirectory, "performance-investigation",
54-
"documents-" + records + "-n" + nodes + "-" + Guid.NewGuid().ToString("N"));
55-
Directory.CreateDirectory(output);
5660
await File.WriteAllBytesAsync(Path.Combine(output, "phases.json"), JsonDefaults.Serialize(phases), CancellationToken.None);
57-
await Console.Out.WriteLineAsync("Local SDK diagnostic evidence: " + output);
61+
await File.WriteAllTextAsync(Path.Combine(output, "active-phase.txt"), "settled", CancellationToken.None);
5862
}, failures);
5963
ServerFailureObserver.ThrowIfAny(failures);
6064
}
@@ -86,7 +90,7 @@ await Parallel.ForEachAsync(Enumerable.Range(0, records), Parallelism(token), as
8690
var reference = new EntityRef(partition, DocumentPathDiagnosticCorpus.Collection, DocumentPathDiagnosticCorpus.Id(ordinal));
8791
var result = ClusterReplicationTestSupport.Success(await sdk.GetAsync(reference, cancellation));
8892
var document = result.Document ?? throw new InvalidOperationException("An acknowledged diagnostic document is missing.");
89-
DocumentPathDiagnosticCorpus.Require(document.Reference.Id, document.Json, ordinal);
93+
DocumentPathDiagnosticCorpus.Require(document.Reference.Id, document.Json, document.Revision, ordinal, updated: false);
9094
});
9195
}
9296

@@ -103,15 +107,16 @@ await Parallel.ForEachAsync(Enumerable.Range(0, QueryOperations), Parallelism(to
103107
{
104108
throw new InvalidOperationException("The diagnostic point-predicate query has an incorrect access path or result cardinality.");
105109
}
106-
DocumentPathDiagnosticCorpus.Require(page.Rows[0].EntityId, page.Rows[0].Json, ordinal);
110+
DocumentPathDiagnosticCorpus.Require(page.Rows[0].EntityId, page.Rows[0].Json, page.Rows[0].Revision, ordinal, updated: false);
107111
});
108112
}
109113

110114
private static ParallelOptions Parallelism(CancellationToken token)
111115
=> new() { MaxDegreeOfParallelism = DocumentPathDiagnosticCorpus.Clients, CancellationToken = token };
112116

113-
private static async Task MeasureAsync(List<DocumentPathDiagnosticPhase> phases, string name, int operations, Func<Task> run)
117+
private static async Task MeasureAsync(string output, List<DocumentPathDiagnosticPhase> phases, string name, int operations, Func<Task> run)
114118
{
119+
await File.WriteAllTextAsync(Path.Combine(output, "active-phase.txt"), name, CancellationToken.None);
115120
await Console.Out.WriteLineAsync($"Local SDK diagnostic phase={name} operations={operations}");
116121
var started = TimeProvider.System.GetTimestamp();
117122
await run();

‎tests/KeyLoad.FunctionalTests/InternalSerialization/Cases/RuntimeOperation/OperationOwnershipTests.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,17 @@ public async Task VerifiedSnapshotSurvivesCallerBufferMutationAndAppliesItsOrigi
1717
var callerBytes = issued.Value!.Input.ToArray();
1818
var caller = database.Database.OwnCommand(issued);
1919
caller.Value = caller.Value! with { Input = callerBytes };
20+
caller.Metadata = new()
21+
{
22+
Tags = new() { [AuthorityFixture.Entity] = AuthorityFixture.Json },
23+
Properties = new() { [AuthorityFixture.Entity] = new byte[] { 1, 2, 3 } }
24+
};
25+
var original = OrleansSerialization.Serialize(caller);
2026
var verified = database.Database.OwnCommand(caller);
2127
Array.Clear(callerBytes);
28+
caller.Metadata.Tags[AuthorityFixture.Entity] = AuthorityFixture.InvalidJson;
29+
Array.Clear((byte[])caller.Metadata.Properties[AuthorityFixture.Entity]!);
30+
await Assert.That(OrleansSerialization.Serialize(verified).AsSpan().SequenceEqual(original)).IsTrue();
2231
var first = database.Database.Apply(verified);
2332
var replay = database.Database.Apply(database.Database.OwnCommand(verified));
2433
await Assert.That(Errors.Code(first.Problem).Value).IsNull();

‎tests/KeyLoad.FunctionalTests/StorageReplication/Observations/StorageOwnerDiscoveryCallFault.cs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,28 @@ internal sealed class StorageOwnerDiscoveryCallFault(Guid commandId) : IOutgoing
1313
private int refused;
1414
private int armed;
1515
private int cuts;
16+
private int unarmedCuts;
17+
private int prepared;
1618
internal Guid CommandId => commandId;
1719
internal TaskCompletionSource Arrived { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
1820
private TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
1921
internal int CutCalls => Volatile.Read(ref cuts);
22+
internal int UnarmedCutCalls => Volatile.Read(ref unarmedCuts);
23+
internal int PreparedCalls => Volatile.Read(ref prepared);
2024

2125
public async Task Invoke(IOutgoingGrainCallContext context)
2226
{
2327
if (context.InterfaceMethod.DeclaringType == typeof(ISiloDatabaseService))
2428
{
29+
if (context.MethodName == nameof(ISiloDatabaseService.ReadCutAsync)
30+
&& Volatile.Read(ref refused) != 0 && Volatile.Read(ref armed) == 0)
31+
{
32+
Interlocked.Increment(ref unarmedCuts);
33+
}
34+
if (context.MethodName == nameof(ISiloDatabaseService.PrepareBatchAsync) && Volatile.Read(ref armed) != 0)
35+
{
36+
Interlocked.Increment(ref prepared);
37+
}
2538
if (context.MethodName == nameof(ISiloDatabaseService.PrepareBatchAsync)
2639
&& context.Request.GetArgument(PayloadArgument) is ImmutableArray<Command<DatabaseCommand>> operations
2740
&& operations.Any(operation => operation.CommandId == commandId)

0 commit comments

Comments
 (0)