diff --git a/src/AquaSynth.Core/SpeechDistributedTraining.cs b/src/AquaSynth.Core/SpeechDistributedTraining.cs index ec994aa..4b8743a 100644 --- a/src/AquaSynth.Core/SpeechDistributedTraining.cs +++ b/src/AquaSynth.Core/SpeechDistributedTraining.cs @@ -32,7 +32,7 @@ public sealed record SpeechRenderResult( [property: CultName] string ResultId, [property: Key(1)] - [property: CultIndex("request")] + [property: CultRole("request")] string RequestId, [property: Key(2)] string WorkerId, [property: Key(3)] string RendererToolchain, @@ -150,7 +150,7 @@ public sealed record SpeechWorkerAdmissionReceipt( [property: CultName] string ReceiptId, [property: Key(1)] - [property: CultIndex("payload")] + [property: CultRole("payload")] string PayloadId, [property: Key(2)] string PeerId, [property: Key(3)] string LeaseId, diff --git a/src/AquaSynth.Faust/AquaSynthDaemonService.cs b/src/AquaSynth.Faust/AquaSynthDaemonService.cs index 3e34ca0..a01135b 100644 --- a/src/AquaSynth.Faust/AquaSynthDaemonService.cs +++ b/src/AquaSynth.Faust/AquaSynthDaemonService.cs @@ -95,14 +95,14 @@ public sealed record AquaSynthInstrumentOpenCommand( [MessagePackObject] public sealed record AquaSynthInstrumentControlCommand( [property: Key(0), CultName] string CommandId, - [property: Key(1), CultIndex("session")] string SessionId, + [property: Key(1), CultRole("session")] string SessionId, [property: Key(2)] Dictionary Controls); [CultDocument("aquasynth.command.instrument_block", AquaSynthDaemonSchemas.InstrumentBlockCommand)] [MessagePackObject] public sealed record AquaSynthInstrumentBlockCommand( [property: Key(0), CultName] string CommandId, - [property: Key(1), CultIndex("session")] string SessionId, + [property: Key(1), CultRole("session")] string SessionId, [property: Key(2)] int FrameCount = 128, [property: Key(3)] float Gain = 1.0f, [property: Key(4)] Dictionary? Controls = null); @@ -111,13 +111,13 @@ public sealed record AquaSynthInstrumentBlockCommand( [MessagePackObject] public sealed record AquaSynthInstrumentCloseCommand( [property: Key(0), CultName] string CommandId, - [property: Key(1), CultIndex("session")] string SessionId); + [property: Key(1), CultRole("session")] string SessionId); [CultDocument("aquasynth.compiled_instrument_session", AquaSynthDaemonSchemas.CompiledInstrumentSession)] [MessagePackObject] public sealed record AquaSynthCompiledInstrumentSession( [property: Key(0), CultName] string SessionId, - [property: Key(1), CultIndex("patch")] string PatchId, + [property: Key(1), CultRole("patch")] string PatchId, [property: Key(2)] string CompileKey, [property: Key(3)] string FaustName, [property: Key(4)] int Revision, @@ -134,7 +134,7 @@ public sealed record AquaSynthCompiledInstrumentSession( [MessagePackObject] public sealed record AquaSynthLiveInstrumentSessionState( [property: Key(0), CultName] string SessionId, - [property: Key(1), CultIndex("patch")] string PatchId, + [property: Key(1), CultRole("patch")] string PatchId, [property: Key(2)] string Status, [property: Key(3)] string OpenedAtUtc, [property: Key(4)] string UpdatedAtUtc, @@ -154,7 +154,7 @@ public sealed record AquaSynthLiveInstrumentSessionState( public sealed record AquaSynthPatchCompileReceipt( [property: Key(0), CultName] string ReceiptId, [property: Key(1), CultIndex("command")] string CommandId, - [property: Key(2), CultIndex("patch")] string PatchId, + [property: Key(2), CultRole("patch")] string PatchId, [property: Key(3)] string SessionId, [property: Key(4)] string Status, [property: Key(5)] string DecidedAtUtc, @@ -170,7 +170,7 @@ public sealed record AquaSynthPatchCompileReceipt( public sealed record AquaSynthRenderSampleReceipt( [property: Key(0), CultName] string RenderId, [property: Key(1), CultIndex("command")] string CommandId, - [property: Key(2), CultIndex("patch")] string PatchId, + [property: Key(2), CultRole("patch")] string PatchId, [property: Key(3)] string SessionId, [property: Key(4)] string Status, [property: Key(5)] string CompletedAtUtc, @@ -190,7 +190,7 @@ public sealed record AquaSynthRenderSampleReceipt( public sealed record AquaSynthAutomationStreamReceipt( [property: Key(0), CultName] string StreamRunId, [property: Key(1), CultIndex("command")] string CommandId, - [property: Key(2), CultIndex("patch")] string PatchId, + [property: Key(2), CultRole("patch")] string PatchId, [property: Key(3)] string SessionId, [property: Key(4)] string Status, [property: Key(5)] string CompletedAtUtc, @@ -210,8 +210,8 @@ public sealed record AquaSynthAutomationStreamReceipt( public sealed record AquaSynthInstrumentOpenReceipt( [property: Key(0), CultName] string ReceiptId, [property: Key(1), CultIndex("command")] string CommandId, - [property: Key(2), CultIndex("patch")] string PatchId, - [property: Key(3), CultIndex("session")] string SessionId, + [property: Key(2), CultRole("patch")] string PatchId, + [property: Key(3), CultRole("session")] string SessionId, [property: Key(4)] string Status, [property: Key(5)] string OpenedAtUtc, [property: Key(6)] int SampleRate, @@ -228,7 +228,7 @@ public sealed record AquaSynthInstrumentOpenReceipt( public sealed record AquaSynthInstrumentControlReceipt( [property: Key(0), CultName] string ReceiptId, [property: Key(1), CultIndex("command")] string CommandId, - [property: Key(2), CultIndex("session")] string SessionId, + [property: Key(2), CultRole("session")] string SessionId, [property: Key(3)] string Status, [property: Key(4)] string AppliedAtUtc, [property: Key(5)] int ControlCount, @@ -240,7 +240,7 @@ public sealed record AquaSynthInstrumentControlReceipt( public sealed record AquaSynthInstrumentBlockReceipt( [property: Key(0), CultName] string BlockId, [property: Key(1), CultIndex("command")] string CommandId, - [property: Key(2), CultIndex("session")] string SessionId, + [property: Key(2), CultRole("session")] string SessionId, [property: Key(3)] string Status, [property: Key(4)] string CompletedAtUtc, [property: Key(5)] ulong Sequence, @@ -258,7 +258,7 @@ public sealed record AquaSynthInstrumentBlockReceipt( public sealed record AquaSynthInstrumentCloseReceipt( [property: Key(0), CultName] string ReceiptId, [property: Key(1), CultIndex("command")] string CommandId, - [property: Key(2), CultIndex("session")] string SessionId, + [property: Key(2), CultRole("session")] string SessionId, [property: Key(3)] string Status, [property: Key(4)] string ClosedAtUtc, [property: Key(5)] bool Released, diff --git a/tests/AquaSynth.Dsl.Tests/CultIndexUniquenessTests.cs b/tests/AquaSynth.Dsl.Tests/CultIndexUniquenessTests.cs new file mode 100644 index 0000000..24afc9d --- /dev/null +++ b/tests/AquaSynth.Dsl.Tests/CultIndexUniquenessTests.cs @@ -0,0 +1,110 @@ +using System.Reflection; +using AquaSynth.Dsl; +using GameCult.Caching; +using GameCult.Caching.MessagePack; + +namespace AquaSynth.Dsl.Tests; + +// CultLib #90 (7760219b): [CultIndex] means unique, enforced at commit and load; [CultRole] names a many-row selection role. +// A member that two rows can share must be a role. The only [CultIndex] left is the CommandId of a receipt: every receipt is stored +// under a key derived from its CommandId alone (AquaSynthCultNetDaemon.*ReceiptKey), so a second row with that CommandId replaces the first. +public sealed class CultIndexUniquenessTests +{ + private static readonly string[] ReceiptTypes = + [ + nameof(AquaSynthPatchCompileReceipt), nameof(AquaSynthRenderSampleReceipt), nameof(AquaSynthAutomationStreamReceipt), nameof(AquaSynthInstrumentOpenReceipt), + nameof(AquaSynthInstrumentControlReceipt), nameof(AquaSynthInstrumentBlockReceipt), nameof(AquaSynthInstrumentCloseReceipt), + ]; + + [Fact] + public void TheOnlyCultIndexMembersAreReceiptCommandIds() + { + var indexed = new[] { typeof(AquaSynthDaemonService).Assembly, typeof(SpeechRenderResult).Assembly }.Distinct() + .SelectMany(assembly => assembly.GetTypes()) + .SelectMany(type => type.GetMembers(BindingFlags.Public | BindingFlags.Instance) + .Where(member => member is PropertyInfo or FieldInfo && member.GetCustomAttribute() is not null) + .Select(member => $"{type.Name}.{member.Name}")) + .OrderBy(name => name, StringComparer.Ordinal).ToArray(); + Assert.Equal(ReceiptTypes.Select(name => $"{name}.CommandId").OrderBy(name => name, StringComparer.Ordinal), indexed); + } + + [Fact] + public async Task ManyRowsMaySharePatchAndSessionAcrossDaemonDocuments() + { + var path = TempFile(); + try + { + using (var cache = await CultCacheMessagePack.OpenAsync(path)) + { + string[] paths = []; + for (var i = 0; i < 3; i++) + { + // Three commands, one patch, one session: the shape a client that opens, drives and closes one instrument produces. + await Put(cache, $"cmd-{i}-control", new AquaSynthInstrumentControlCommand($"cmd-{i}-control", "session-1", new Dictionary())); + await Put(cache, $"cmd-{i}-block", new AquaSynthInstrumentBlockCommand($"cmd-{i}-block", "session-1")); + await Put(cache, $"cmd-{i}-close", new AquaSynthInstrumentCloseCommand($"cmd-{i}-close", "session-1")); + await Put(cache, $"sess-{i}", new AquaSynthCompiledInstrumentSession($"sess-{i}", "patch-1", $"key-{i}", "f", 1, 48000, 0, 1, 128, 0.1f, "t", paths, paths)); + await Put(cache, $"live-{i}", new AquaSynthLiveInstrumentSessionState($"live-{i}", "patch-1", "open", "t", "t", "", 48000, 0, 1, 128, 1f, 0, new Dictionary(), "", "")); + await Put(cache, $"cmd-{i}-compile", new AquaSynthPatchCompileReceipt($"cmd-{i}-compile", $"cmd-{i}", "patch-1", "session-1", "succeeded", "t", "k", 1, paths, paths)); + await Put(cache, $"cmd-{i}-render", new AquaSynthRenderSampleReceipt($"cmd-{i}-render", $"cmd-{i}", "patch-1", "session-1", "succeeded", "t", 48000, 1, 0.1f, 0, 0, "", "", "")); + await Put(cache, $"cmd-{i}-stream", new AquaSynthAutomationStreamReceipt($"cmd-{i}-stream", $"cmd-{i}", "patch-1", "session-1", "succeeded", "t", "v", "a", "c", 48000, 128, 1, [], [])); + await Put(cache, $"cmd-{i}-open", new AquaSynthInstrumentOpenReceipt($"cmd-{i}-open", $"cmd-{i}", "patch-1", "session-1", "succeeded", "t", 48000, 0, 1, 128, paths, paths)); + await Put(cache, $"cmd-{i}-ctl", new AquaSynthInstrumentControlReceipt($"cmd-{i}-ctl", $"cmd-{i}", "session-1", "applied", "t", 0)); + await Put(cache, $"cmd-{i}-blk", new AquaSynthInstrumentBlockReceipt($"cmd-{i}-blk", $"cmd-{i}", "session-1", "succeeded", "t", 0, 48000, 128, 0, 0, "", "")); + await Put(cache, $"cmd-{i}-cls", new AquaSynthInstrumentCloseReceipt($"cmd-{i}-cls", $"cmd-{i}", "session-1", "closed", "t", true)); + } + + await cache.FlushAsync(); + } + + // Reopening hydrates and revalidates: a unique index would refuse the file here. + using var reloaded = await CultCacheMessagePack.OpenAsync(path); + Assert.Equal(3, reloaded.GetAll().Count()); + Assert.Equal(3, reloaded.GetAll().Count(session => session.PatchId == "patch-1")); + Assert.Equal(3, reloaded.GetAll().Count(receipt => receipt.SessionId == "session-1" && receipt.PatchId == "patch-1")); + Assert.Equal(3, reloaded.GetAll().Count(receipt => receipt.SessionId == "session-1")); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public async Task OneRowPerCommandIdPerReceiptType() + { + var path = TempFile(); + try + { + using var cache = await CultCacheMessagePack.OpenAsync(path); + string[] paths = []; + AquaSynthPatchCompileReceipt Receipt(string command, string status) => + new(AquaSynthCultNetDaemon.CompileReceiptKey(command).Value, command, "patch-1", "session-1", status, "t", "k", 1, paths, paths); + foreach (var (command, status) in new[] { ("a", "failed"), ("a", "succeeded"), ("b", "succeeded") }) + { + var receipt = Receipt(command, status); + await cache.UpsertAsync(receipt, new CultRecordHandle(AquaSynthCultNetDaemon.CompileReceiptKey(command))); + } + + // A retried command replaces its own receipt; it cannot add a second row that carries the same CommandId. + var all = cache.GetAll().OrderBy(receipt => receipt.CommandId, StringComparer.Ordinal).ToArray(); + Assert.Equal(["a", "b"], all.Select(receipt => receipt.CommandId)); + Assert.Equal("succeeded", all[0].Status); + foreach (var kind in new Func[] { AquaSynthCultNetDaemon.CompileReceiptKey, AquaSynthCultNetDaemon.RenderReceiptKey, AquaSynthCultNetDaemon.StreamReceiptKey, + AquaSynthCultNetDaemon.OpenReceiptKey, AquaSynthCultNetDaemon.ControlReceiptKey, AquaSynthCultNetDaemon.BlockReceiptKey, AquaSynthCultNetDaemon.CloseReceiptKey }) + { + Assert.NotEqual(kind("a"), kind("b")); + Assert.Equal(kind("a"), kind("a")); + } + } + finally + { + File.Delete(path); + } + } + + private static Task Put(CultCache cache, string key, T document) where T : class => + cache.UpsertAsync(document, new CultRecordHandle(new CultRecordKey(key))); + + private static string TempFile() => Path.Combine(Path.GetTempPath(), $"aquasynth-cultindex-{Guid.NewGuid():N}.cc"); +} diff --git a/tests/AquaSynth.Dsl.Tests/SpeechDistributedTrainingTests.cs b/tests/AquaSynth.Dsl.Tests/SpeechDistributedTrainingTests.cs index 4c06e7a..15f564c 100644 --- a/tests/AquaSynth.Dsl.Tests/SpeechDistributedTrainingTests.cs +++ b/tests/AquaSynth.Dsl.Tests/SpeechDistributedTrainingTests.cs @@ -180,6 +180,8 @@ public sealed class SpeechDistributedTrainingTests Assert.True(after < before, $"expected CultMesh worker gradients to reduce loss; before={before}, after={after}"); Assert.Single(payloads); Assert.Equal(SpeechCultMeshRoles.RenderWorker, payloads[0].WorkerRole); + // One payload, four receipts: PayloadId is a role (many rows share it), not a unique index (CultLib #90). + Assert.Equal(4, admissions.Count(receipt => receipt.PayloadId == "payload-cultmesh-0001")); Assert.Equal(2, admissions.Count(receipt => receipt.Status == SpeechWorkerAdmissionStatus.Admitted)); Assert.Equal(2, admissions.Count(receipt => receipt.Status == SpeechWorkerAdmissionStatus.Rejected)); Assert.All(admissions.Where(receipt => receipt.Status == SpeechWorkerAdmissionStatus.Admitted), receipt => Assert.NotEmpty(receipt.AssignedRequestIds)); @@ -284,6 +286,30 @@ public sealed class SpeechDistributedTrainingTests return loss / actual.Count; } + [Fact] + public async Task OneRequestMayHaveAFailedAndAScoredResultInTheSameStore() + { + var directory = TempDirectory(); + try + { + var resultStore = Path.Combine(directory, "speech-results.cc"); + var request = SpeechDistributedTrainingCoordinator.CreateRenderRequests("batch-roles", Pipeline(), TrainingSet())[0]; + var scored = SpeechDistributedTrainingCoordinator.ScoreControlVectorRequests([request], "worker-a"); + var failed = SpeechDistributedTrainingCoordinator.ScoreControlVectorRequests([request with { CandidateControlVector = [] }], "worker-b"); + await SpeechDistributedTrainingCultCacheStore.UpsertResultsAsync(resultStore, [.. scored, .. failed]); + + // RequestId is a role: a retried request keeps its failed result beside the later scored one (CultLib #90 makes CultIndex unique). + var loaded = await SpeechDistributedTrainingCultCacheStore.ReadResultsAsync(resultStore); + Assert.Equal(2, loaded.Count(result => result.RequestId == request.RequestId)); + Assert.Contains(loaded, result => result.Status == SpeechRenderStatus.Failed); + Assert.Contains(loaded, result => result.Status == SpeechRenderStatus.Succeeded); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + private static string TempDirectory() { var path = Path.Combine(Path.GetTempPath(), $"aquasynth-speech-distributed-{Guid.NewGuid():N}");