From 165ecfc443da367b521a6d52904e91bab74f0c8e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 22 Jul 2026 00:12:13 +0100 Subject: [PATCH] Defer Aetheria worlds until client activation --- Aetheria.State.Daemon/Program.cs | 115 +++++++++++++----- Aetheria.State.Verify/Program.cs | 23 +++- .../Editor/AetheriaDaemonDevelopmentWindow.cs | 26 ++-- docs/unity-daemon-development.md | 19 ++- 4 files changed, 130 insertions(+), 53 deletions(-) diff --git a/Aetheria.State.Daemon/Program.cs b/Aetheria.State.Daemon/Program.cs index 0072bdd90..e1b0bd128 100644 --- a/Aetheria.State.Daemon/Program.cs +++ b/Aetheria.State.Daemon/Program.cs @@ -73,10 +73,6 @@ if (persistedRuntimeCatalog == null || nativeCatalogChanged) await node.RefreshRuntimeCatalogAsync().ConfigureAwait(false); TraceStartup("runtime-catalog"); -await EnsurePlayableRunDocumentsAsync(node, options, startedAtUtc, latestFrame).ConfigureAwait(false); -TraceStartup("playable-run"); -await EnsureGameSessionAsync(node, options, startedAtUtc, latestFrame).ConfigureAwait(false); -TraceStartup("game-session"); var verseHost = await EnsureVerseHostSettingsAsync(node, options, startedAtUtc).ConfigureAwait(false); TraceStartup("verse-host"); await EnsureVerseAuthorityPolicyAsync(node, options).ConfigureAwait(false); @@ -86,13 +82,86 @@ await PublishRuntimeSessionAsync(node, options, startedAtUtc, "starting").Config TraceStartup("runtime-session"); await PublishStateSurfacesAsync(node, options, startedAtUtc).ConfigureAwait(false); TraceStartup("state-surfaces"); +var ingressState = new AetheriaDaemonIngressState(); +await RefreshControlPlaneInputsAsync(node, ingressState).ConfigureAwait(false); +await using var cultMeshClientHost = await StartClientCultMeshHostAsync( + node, options, unityBundles, () => latestFrame).ConfigureAwait(false); +TraceStartup("client-host"); +Console.WriteLine($"Aetheria client CultMesh endpoint: {cultMeshClientHost.ControlEndpoint}"); +Console.WriteLine($"Aetheria client CDN endpoint: {cultMeshClientHost.ContentEndpoint}"); +Console.WriteLine($"Aetheria client realtime endpoint: {cultMeshClientHost.RealtimeEndpoint}"); +Console.WriteLine($"Aetheria daemon transport-ready in {startup.Elapsed.TotalMilliseconds:0.###}ms."); +using var clientSubscriptions = new CultNetDatabaseSubscriptionServer(cultMeshClientHost.Control, node.Database); +var playableWorldRequested = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); +clientSubscriptions.DemandChanged += demand => +{ + if (RequestsPlayableWorld(demand)) + playableWorldRequested.TrySetResult(null); +}; +var managedViewportDemand = new AetheriaManagedViewportDemandState(); +clientSubscriptions.DemandChanged += managedViewportDemand.Observe; +if (traceClientTransport) + clientSubscriptions.DemandChanged += demand => Console.WriteLine( + $"CultMesh state demand consumer={demand.ConsumerRuntimeId} subscription={demand.SubscriptionId} " + + $"active={demand.Active} sameMachine={demand.SameMachine} " + + $"records=[{string.Join(",", demand.RecordKeys)}] schemas=[{string.Join(",", demand.SchemaIds)}] " + + $"bodies=[{string.Join(",", demand.BodyIds)}] transports=[{string.Join(",", demand.SupportedBodyTransports)}]"); +using var bodyDemand = new CultMeshBodyDemandTracker(clientSubscriptions); +using var soaPublisher = new AetheriaRuntimeDaemonSoaFramePublisher( + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + bodyDemand); +var stopped = new TaskCompletionSource(); +Console.CancelKeyPress += (_, eventArgs) => +{ + eventArgs.Cancel = true; + stopped.TrySetResult(null); +}; + +if (!options.Once && !options.UseTerminusFixture) +{ + await PublishRuntimeSessionAsync(node, options, startedAtUtc, "ready").ConfigureAwait(false); + Console.WriteLine("Aetheria daemon ready; waiting for a client to load or generate a world."); + while (!stopped.Task.IsCompleted) + { + ThrowIfClientHostFaulted(cultMeshClientHost); + await AcceptCoreEveInvocationsAsync(node, options, latestFrame).ConfigureAwait(false); + await AcceptEveCommandsAsync(node, options, ingressState).ConfigureAwait(false); + if (await ApplyRequestedNewGameSessionAsync(node, options).ConfigureAwait(false)) + { + latestFrame = null; + break; + } + + if (playableWorldRequested.Task.IsCompleted && + (HasPlayableRun(latestFrame?.Run) || + HasPlayableRun(await ReadRuntimeRunCheckpointAsync(node, options.RenderSettings).ConfigureAwait(false)))) + break; + + var completed = await Task.WhenAny(stopped.Task, Task.Delay(options.TickInterval)).ConfigureAwait(false); + if (completed == stopped.Task) + break; + } + + if (stopped.Task.IsCompleted) + { + await PublishRuntimeSessionAsync(node, options, startedAtUtc, "stopped").ConfigureAwait(false); + return; + } +} +else +{ + await EnsurePlayableRunDocumentsAsync(node, options, startedAtUtc, latestFrame).ConfigureAwait(false); + TraceStartup("playable-run"); +} + +await EnsureGameSessionAsync(node, options, startedAtUtc, latestFrame).ConfigureAwait(false); +TraceStartup("game-session"); using var physicsPersistence = await AetheriaYmirPersistenceCoordinator.OpenAsync( node, worldPhysics, latestFrame).ConfigureAwait(false); TraceStartup("ymir-persistence"); var nextApiPublicationUtc = DateTimeOffset.UtcNow; -var ingressState = new AetheriaDaemonIngressState(); var hotState = new AetheriaHotEntityPublicationState(); var reactiveSurfaceState = new AetheriaReactiveSurfacePublicationState(); var publishRestoredFrame = !options.Once && @@ -133,26 +202,6 @@ if (!publishRestoredFrame) publishTopology: true).ConfigureAwait(false); } TraceStartup("client-bootstrap"); -await using var cultMeshClientHost = await StartClientCultMeshHostAsync( - node, options, unityBundles, () => latestFrame).ConfigureAwait(false); -TraceStartup("client-host"); -Console.WriteLine($"Aetheria client CultMesh endpoint: {cultMeshClientHost.ControlEndpoint}"); -Console.WriteLine($"Aetheria client CDN endpoint: {cultMeshClientHost.ContentEndpoint}"); -Console.WriteLine($"Aetheria client realtime endpoint: {cultMeshClientHost.RealtimeEndpoint}"); -Console.WriteLine($"Aetheria daemon transport-ready in {startup.Elapsed.TotalMilliseconds:0.###}ms."); -using var clientSubscriptions = new CultNetDatabaseSubscriptionServer(cultMeshClientHost.Control, node.Database); -var managedViewportDemand = new AetheriaManagedViewportDemandState(); -clientSubscriptions.DemandChanged += managedViewportDemand.Observe; -if (traceClientTransport) - clientSubscriptions.DemandChanged += demand => Console.WriteLine( - $"CultMesh state demand consumer={demand.ConsumerRuntimeId} subscription={demand.SubscriptionId} " + - $"active={demand.Active} sameMachine={demand.SameMachine} " + - $"records=[{string.Join(",", demand.RecordKeys)}] schemas=[{string.Join(",", demand.SchemaIds)}] " + - $"bodies=[{string.Join(",", demand.BodyIds)}] transports=[{string.Join(",", demand.SupportedBodyTransports)}]"); -using var bodyDemand = new CultMeshBodyDemandTracker(clientSubscriptions); -using var soaPublisher = new AetheriaRuntimeDaemonSoaFramePublisher( - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), - bodyDemand); ThrowIfClientHostFaulted(cultMeshClientHost); await PublishHotEntityStateAsync( node, soaPublisher, hotState, latestFrame!, ingressState.Catalog, cultMeshClientHost).ConfigureAwait(false); @@ -180,13 +229,6 @@ if (options.Once) await PublishRuntimeSessionAsync(node, options, startedAtUtc, "completed").ConfigureAwait(false); return; } -var stopped = new TaskCompletionSource(); -Console.CancelKeyPress += (_, eventArgs) => -{ - eventArgs.Cancel = true; - stopped.TrySetResult(null); -}; - await PublishRuntimeSessionAsync(node, options, startedAtUtc, "running").ConfigureAwait(false); Console.WriteLine("Aetheria Verse daemon is running. Press Ctrl+C to stop."); @@ -258,6 +300,15 @@ static void ThrowIfClientHostFaulted(AetheriaClientCultMeshHost host) host.Realtime.BackgroundFailure.GetAwaiter().GetResult()); } +static bool RequestsPlayableWorld(CultNetDatabaseSubscriptionDemand demand) => + demand.Active && + (demand.RecordKeys.Any(key => + string.Equals(key, AetheriaRuntimeVerseRecordKeys.DaemonFrameLatest.ToString(), StringComparison.Ordinal) || + string.Equals(key, AetheriaRuntimeVerseRecordKeys.DaemonGameSurface.ToString(), StringComparison.Ordinal) || + string.Equals(key, AetheriaRuntimeVerseRecordKeys.DaemonGameReactiveSurface.ToString(), StringComparison.Ordinal)) || + demand.SchemaIds.Contains(AetheriaRuntimeDaemonSchemas.Frame, StringComparer.Ordinal) || + demand.BodyIds.Contains(AetheriaRuntimeDaemonSoaFramePublisher.BodyId, StringComparer.Ordinal)); + static async Task TickAsync( AetheriaStateNode node, AetheriaDaemonHostOptions options, diff --git a/Aetheria.State.Verify/Program.cs b/Aetheria.State.Verify/Program.cs index cd7609bb1..f5617d339 100644 --- a/Aetheria.State.Verify/Program.cs +++ b/Aetheria.State.Verify/Program.cs @@ -1339,9 +1339,23 @@ static void RequireClientTransportPlaneOwnership(string root) var clientHostIndex = daemon.IndexOf( "await using var cultMeshClientHost = await StartClientCultMeshHostAsync(", StringComparison.Ordinal); - if (restoreIndex < 0 || clientHostIndex < 0 || clientHostIndex < restoreIndex) + var readyGateIndex = daemon.IndexOf( + "if (!options.Once && !options.UseTerminusFixture)", + StringComparison.Ordinal); + var demandIndex = daemon.IndexOf( + "var playableWorldRequested = new TaskCompletionSource", + StringComparison.Ordinal); + var gameSessionIndex = daemon.IndexOf( + "await EnsureGameSessionAsync(node, options, startedAtUtc, latestFrame)", + StringComparison.Ordinal); + if (restoreIndex < 0 || clientHostIndex < 0 || readyGateIndex < 0 || demandIndex < 0 || gameSessionIndex < 0 || + clientHostIndex > readyGateIndex || demandIndex > readyGateIndex || + readyGateIndex > gameSessionIndex || gameSessionIndex > restoreIndex || + !daemon.Contains("Aetheria daemon ready; waiting for a client to load or generate a world.", StringComparison.Ordinal) || + !daemon.Contains("if (playableWorldRequested.Task.IsCompleted", StringComparison.Ordinal) || + !daemon.Contains("if (await ApplyRequestedNewGameSessionAsync(node, options)", StringComparison.Ordinal)) throw new InvalidOperationException( - "Aetheria client transport must not listen before daemon-private Ymir restoration succeeds."); + "Aetheria daemon startup must expose transport in ready mode and defer game-session/Ymir activation until playable-world demand or New Game."); var requiredEditorResetSymbols = new[] { @@ -1360,8 +1374,9 @@ static void RequireClientTransportPlaneOwnership(string root) !editorController.Contains("public static void Start()", StringComparison.Ordinal) || !editorController.Contains("public static void Build(bool forceImport = false)", StringComparison.Ordinal) || !editorController.Contains("Process.Start(startInfo)", StringComparison.Ordinal) || - !editorController.Contains("new ProcessStartInfo(DotNetExePath, arguments)", StringComparison.Ordinal) || + !editorController.Contains("new ProcessStartInfo(DaemonExePath, arguments)", StringComparison.Ordinal) || !editorController.Contains("DOTNET_ROOT", StringComparison.Ordinal) || + !editorController.Contains("DOTNET_ROOT_X64", StringComparison.Ordinal) || !editorController.Contains("_status = \"Debug daemon prepared\"", StringComparison.Ordinal) || !editorController.Contains("SessionState.SetInt(ProcessIdSessionKey, daemon.Id)", StringComparison.Ordinal) || editorController.Contains("playModeStateChanged", StringComparison.Ordinal) || @@ -1371,7 +1386,7 @@ static void RequireClientTransportPlaneOwnership(string root) throw new InvalidOperationException( "The daemon window must independently build and launch through the system .NET host without coupling either operation to Unity Play lifecycle."); - Console.WriteLine("Client transport ownership: Ymir restores before transport listen; the daemon window owns an independent prepared Debug daemon and matching private state"); + Console.WriteLine("Client transport ownership: ready transport precedes demand-gated game/Ymir activation; the daemon window owns an independent prepared Debug apphost and matching private state"); } static void RequireDaemonPlayableRunGenerationAuthority(string root) diff --git a/Aetheria.Unity/Assets/Editor/AetheriaDaemonDevelopmentWindow.cs b/Aetheria.Unity/Assets/Editor/AetheriaDaemonDevelopmentWindow.cs index e1cb41b86..83c36994a 100644 --- a/Aetheria.Unity/Assets/Editor/AetheriaDaemonDevelopmentWindow.cs +++ b/Aetheria.Unity/Assets/Editor/AetheriaDaemonDevelopmentWindow.cs @@ -188,7 +188,7 @@ namespace Aetheria.Editor public static bool IsRunning => TryRefreshDaemon(); public static bool IsStarting => _launcher != null && !_launcher.HasExited; - public static bool IsPrepared => File.Exists(DaemonDllPath) && File.Exists(DotNetExePath); + public static bool IsPrepared => File.Exists(DaemonExePath) && Directory.Exists(DotNetRootPath); public static string Status => _status; public static string LastError => _lastError; public static string Endpoint => $"cultnet+tcp://127.0.0.1:{Port}"; @@ -205,10 +205,10 @@ namespace Aetheria.Editor private static string ErrorLogPath => Path.Combine(ArtifactsRoot, "daemon.error.log"); private static string LauncherLogPath => Path.Combine(ArtifactsRoot, "launcher.log"); private static string LauncherErrorPath => Path.Combine(ArtifactsRoot, "launcher.error.log"); - private static string DaemonDllPath => Path.Combine( - ProjectRoot, "Aetheria.State.Daemon", "bin", "Debug", "net10.0", "Aetheria.State.Daemon.dll"); - private static string DotNetExePath => Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "dotnet", "dotnet.exe"); + private static string DaemonExePath => Path.Combine( + ProjectRoot, "Aetheria.State.Daemon", "bin", "Debug", "net10.0", "Aetheria.State.Daemon.exe"); + private static string DotNetRootPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "dotnet"); public static void Start() { @@ -536,21 +536,22 @@ namespace Aetheria.Editor private static void LaunchDaemon() { - if (!File.Exists(DaemonDllPath)) - throw new FileNotFoundException("Prepared Aetheria Debug daemon is missing. Use Build daemon first.", DaemonDllPath); - if (!File.Exists(DotNetExePath)) - throw new FileNotFoundException("The system .NET host required by the Aetheria daemon is missing.", DotNetExePath); + if (!File.Exists(DaemonExePath)) + throw new FileNotFoundException("Prepared Aetheria Debug daemon is missing. Use Build daemon first.", DaemonExePath); + if (!Directory.Exists(DotNetRootPath)) + throw new DirectoryNotFoundException( + $"The system .NET runtime root required by the Aetheria daemon is missing: {DotNetRootPath}"); File.WriteAllText(LogPath, ""); File.WriteAllText(ErrorLogPath, ""); var arguments = - $"{Quote(DaemonDllPath)} --root {Quote(ProjectRoot)} " + + $"--root {Quote(ProjectRoot)} " + $"--state {Quote(StatePath)} " + "--client-cultmesh-host 127.0.0.1 " + "--client-cultmesh-advertise-host 127.0.0.1 " + $"--client-cultmesh-port {Port} " + "--tick-interval-ms 20 --fixed-delta-ms 20 --no-odin-announcements"; - var startInfo = new ProcessStartInfo(DotNetExePath, arguments) + var startInfo = new ProcessStartInfo(DaemonExePath, arguments) { WorkingDirectory = ProjectRoot, UseShellExecute = false, @@ -558,7 +559,8 @@ namespace Aetheria.Editor RedirectStandardOutput = true, RedirectStandardError = true }; - startInfo.EnvironmentVariables["DOTNET_ROOT"] = Path.GetDirectoryName(DotNetExePath); + startInfo.EnvironmentVariables["DOTNET_ROOT"] = DotNetRootPath; + startInfo.EnvironmentVariables["DOTNET_ROOT_X64"] = DotNetRootPath; startInfo.EnvironmentVariables.Remove("DOTNET_HOST_PATH"); var daemon = Process.Start(startInfo) ?? throw new InvalidOperationException("Aetheria Debug daemon process did not start."); diff --git a/docs/unity-daemon-development.md b/docs/unity-daemon-development.md index 0c95ff020..58383a88a 100644 --- a/docs/unity-daemon-development.md +++ b/docs/unity-daemon-development.md @@ -7,20 +7,29 @@ the automated integration proof and is not required for ordinary iteration. **Build daemon** explicitly builds `Aetheria.State.Daemon` in `bin/Debug/net10.0`. **Reimport state & build** also replaces the isolated development state under `Aetheria.Unity/Build`. **Start daemon** launches the -already-prepared DLL immediately; it never performs a build. The editor owns +already-prepared Debug apphost immediately; it never performs a build. The editor owns the daemon process, its PID, and its output streams. The generic EveUnity client connects directly to the daemon's local CultMesh endpoint. Odin is not part of this path. -The daemon is launched by the installed system .NET host rather than Unity's -embedded runtime environment. This keeps .NET 10 host resolution deterministic -and preserves managed startup and error output in the daemon logs. +The named daemon apphost is launched with both system .NET runtime-root +variables pinned explicitly rather than inheriting Unity's embedded runtime +environment. This keeps .NET 10 host resolution deterministic while preserving +the `Aetheria.State.Daemon` process identity used for ownership, Rider attach, +and domain-reload reattachment. The daemon lifecycle is independent of Unity Play Mode. Play never builds, starts, restarts, or stops the daemon. Entering Play connects a generic client; leaving Play drops that client while the authoritative daemon remains alive and ready for the next connection. +Starting the daemon does not create, load, or step a game world. It starts the +typed state boundary and CultMesh transport in `ready` mode. A playable-world +subscription loads an existing run; the advertised New Game command generates +a new run. Only that activation boundary opens Ymir persistence and starts the +fixed simulation clock. A dropped client therefore leaves the daemon and saved +world alive without making Unity Play Mode a lifecycle authority. + The editor connects through the daemon's `cultnet+tcp` control endpoint. The advertised session then selects the dedicated content and QUIC realtime planes; the editor bootstrap does not choose those planes or retain an RUDP fallback. @@ -73,7 +82,7 @@ resumes; it does not simulate through the breakpoint. - Daemon stderr: `Aetheria.Unity/Build/DaemonDevelopment/daemon.error.log` - Preparation logs: `Aetheria.Unity/Build/DaemonDevelopment/launcher*.log` -`Reimport state & start` deletes only the isolated development `.cc` file, its +`Reimport state & build` deletes only the isolated development `.cc` file, its `.cultmesh` (or legacy `.records`) sidecar, and the matching daemon-private `.ymir.cc` journal store before importing it again. It does not touch `GameData`, the source catalog, or another witness/run state.