From d024a04fd5d7b6ceb4482490bed9f86e915e1b94 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 4 Oct 2026 16:07:28 +0200 Subject: [PATCH] feat(desktop): control managed models over gRPC (STRA-58) --- .github/workflows/desktop.yml | 2 + desktop-core/GRPC.md | 40 +++++++++- desktop-core/proto/node.proto | 1 + desktop-core/src/main.rs | 11 +++ desktop-core/src/node.rs | 5 ++ desktop-core/tests/managed_worker.rs | 29 ++++++- desktop/CoreClient.Worker.cs | 45 +++++++++++ desktop/CoreClient.cs | 2 +- desktop/MainWindow.cs | 45 ++++++++++- desktop/Program.cs | 5 ++ desktop/README.md | 24 +++++- desktop/WorkerController.cs | 103 ++++++++++++++++++++++++ desktop/WorkerSelfCheck.cs | 81 +++++++++++++++++++ desktop/tests/lifecycle.py | 114 +++++++++++++++++++++++++++ 14 files changed, 500 insertions(+), 7 deletions(-) create mode 100644 desktop/CoreClient.Worker.cs create mode 100644 desktop/WorkerController.cs create mode 100644 desktop/WorkerSelfCheck.cs create mode 100644 desktop/tests/lifecycle.py diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index d6f5432c..03ccaf0a 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -34,3 +34,5 @@ jobs: run: dotnet desktop/bin/Debug/net10.0/Strata.Desktop.dll --self-check - name: Desktop gRPC restart recovery (isolated node) run: python desktop/tests/reconnect.py + - name: Desktop managed lifecycle (isolated synthetic worker) + run: python desktop/tests/lifecycle.py diff --git a/desktop-core/GRPC.md b/desktop-core/GRPC.md index 1c4a71bb..7f75dd4a 100644 --- a/desktop-core/GRPC.md +++ b/desktop-core/GRPC.md @@ -186,8 +186,8 @@ acceptance. CLI stop uses a 30-second drain grace. A lost connection can query the same ID in the same node epoch; unknown ID after node restart requires explicit reconciliation, not automatic resubmission. Node capability is worker.lifecycle.v1. Existing inventory-only UI children cannot own models; -managed nodes stay independent of UI lifetime. UI buttons and profile installation -remain pending. +managed nodes stay independent of UI lifetime. Profile installation remains pending; the desktop now exposes lifecycle buttons +for an explicitly configured persistent node. The child receives STRATA_WORKER_ENDPOINT and STRATA_WORKER_MODEL alongside a restricted platform environment. Backend stdout/stderr are discarded. An owned @@ -202,3 +202,39 @@ affinity rejection, wrong model/occupied endpoint fail-closed, child crash and explicit restart, drain timeout preserves active request. The ignored fixture entry is invoked as a subprocess by the tests, not an omitted quality check. These are synthetic protocol/process tests, not model quality or speed results. + +### Desktop lifecycle controls +A configured persistent node exposes model phase and explicit Start/Stop buttons. +The inventory-only app-owned node cannot launch models. UI submits one UUID once, +polls its outcome after reconnect, and never retries a mutation after uncertain +delivery. Expected node epoch fences mutations; a changed epoch or missing +operation requires explicit operator reconciliation. UI closure cancels only +client observation, never stops the external worker. No automatic Start on app +launch, no SSH provisioning or user runtime adoption in this slice. + + +The UI controller keeps one outstanding operation ID for the lifetime of that +window. Start/Stop are disabled when state is unavailable, the worker is +transitioning, or an operation remains unresolved. Each explicit command first +reads fresh worker state. Acknowledgement loss triggers status queries only; +the command is not resubmitted. Expected epoch is sent by both current CLI and +desktop; the node rejects mismatching nonempty epochs before enqueueing. +Empty epoch remains accepted for earlier v1 clients. This is additive protobuf +compatibility, not durable cross-restart idempotency. + +The UI polls managed status every second with bounded RPC deadlines, separately +from the connection observer. A changed node epoch or missing operation retains +the UUID and blocks new UI commands with a reconciliation message. Pending state +is currently in memory: closing/reopening the app reads authoritative worker state +but does not recover the previous UI operation journal. Auto-download/provision, +profile selection and durable reconciliation are still outstanding. + +Verification: `python desktop/tests/lifecycle.py` exercises the same desktop +controller and generated C# client against an actual isolated Rust node and +synthetic backend process. It injects lost acknowledgement after real commands, +confirms polling reaches completion with exactly one submit, closes/reconnects +the client without stopping the worker, checks exact synthetic Responses bytes, +and stops the owned worker. A deterministic replacement-epoch fixture verifies +that uncertain commands remain blocked. Rust gRPC tests additionally verify +rejection of a stale epoch with the worker still stopped. No active remote node +or user inference is involved. Python is only the offline test fixture/runner. diff --git a/desktop-core/proto/node.proto b/desktop-core/proto/node.proto index a7575c0c..0bdddcc7 100644 --- a/desktop-core/proto/node.proto +++ b/desktop-core/proto/node.proto @@ -46,6 +46,7 @@ message WorkerCommand { enum Action { UNSPECIFIED = 0; START = 1; STOP = 2; } Action action = 2; uint32 drain_timeout_ms = 3; + string expected_epoch = 4; } message OperationQuery { string operation_id = 1; } message WorkerOperation { diff --git a/desktop-core/src/main.rs b/desktop-core/src/main.rs index db160ee6..f9048ae3 100644 --- a/desktop-core/src/main.rs +++ b/desktop-core/src/main.rs @@ -163,10 +163,21 @@ async fn worker(args: &[String]) -> Result<(), Box> { serde_json::json!({"profile_id":s.profile_id,"model":s.model,"phase":s.phase,"pid":s.pid,"reason":s.reason}) } ("start" | "stop", [id]) => { + let epoch = client + .handshake(worker_request( + Hello { + protocol_version: 1, + }, + &token, + )?) + .await? + .into_inner() + .agent_epoch; let s = client .control_worker(worker_request( WorkerCommand { operation_id: id.clone(), + expected_epoch: epoch, action: if action == "start" { 1 } else { 2 }, drain_timeout_ms: if action == "stop" { 30000 } else { 0 }, }, diff --git a/desktop-core/src/node.rs b/desktop-core/src/node.rs index 851fa84f..72da10d2 100644 --- a/desktop-core/src/node.rs +++ b/desktop-core/src/node.rs @@ -187,6 +187,11 @@ impl Node for Agent { r: Request, ) -> Result, Status> { self.auth(&r)?; + if !r.get_ref().expected_epoch.is_empty() + && r.get_ref().expected_epoch != self.snapshot().agent_epoch + { + return Err(Status::failed_precondition("node epoch changed")); + } self.0 .manager .as_ref() diff --git a/desktop-core/tests/managed_worker.rs b/desktop-core/tests/managed_worker.rs index f08ba0bf..5cf91a22 100644 --- a/desktop-core/tests/managed_worker.rs +++ b/desktop-core/tests/managed_worker.rs @@ -93,6 +93,7 @@ fn command(action: i32, grace: u32) -> WorkerCommand { operation_id: uuid::Uuid::new_v4().to_string(), action, drain_timeout_ms: grace, + expected_epoch: String::new(), } } async fn finish(m: &Manager, c: WorkerCommand) -> WorkerOperation { @@ -180,6 +181,20 @@ async fn grpc_owned_start_stop_and_exact_response() { c.respond(req(input.clone())).await.unwrap_err().code(), tonic::Code::Unavailable ); + let mut stale = command(1, 0); + stale.expected_epoch = "old-epoch".into(); + assert_eq!( + c.control_worker(req(stale)).await.unwrap_err().code(), + tonic::Code::FailedPrecondition + ); + assert_eq!( + c.worker_status(req(Empty {})) + .await + .unwrap() + .into_inner() + .phase, + "stopped" + ); let op = command(1, 0); assert_eq!(remote_finish(&mut c, op.clone()).await.status, "succeeded"); let state = c.worker_status(req(Empty {})).await.unwrap().into_inner(); @@ -436,13 +451,22 @@ async fn cli_profile_start_status_stop_and_node_drop_cleanup() { let id = uuid::Uuid::new_v4().to_string(); assert_eq!(cli(&address, &["start", &id]).await["operation_id"], id); let mut c = node::connect(address.parse().unwrap()).await.unwrap(); + let epoch = c + .handshake(req(Hello { + protocol_version: 1, + })) + .await + .unwrap() + .into_inner() + .agent_epoch; assert_eq!( remote_finish( &mut c, WorkerCommand { operation_id: id.clone(), action: 1, - drain_timeout_ms: 0 + drain_timeout_ms: 0, + expected_epoch: epoch.clone(), } ) .await @@ -462,7 +486,8 @@ async fn cli_profile_start_status_stop_and_node_drop_cleanup() { WorkerCommand { operation_id: id, action: 2, - drain_timeout_ms: 30000 + drain_timeout_ms: 30000, + expected_epoch: epoch.clone(), } ) .await diff --git a/desktop/CoreClient.Worker.cs b/desktop/CoreClient.Worker.cs new file mode 100644 index 00000000..b2da7fbe --- /dev/null +++ b/desktop/CoreClient.Worker.cs @@ -0,0 +1,45 @@ +using Grpc.Core; +using Strata.Node.V1; + +namespace Strata.Desktop; + +internal static partial class CoreClient +{ + public static IWorkerRpc WorkerRpc() => new WorkerRpcClient(); + private sealed class WorkerRpcClient : IWorkerRpc + { + public async Task Read(CancellationToken token) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var c = await Connect(timeout.Token); + var hello = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: timeout.Token); + ValidateSnapshot(hello, null); + if (!hello.Capabilities.Contains("worker.lifecycle.v1")) return new(hello.AgentEpoch, null); + var state = await c.WorkerStatusAsync(new Empty(), Headers(), + deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: timeout.Token); + var after = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: timeout.Token); + ValidateSnapshot(after, hello); + if (after.AgentEpoch != hello.AgentEpoch) + throw new RpcException(new Status(StatusCode.Unavailable, "Node changed")); + if (state.ProfileId.Length > 128 || state.Model.Length > 256 || state.Reason.Length > 256 + || state.Phase is not ("stopped" or "starting" or "ready" or "draining" or "failed")) + throw new InvalidOperationException("Invalid worker state"); + return new(hello.AgentEpoch, state); + } + public async Task Submit(WorkerCommand command, CancellationToken token) + { + var c = await Connect(token); + return await c.ControlWorkerAsync(command, Headers(), + deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: token); + } + public async Task Lookup(string id, CancellationToken token) + { + var c = await Connect(token); + return await c.OperationStatusAsync(new OperationQuery { OperationId = id }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: token); + } + } +} diff --git a/desktop/CoreClient.cs b/desktop/CoreClient.cs index db4a1e41..f527b6d1 100644 --- a/desktop/CoreClient.cs +++ b/desktop/CoreClient.cs @@ -9,7 +9,7 @@ using Strata.Node.V1; namespace Strata.Desktop; -internal static class CoreClient +internal static partial class CoreClient { private static readonly SemaphoreSlim Gate = new(1); private static GrpcChannel? channel; diff --git a/desktop/MainWindow.cs b/desktop/MainWindow.cs index 3181692c..ca47f0dc 100644 --- a/desktop/MainWindow.cs +++ b/desktop/MainWindow.cs @@ -19,6 +19,10 @@ public sealed class MainWindow : Window private readonly Button refresh = Action("Оновити обладнання"); private readonly Button import = Action("Відкрити профіль…"); private readonly Button example = Action("Приклад оцінки"); + private readonly WorkerController worker = new(CoreClient.WorkerRpc()); + private readonly TextBlock workerStatus = Text("Модель: перевірка вузла…", 14, Muted); + private readonly Button startWorker = Action("Запустити модель"); + private readonly Button stopWorker = Action("Зупинити модель"); private readonly CancellationTokenSource lifetime = new(); public MainWindow() @@ -46,6 +50,13 @@ public sealed class MainWindow : Window page.Children.Add(toolbar); page.Children.Add(status); page.Children.Add(connectionStatus); + page.Children.Add(workerStatus); + var workerActions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10 }; + startWorker.IsEnabled = stopWorker.IsEnabled = false; + workerActions.Children.Add(startWorker); workerActions.Children.Add(stopWorker); + page.Children.Add(workerActions); + startWorker.Click += async (_, _) => await WorkerCommand(true); + stopWorker.Click += async (_, _) => await WorkerCommand(false); var columns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,24,*") }; var left = new StackPanel { Spacing = 14 }; left.Children.Add(Text("ОБЛАДНАННЯ", 11, Accent, FontWeight.SemiBold)); @@ -58,11 +69,12 @@ public sealed class MainWindow : Window var scroll = new ScrollViewer { Content = page, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled }; Grid.SetColumn(scroll, 1); root.Children.Add(scroll); Content = root; planCards.Children.Add(Card("Спочатку — вимоги моделі", "Відкрийте JSON-профіль із runtime-розмірами ваг, KV і буферів. Або перегляньте явно позначений синтетичний приклад.")); - planCards.Children.Add(Card("Що вже працює", "Локальне визначення обладнання та оцінка пам’яті. Запуск моделей і автоматичні бенчмарки ще не підключені.")); + planCards.Children.Add(Card("Що вже працює", "Локальне визначення обладнання та оцінка пам’яті. Керування встановленою моделлю доступне на налаштованому керованому вузлі. Завантаження моделей і автоматичні бенчмарки ще попереду.")); refresh.Click += async (_, _) => await Busy(RefreshHardware); import.Click += async (_, _) => await PickProfile(); example.Click += async (_, _) => await Busy(() => LoadPlan(Path.Combine(AppContext.BaseDirectory, "example-requirements.json"))); Opened += async (_, _) => { + _ = ObserveWorker(); await Busy(RefreshHardware); _ = Task.Run(() => CoreClient.Observe(state => Avalonia.Threading.Dispatcher.UIThread.Post(() => { connectionStatus.Text = state.Phase switch { @@ -79,6 +91,37 @@ public sealed class MainWindow : Window Closed += (_, _) => lifetime.Cancel(); } + private void RenderWorker() + { + var w = worker.View; + string label = w.Phase switch { + "ready" => "Модель готова", "stopped" => "Модель зупинена", + "starting" => "Завантаження моделі…", "draining" => "Завершення активних запитів…", + "failed" => "Помилка моделі", "unmanaged" => "На цьому вузлі немає профілю запуску моделі", + "auth_error" => "Перевірте доступ до вузла", "reconcile" => "Потрібна звірка стану", + _ => "Стан моделі недоступний · відновлення зв’язку…" + }; + workerStatus.Text = label + (w.Model.Length > 0 ? " · " + w.Model : "") + + (w.Detail.Length > 0 ? "\n" + w.Detail : "") + + (w.OperationId.Length > 0 ? "\nОперація: " + w.OperationId : ""); + startWorker.IsEnabled = w.CanStart; stopWorker.IsEnabled = w.CanStop; + } + private async Task ObserveWorker() + { + try { + while (!lifetime.IsCancellationRequested) { + await worker.Refresh(lifetime.Token); RenderWorker(); + await Task.Delay(1000, lifetime.Token); + } + } catch (OperationCanceledException) {} + } + private async Task WorkerCommand(bool start) + { + startWorker.IsEnabled = stopWorker.IsEnabled = false; + try { await worker.Command(start, lifetime.Token); RenderWorker(); } + catch (OperationCanceledException) {} + } + private async Task Busy(Func action) { refresh.IsEnabled = import.IsEnabled = example.IsEnabled = false; diff --git a/desktop/Program.cs b/desktop/Program.cs index 4e725f3d..36843b0b 100644 --- a/desktop/Program.cs +++ b/desktop/Program.cs @@ -12,6 +12,11 @@ internal static class Program { try { + if (args is ["--self-check-worker"]) + { + try { CoreClient.WorkerSelfCheck().GetAwaiter().GetResult(); return 0; } + catch (Exception e) { Console.Error.WriteLine(e.Message); return 1; } + } if (args is ["--self-check-reconnect"]) { try { CoreClient.ReconnectSelfCheck().GetAwaiter().GetResult(); return 0; } diff --git a/desktop/README.md b/desktop/README.md index f3ef853e..f3bbd06b 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -82,7 +82,7 @@ See [product architecture](../docs/cross-platform-application.md) for boundaries The Rust CLI now also has an experimental [pool gateway](../desktop-core/POOL.md) and [SSH preflight](../desktop-core/REMOTE.md). They are separate CLI capabilities; -the current desktop window still covers local inventory and memory planning. +the desktop covers node inventory, memory planning and an installed worker’s lifecycle. Shared node implementation: [gRPC contract and commands](../desktop-core/GRPC.md). On macOS the C#→gRPC→Rust self-check passed. Rust integration tests also cover @@ -96,3 +96,25 @@ state on agent epoch changes and stops automatic retries for auth/protocol error Run `python desktop/tests/reconnect.py` after building to test C# recovery against an isolated node restart. This test creates and cleans its own local processes; it never sends model requests or contacts the user's remote endpoint. + + +## Managed model controls + +For an operator-configured persistent node started with `--worker-profile`, set +`STRATA_NODE_ENDPOINT` to its loopback address (or existing SSH forward) and +`STRATA_NODE_TOKEN` to its private credential before launching the desktop. +See the [node commands/profile format](../desktop-core/GRPC.md). The window shows +the model’s phase and provides **Запустити модель** / **Зупинити модель**. Neither +opening nor closing the window changes the model’s running state. With the default +inventory-only node, lifecycle buttons remain disabled. + +During a lost connection the app queries the existing operation UUID instead of +resending Start/Stop. Unknown outcomes or a replaced node block further actions +and show the UUID for operator reconciliation. Installing/downloading a model, +selecting another installed profile and creating SSH tunnels are not yet exposed. + +`python desktop/tests/lifecycle.py` runs the real C# controller/gRPC/managed-child +integration with synthetic data. On macOS it passed start/stop, lost-ack status +recovery, client-close independence and exact Responses byte checks. The test is +in the three-platform CI definition; hosted Actions and interactive inspection of +the new buttons on all platforms remain unverified. No model quality/speed claim. diff --git a/desktop/WorkerController.cs b/desktop/WorkerController.cs new file mode 100644 index 00000000..848333a9 --- /dev/null +++ b/desktop/WorkerController.cs @@ -0,0 +1,103 @@ +using Grpc.Core; +using Strata.Node.V1; + +namespace Strata.Desktop; + +internal sealed record WorkerReading(string Epoch, WorkerState? Worker); +internal interface IWorkerRpc +{ + Task Read(CancellationToken token); + Task Submit(WorkerCommand command, CancellationToken token); + Task Lookup(string id, CancellationToken token); +} +internal sealed record WorkerView(string Phase, string Model = "", string Detail = "", bool CanStart = false, + bool CanStop = false, string OperationId = "", uint Pid = 0); + +// One outstanding command, never automatically resubmitted. Polling is read-only. +internal sealed class WorkerController(IWorkerRpc rpc) +{ + private readonly SemaphoreSlim gate = new(1); + private WorkerCommand? pending; + private bool uncertain; + public WorkerView View { get; private set; } = new("connecting"); + private static bool Startable(WorkerState w) => w.Pid == 0 && w.Phase is "stopped" or "failed"; + private static bool Stoppable(WorkerState w) => w.Pid != 0 && w.Phase is "ready" or "failed"; + private void Show(WorkerState w, string detail = "") + { + View = new(w.Phase, w.Model, detail.Length > 0 ? detail : w.Reason, + pending == null && Startable(w), pending == null && Stoppable(w), pending?.OperationId ?? "", w.Pid); + } + public async Task Refresh(CancellationToken token) + { + await gate.WaitAsync(token); + try { await RefreshLocked(token); } + catch (Exception e) when (e is RpcException or IOException or InvalidOperationException or OperationCanceledException) + { Offline(e); } + finally { gate.Release(); } + } + private async Task RefreshLocked(CancellationToken token) + { + var reading = await rpc.Read(token); + if (pending != null && reading.Epoch != pending.ExpectedEpoch) uncertain = true; + if (reading.Worker == null) { + View = new("unmanaged", Detail: pending == null ? "" : "Операцію неможливо звірити: вузол змінився.", OperationId: pending?.OperationId ?? ""); + return; + } + if (pending == null) { Show(reading.Worker); return; } + if (uncertain) { Show(reading.Worker, "Вузол або журнал змінився. Потрібна ручна звірка операції; повторного запуску немає."); return; } + WorkerOperation op; + try { op = await rpc.Lookup(pending.OperationId, token); } + catch (RpcException e) when (e.StatusCode == StatusCode.NotFound) { + uncertain = true; Show(reading.Worker, "Результат операції невідомий. Команду не повторено."); return; + } + Validate(op, pending.OperationId); + // Recheck epoch and phase after lookup: a replacement may have occurred between RPCs. + var after = await rpc.Read(token); + if (after.Epoch != pending.ExpectedEpoch || after.Worker == null) { + uncertain = true; View = new("reconcile", Detail: "Вузол змінився. Команду не повторено.", OperationId: pending.OperationId); return; + } + if (op.Status is "succeeded" or "failed") { + pending = null; + Show(after.Worker, op.Status == "succeeded" ? "Операцію завершено." : "Операція не виконана: " + op.Reason); + } + else Show(after.Worker, "Операція виконується…"); + } + public async Task Command(bool start, CancellationToken token) + { + await gate.WaitAsync(token); + try { + if (pending != null) return; + var reading = await rpc.Read(token); + var w = reading.Worker; + if (w == null || !(start ? Startable(w) : Stoppable(w))) { + if (w != null) Show(w, "Стан змінився; команду не надіслано."); + return; + } + pending = new WorkerCommand { + OperationId = Guid.NewGuid().ToString(), ExpectedEpoch = reading.Epoch, + Action = start ? WorkerCommand.Types.Action.Start : WorkerCommand.Types.Action.Stop, + DrainTimeoutMs = start ? 0u : 30000u + }; + uncertain = false; Show(w, "Надсилання команди…"); + // Keep pending even if acknowledgement is lost. Only Lookup follows. + var result = await rpc.Submit(pending.Clone(), token); + Validate(result, pending.OperationId); + await RefreshLocked(token); + } + catch (Exception e) when (e is RpcException or IOException or InvalidOperationException or OperationCanceledException) + { Offline(e); } + finally { gate.Release(); } + } + private void Offline(Exception e) + { + var phase = e is RpcException r && r.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied + ? "auth_error" : "disconnected"; + View = new(phase, Detail: pending == null ? "Оновлюю зв’язок…" : "Очікую результат попередньої операції; команда не повторюється.", + OperationId: pending?.OperationId ?? ""); + } + private static void Validate(WorkerOperation op, string id) + { + if (op.OperationId != id || op.Status is not ("accepted" or "running" or "succeeded" or "failed") || op.Reason.Length > 256) + throw new InvalidOperationException("Invalid operation state"); + } +} diff --git a/desktop/WorkerSelfCheck.cs b/desktop/WorkerSelfCheck.cs new file mode 100644 index 00000000..16fa603f --- /dev/null +++ b/desktop/WorkerSelfCheck.cs @@ -0,0 +1,81 @@ +using Grpc.Core; +using Strata.Node.V1; + +namespace Strata.Desktop; + +internal static partial class CoreClient +{ + private sealed class LostAcknowledgementRpc(IWorkerRpc inner) : IWorkerRpc + { + public int Submits; + public Task Read(CancellationToken token) => inner.Read(token); + public Task Lookup(string id, CancellationToken token) => inner.Lookup(id, token); + public async Task Submit(WorkerCommand command, CancellationToken token) + { + Submits++; + await inner.Submit(command, token); + throw new RpcException(new Status(StatusCode.Unavailable, "Synthetic lost acknowledgement")); + } + } + private sealed class ChangedEpochRpc : IWorkerRpc + { + public int Submits; + public bool Changed; + public Task Read(CancellationToken token) => Task.FromResult(new WorkerReading( + Changed ? "replacement" : "original", new WorkerState { Phase = "stopped", Model = "synthetic" })); + public Task Lookup(string id, CancellationToken token) => throw new Exception("Must not query replaced epoch"); + public Task Submit(WorkerCommand command, CancellationToken token) { + Submits++; Changed = true; + throw new RpcException(new Status(StatusCode.Unavailable, "Synthetic epoch replacement")); + } + } + public static async Task WorkerSelfCheck() + { + if (Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT") == null) + throw new InvalidOperationException("Lifecycle check requires an isolated configured test node."); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25)); + var token = timeout.Token; + var rpc = new LostAcknowledgementRpc(WorkerRpc()); + var controller = new WorkerController(rpc); + await controller.Refresh(token); + if (!controller.View.CanStart) throw new Exception("Fixture must start stopped"); + await controller.Command(true, token); + var id = controller.View.OperationId; + if (id.Length == 0 || controller.View.CanStart || controller.View.CanStop) throw new Exception("Uncertain command must block duplicates"); + while (controller.View.Phase != "ready" || !controller.View.CanStop) { + await controller.Refresh(token); + await Task.Delay(50, token); + } + if (rpc.Submits != 1) throw new Exception("Mutation was replayed"); + var pid = controller.View.Pid; + // Closing a desktop client must not stop a configured persistent node. + Close(); + await controller.Refresh(token); + if (controller.View.Pid != pid || !controller.View.CanStop) throw new Exception("Worker did not survive client close"); + var c = await Connect(token); + using (var response = c.Respond(new ResponseRequest { Json = Google.Protobuf.ByteString.CopyFromUtf8( + """{"model":"fixture","input":"synthetic","stream":false}""") }, Headers(), cancellationToken: token)) { + using var bytes = new MemoryStream(); bool ended = false; + while (await response.ResponseStream.MoveNext(token)) { + var frame = response.ResponseStream.Current; + if (frame.PayloadCase == ResponseFrame.PayloadOneofCase.Data) bytes.Write(frame.Data.Span); + if (frame.PayloadCase == ResponseFrame.PayloadOneofCase.End) ended = true; + if (frame.PayloadCase == ResponseFrame.PayloadOneofCase.Headers && frame.Headers.Status != 200) throw new Exception("Response failed"); + } + if (!ended || System.Text.Encoding.UTF8.GetString(bytes.ToArray()) != """{"id":"fixture_response","status":"completed","output":[]}""") + throw new Exception("Response bytes or terminal changed"); + } + await controller.Command(false, token); + while (controller.View.Phase != "stopped" || !controller.View.CanStart) { + await controller.Refresh(token); await Task.Delay(50, token); + } + if (rpc.Submits != 2) throw new Exception("Stop was replayed"); + var changed = new ChangedEpochRpc(); + var epoch = new WorkerController(changed); + await epoch.Refresh(token); await epoch.Command(true, token); await epoch.Refresh(token); + await epoch.Command(true, token); + if (changed.Submits != 1 || epoch.View.CanStart || epoch.View.CanStop || epoch.View.OperationId.Length == 0) + throw new Exception("Epoch replacement enabled unsafe mutation"); + Console.WriteLine("PASS: desktop lifecycle start/stop, lost-ack reconciliation, no duplicate mutation, client-close independence, epoch replacement blocked, byte-exact synthetic Responses."); + } +} diff --git a/desktop/tests/lifecycle.py b/desktop/tests/lifecycle.py new file mode 100644 index 00000000..24a6bcc6 --- /dev/null +++ b/desktop/tests/lifecycle.py @@ -0,0 +1,114 @@ +"""Offline desktop lifecycle test. Python is a synthetic backend/test runner only.""" +import asyncio +import json +import os +from pathlib import Path +import secrets +import socket +import sys +import tempfile +import uuid + + +def fixture(): + from http.server import BaseHTTPRequestHandler, HTTPServer + import threading + assert "STRATA_NODE_TOKEN" not in os.environ + host, port = os.environ["STRATA_WORKER_ENDPOINT"].rsplit(":", 1) + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def do_GET(self): + body = json.dumps({"status": "ok", "loaded": True, "model": os.environ["STRATA_WORKER_MODEL"]}).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", 0))) + body = b'{"id":"fixture_response","status":"completed","output":[]}' + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + # Last-resort bound if the entire test runner is killed. + timer = threading.Timer(40, lambda: os._exit(0)) + timer.daemon = True + timer.start() + HTTPServer((host, int(port)), Handler).serve_forever() + + +async def main(): + root = Path(__file__).resolve().parents[2] + binary = root / "desktop-core/target/debug" / ("strata-desktop.exe" if os.name == "nt" else "strata-desktop") + dll = root / "desktop/bin/Debug/net10.0/Strata.Desktop.dll" + env = os.environ.copy() + env.pop("STRATA_NODE_ENDPOINT", None) + env["STRATA_NODE_TOKEN"] = secrets.token_hex(32) + node = app = None + endpoint = None + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + worker_port = listener.getsockname()[1] + with tempfile.TemporaryDirectory(prefix="strata-lifecycle-") as temp: + profile = Path(temp) / "profile.json" + profile.write_text(json.dumps({ + "schema_version": 1, "id": "fixture", "model": "synthetic", + "executable": sys.executable, "args": [str(Path(__file__).resolve()), "--fixture"], + "endpoint": f"127.0.0.1:{worker_port}", "startup_timeout_ms": 5000, + })) + try: + node = await asyncio.create_subprocess_exec( + str(binary), "node", "--listen", "127.0.0.1:0", "--token-env", "STRATA_NODE_TOKEN", + "--worker-profile", str(profile), env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, + ) + endpoint = json.loads(await asyncio.wait_for(node.stdout.readline(), 5))["endpoint"] + env["STRATA_NODE_ENDPOINT"] = endpoint + app = await asyncio.create_subprocess_exec( + "dotnet", str(dll), "--self-check-worker", env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await asyncio.wait_for(app.communicate(), 30) + if app.returncode != 0: + raise RuntimeError("Desktop lifecycle failed: " + stderr.decode()[:500]) + print(stdout.decode().strip()) + finally: + if app and app.returncode is None: + app.kill() + await app.wait() + if node and node.returncode is None: + try: + if endpoint: + cmd = [str(binary), "worker", "--node", endpoint.removeprefix("http://"), + "--token-env", "STRATA_NODE_TOKEN"] + child = await asyncio.create_subprocess_exec( + *cmd, "stop", str(uuid.uuid4()), env=env, + stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL) + await asyncio.wait_for(child.wait(), 6) + for _ in range(30): + child = await asyncio.create_subprocess_exec( + *cmd, "status", env=env, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL) + data, _ = await asyncio.wait_for(child.communicate(), 6) + if child.returncode == 0 and json.loads(data)["phase"] == "stopped": + break + await asyncio.sleep(.1) + finally: + if node.returncode is None: + node.kill() + await node.wait() + with socket.socket() as listener: + assert listener.connect_ex(("127.0.0.1", worker_port)) != 0, "fixture listener leaked" + + +if __name__ == "__main__": + if sys.argv[1:] == ["--fixture"]: + fixture() + else: + asyncio.run(main())