From c10271a7aab5f5e2bebe5b06431d9f159b9a0fa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Sun, 15 Nov 2026 17:17:15 +0300 Subject: [PATCH 1/4] fix(hosting): make inner handoff preparation best-effort (#895) --- CHANGELOG.md | 1 + .../Internal/Handoff/ServicePtyHandoff.cs | 12 +-- .../Handoff/ServicePtyHandoffTests.cs | 81 ++++++++++++++++--- 3 files changed, 78 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98b093ca..fc3bac0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ The next SDK version is **2.0.0**, on the same opencode **2.3.0** pin already re ### 🔧 Changes - `StopAsync` and the `EnsureAsync` version-mismatch replacement treat a failed persistent-terminal handoff or clear as best-effort, whatever the exception type, as opencode's CLI does. Before: a failure other than an `OpenCodeServerException` ended `StopAsync` before it terminated the old service, and ended `EnsureAsync` at once. After: `StopAsync` terminates the old service; `EnsureAsync` keeps polling, and the last replacement failure becomes the inner exception of its timeout. The caller's cancellation still ends both. (#871) +- A failed persistent-terminal ticket request, terminal-shutdown fallback or sidecar publish, whatever its exception type, no longer ends the handoff preparation: the replacement then starts without the terminals, as with opencode's CLI. The caller's cancellation still ends the preparation. (#895) - The packages' .NET dependency floors move from `10.0.13` to the `10.0.15` servicing release: on `net472` and `netstandard2.0`, `System.Text.Json`, `System.Threading.Channels`, `System.Collections.Immutable`, `Microsoft.Bcl.AsyncInterfaces`, `Microsoft.Bcl.Memory` and `Microsoft.Bcl.TimeProvider`; in `OpenCodeDotNet.Sdk.Extensions`, on every target, `Microsoft.Extensions.DependencyInjection.Abstractions` and `Microsoft.Extensions.Options.ConfigurationExtensions`. No security advisory of the .NET 10.0.14 or 10.0.15 release lists these packages. - Event Types are copied and validated at the call and selected locally; physical attempts send no Types query. The whole bus is decoded once, so malformed unselected traffic reconnects every subscriber. Event and metadata instances are shared references, not deep-frozen graphs; consumers treat them as read-only. Queue bounds count events, not bytes, and subscriber count remains unbounded. - Event subscriptions accept but no longer forward per-call Location. Every shared attempt sends only the client's ambient header snapshot; other operations retain their existing override behavior. diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs index f68d27a9..632256f7 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs @@ -62,7 +62,7 @@ public async Task PrepareAsync( { throw FailureClassification.CallerCancellation(failure, "The persistent-terminal handoff request was canceled.", cancellationToken); } - catch (Exception failure) when (failure is OpenCodeException or OperationCanceledException or ArgumentException { ParamName: "endpoint" }) + catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { // Another caller may already have prepared and stopped this server; otherwise the // daemon's terminals are shut down and the replacement starts without a handoff. @@ -190,7 +190,7 @@ private PtyHandoffSidecar Parse(ServiceHandoffTicketResponse answer, ServiceRegi /// [SlopwatchSuppress( "SW003", - "The pinned client's shutdown .catch(() => {}) is best-effort (prepare in pty-handoff.ts): endpoint refusal or a failed shutdown leads to a null sidecar and replacement without these terminals.")] + "The pinned client's prepare catches every shutdown fallback failure (prepare in pty-handoff.ts); the SDK has no warning channel here, so request failures are dropped where upstream warns and shutdown failures are dropped as upstream does. Only the caller's cancellation propagates, so the replacement starts without the terminals.")] private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan timeout, CancellationToken cancellationToken) { using var deadline = TimedCancellation.Create(timeout, time); @@ -203,7 +203,7 @@ private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan time { throw FailureClassification.CallerCancellation(failure, "The persistent-terminal shutdown fallback was canceled.", cancellationToken); } - catch (Exception failure) when (failure is OpenCodeException or OperationCanceledException or ArgumentException { ParamName: "endpoint" }) + catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { // Best-effort: the replacement starts without these terminals. } @@ -211,18 +211,18 @@ private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan time /// /// publish(...).catch(warn): a sidecar that cannot be written leaves the replacement - /// without a handoff; it never fails the preparation. + /// without a handoff; only the caller's cancellation fails the preparation. /// [SlopwatchSuppress( "SW003", - "The pinned client only warns when publishing the handoff fails (prepare in pty-handoff.ts): the replacement then starts without the terminals, which is the best-effort contract.")] + "The pinned client's prepare catches every sidecar publish failure and only warns (prepare in pty-handoff.ts); the SDK has no warning channel here, so the failure is dropped. Only the caller's cancellation propagates, so the replacement starts without the terminals.")] private async Task TryPublishAsync(string sidecarPath, PtyHandoffSidecar sidecar, CancellationToken cancellationToken) { try { await PublishAsync(sidecarPath, sidecar, cancellationToken).ConfigureAwait(false); } - catch (OpenCodeServerException) + catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { // Best-effort: no sidecar means no handoff. } diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs index a052b32d..979dc26f 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs @@ -250,33 +250,72 @@ public async Task PrepareAsync_Should_Fall_Back_When_The_Registered_Endpoint_Is_ [Test] [Arguments("options")] [Arguments(null)] - public async Task PrepareAsync_Should_Propagate_An_Unrelated_Shutdown_Argument_Error(string? parameterName) + [Arguments("io")] + public async Task PrepareAsync_Should_Swallow_A_Failed_Shutdown_Fallback(string? parameterName) { + _scenario.EnsureSidecarDirectory(); await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); - var failure = new ArgumentException("The shutdown implementation rejected another parameter.", parameterName); + Exception failure = parameterName == "io" + ? new IOException("The shutdown failed.") + : new ArgumentException("The shutdown implementation rejected another parameter.", parameterName); var shutdown = Substitute.For(); shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.FromException(failure)); var handoff = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown); - var exception = await Assert.That(async () => await handoff.PrepareAsync( - _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).Throws(); + await Assert.That(async () => await handoff.PrepareAsync( + _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing(); - await Assert.That(exception).IsSameReferenceAs(failure); - await Assert.That(_scenario.ReadSidecar()).IsNull(); + _ = await AssertNullSidecarAsync(); + } + + [Test] + public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_When_The_Ticket_Request_Fails_With_An_IO_Error() + { + _scenario.EnsureSidecarDirectory(); + var files = new TestablyServiceFileSystem(_scenario.FileSystem); + var fileSystem = Substitute.For(); + fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()) + .Returns(call => files.TryReadAllBytesAsync(call.Arg(), call.Arg())); + fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(call => files.TryCreateExclusiveAsync(call.Arg(), call.Arg>(), call.Arg())); + fileSystem.When(static system => system.Rename(Arg.Any(), Arg.Any())) + .Do(call => files.Rename(call.ArgAt(0), call.ArgAt(1))); + var time = Substitute.For(); + time.GetUtcNow().Returns(_scenario.Clock.GetUtcNow()); + // Fail the ticket request's bound once, before transport can wrap the IOException; + // the shutdown fallback gets a working bound from the same clock seam. + time.CreateTimer(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => throw new IOException("The ticket request's timer could not be created."), + call => _scenario.Clock.CreateTimer(call.Arg(), call.Arg(), call.ArgAt(2), call.ArgAt(3))); + var shutdown = Substitute.For(); + shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var registration = FixedRegistration(); + + await Assert.That(async () => await new ServicePtyHandoff(fileSystem, time, shutdown).PrepareAsync( + _scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None)).ThrowsNothing(); + + _ = fileSystem.Received(2).TryReadAllBytesAsync(_scenario.SidecarPath(), CancellationToken.None); + _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any()); + _ = await AssertNullSidecarAsync(); } [Test] - public async Task PrepareAsync_Should_Complete_Without_A_Sidecar_When_The_Publish_Fails() + [Arguments("io")] + [Arguments("argument")] + public async Task PrepareAsync_Should_Complete_Without_A_Sidecar_When_The_Publish_Fails(string failureKind) { await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); var fileSystem = Substitute.For(); fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); + Exception failure = failureKind == "io" + ? new IOException("The sidecar directory vanished.") + : new ArgumentException("The sidecar write was refused.", "path"); fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) - .ThrowsAsync(new IOException("The sidecar directory vanished.")); + .ThrowsAsync(failure); - await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( - _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None); + await Assert.That(async () => await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( + _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing(); _ = fileSystem.Received(1).TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()); fileSystem.DidNotReceiveWithAnyArgs().Rename(default!, default!); @@ -511,6 +550,28 @@ public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation_During_The_Tic server.ReleaseResponses(); } + [Test] + public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation_During_The_Publish() + { + await using var server = LoopbackHttpServer.Start(static _ => + Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); + using var caller = new CancellationTokenSource(); + var fileSystem = Substitute.For(); + fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); + fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(async call => + { + await caller.CancelOnWorkerAsync(); + return await Task.FromCanceled(call.Arg()); + }); + + var exception = await Assert.That(async () => await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( + _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token)).Throws(); + + await Assert.That(exception!.CancellationToken).IsEqualTo(caller.Token); + fileSystem.DidNotReceiveWithAnyArgs().Rename(default!, default!); + } + /// The pinned client's environment reads a JSON-null ticket as no ticket and removes the variable. [Test] public async Task EnvironmentAsync_Should_Remove_The_Variable_For_A_Fresh_Matching_Sidecar_Without_A_Ticket() From 2c7a9ab677100be8321773ffe99427bf3ed43eca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Sun, 15 Nov 2026 17:29:52 +0300 Subject: [PATCH 2/4] test(hosting): use a valid parameter name in publish failure row --- .../Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs index 979dc26f..70453f0a 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs @@ -310,7 +310,7 @@ public async Task PrepareAsync_Should_Complete_Without_A_Sidecar_When_The_Publis fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); Exception failure = failureKind == "io" ? new IOException("The sidecar directory vanished.") - : new ArgumentException("The sidecar write was refused.", "path"); + : new ArgumentException("The sidecar write was refused.", nameof(failureKind)); fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) .ThrowsAsync(failure); From fded158112b7612cdbf2cc97a6b3ce87c243c841 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Sun, 15 Nov 2026 19:10:27 +0300 Subject: [PATCH 3/4] test(hosting): separate best-effort handoff preparation proofs --- .../ServicePtyHandoffBestEffortTests.cs | 287 ++++++++++++++ .../Handoff/ServicePtyHandoffScenario.cs | 34 ++ .../Handoff/ServicePtyHandoffTests.cs | 359 ++---------------- 3 files changed, 349 insertions(+), 331 deletions(-) create mode 100644 tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs new file mode 100644 index 00000000..7c603d8b --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs @@ -0,0 +1,287 @@ +using System.Net; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Support; +using TUnit.Assertions.Enums; +using static OpenCode.Sdk.Tests.Hosting.BackgroundService.Handoff.ServicePtyHandoffScenario; + +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Handoff; + +/// Failed inner preparation steps are best-effort; only the caller's cancellation propagates. +public sealed class ServicePtyHandoffBestEffortTests +{ + private readonly ServicePtyHandoffScenario _scenario = new(); + + [Test] + public async Task PrepareAsync_Should_Expire_The_Ticket_On_The_Injected_Clock() + { + _scenario.EnsureSidecarDirectory(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await using var server = LoopbackHttpServer.Start(_ => Pending(entered)); + var shutdown = Substitute.For(); + shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + using var caller = new CancellationTokenSource(); + var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); + var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown) + .PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, caller.Token); + try + { + await entered.Task.WaitAsync(PreparationHangGuard); + await AdvanceToJustBeforeRequestTimeoutAsync(); + await Assert.That(pending.IsCompleted).IsFalse(); + _ = shutdown.DidNotReceiveWithAnyArgs().ShutdownAsync(default!, default); + _scenario.Clock.Advance(TimeSpan.FromTicks(1)); + await pending.WaitAsync(PreparationHangGuard); + + _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any()); + await AssertNullSidecarAfterExpiryAsync(); + } + finally + { + await caller.CancelOnWorkerAsync(); + server.ReleaseResponses(); + } + } + + [Test] + public async Task PrepareAsync_Should_Expire_The_Fallback_On_The_Injected_Clock() + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var shutdown = Substitute.For(); + CancellationToken received = default; + shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(async call => + { + received = call.Arg(); + var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var cancellation = received.Register(() => held.TrySetCanceled(received)); + entered.TrySetResult(); + await held.Task; + }); + using var caller = new CancellationTokenSource(); + var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown) + .PrepareAsync(_scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token); + try + { + await entered.Task.WaitAsync(PreparationHangGuard); + await AdvanceToJustBeforeRequestTimeoutAsync(); + await Assert.That(received.IsCancellationRequested).IsFalse(); + await Assert.That(pending.IsCompleted).IsFalse(); + _scenario.Clock.Advance(TimeSpan.FromTicks(1)); + await pending.WaitAsync(PreparationHangGuard); + + await Assert.That(received.IsCancellationRequested).IsTrue(); + await AssertNullSidecarAfterExpiryAsync(); + } + finally + { + await caller.CancelOnWorkerAsync(); + } + } + + [Test] + public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Sidecar_When_The_Daemon_Answers_An_Error() + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static path => path == ShutdownPath + ? NoContent() + : Json(HttpStatusCode.InternalServerError, "{}")); + + await _scenario.PrepareAsync(server.Endpoint); + + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath, ShutdownPath], CollectionOrdering.Matching); + } + + [Test] + [Arguments("options")] + [Arguments(null)] + [Arguments("io")] + public async Task PrepareAsync_Should_Swallow_A_Failed_Shutdown_Fallback(string? parameterName) + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); + Exception failure = parameterName == "io" + ? new IOException("The shutdown failed.") + : new ArgumentException("The shutdown implementation rejected another parameter.", parameterName); + var shutdown = Substitute.For(); + shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.FromException(failure)); + var handoff = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown); + + await Assert.That(async () => await handoff.PrepareAsync( + _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing(); + + _ = await _scenario.AssertNullSidecarAsync(); + } + + [Test] + public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_When_The_Ticket_Request_Fails_With_An_IO_Error() + { + _scenario.EnsureSidecarDirectory(); + var files = new TestablyServiceFileSystem(_scenario.FileSystem); + var fileSystem = Substitute.For(); + fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()) + .Returns(call => files.TryReadAllBytesAsync(call.Arg(), call.Arg())); + fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(call => files.TryCreateExclusiveAsync(call.Arg(), call.Arg>(), call.Arg())); + fileSystem.When(static system => system.Rename(Arg.Any(), Arg.Any())) + .Do(call => files.Rename(call.ArgAt(0), call.ArgAt(1))); + var time = Substitute.For(); + time.GetUtcNow().Returns(_scenario.Clock.GetUtcNow()); + // Fail the ticket request's bound once, before transport can wrap the IOException; + // the shutdown fallback gets a working bound from the same clock seam. + time.CreateTimer(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => throw new IOException("The ticket request's timer could not be created."), + call => _scenario.Clock.CreateTimer(call.Arg(), call.Arg(), call.ArgAt(2), call.ArgAt(3))); + var shutdown = Substitute.For(); + shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var registration = FixedRegistration(); + + await Assert.That(async () => await new ServicePtyHandoff(fileSystem, time, shutdown).PrepareAsync( + _scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None)).ThrowsNothing(); + + _ = fileSystem.Received(2).TryReadAllBytesAsync(_scenario.SidecarPath(), CancellationToken.None); + _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any()); + _ = await _scenario.AssertNullSidecarAsync(); + } + + [Test] + [Arguments("io")] + [Arguments("argument")] + public async Task PrepareAsync_Should_Complete_Without_A_Sidecar_When_The_Publish_Fails(string failureKind) + { + await using var server = LoopbackHttpServer.Start(static _ => + Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); + var fileSystem = Substitute.For(); + fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); + Exception failure = failureKind == "io" + ? new IOException("The sidecar directory vanished.") + : new ArgumentException("The sidecar write was refused.", nameof(failureKind)); + fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .ThrowsAsync(failure); + + await Assert.That(async () => await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( + _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing(); + + _ = fileSystem.Received(1).TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + fileSystem.DidNotReceiveWithAnyArgs().Rename(default!, default!); + } + + [Test] + public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation_During_The_Publish() + { + await using var server = LoopbackHttpServer.Start(static _ => + Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); + using var caller = new CancellationTokenSource(); + var fileSystem = Substitute.For(); + fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); + fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(async call => + { + await caller.CancelOnWorkerAsync(); + return await Task.FromCanceled(call.Arg()); + }); + + var exception = await Assert.That(async () => await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( + _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token)).Throws(); + + await Assert.That(exception!.CancellationToken).IsEqualTo(caller.Token); + fileSystem.DidNotReceiveWithAnyArgs().Rename(default!, default!); + } + + [Test] + public async Task PrepareAsync_Should_Take_The_Fallback_When_The_Request_Bound_Expires() + { + // The ticket request and the shutdown both outlive their bound; neither expiry is the + // caller's cancellation, so both are failures the best-effort path absorbs. The shutdown + // seam records the call and holds it until its own bound cancels it, so the proof rests on + // the two timers alone, not on how fast a loaded host delivers a request. + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Hold(HttpStatusCode.OK, "{}")); + var shutdown = new BoundOutlivingShutdown(); + var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); + + await new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), TimeProvider.System, shutdown).PrepareAsync( + _scenario.RegistrationPath(), registration, TimeSpan.FromMilliseconds(200), CancellationToken.None); + + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + await Assert.That(shutdown.Calls).IsEqualTo(1); + await Assert.That(shutdown.Received).IsSameReferenceAs(registration); + await Assert.That(shutdown.EndedByItsBound).IsTrue(); + server.ReleaseResponses(); + } + + [Test] + public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Shutdown_Fails() + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static path => path == ShutdownPath + ? Json(HttpStatusCode.InternalServerError, "{}") + : Json(HttpStatusCode.NotFound, "{}")); + + await _scenario.PrepareAsync(server.Endpoint); + + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + await Assert.That(server.RequestPaths).Contains(ShutdownPath); + } + + [Test] + public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Shutdown_Route_Is_Absent_Too() + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); + + await _scenario.PrepareAsync(server.Endpoint); + + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + } + + private async Task AdvanceToJustBeforeRequestTimeoutAsync() + { + await _scenario.Clock.WaitForArmedAsync(RequestTimeout, PreparationHangGuard); + _scenario.Clock.Advance(RequestTimeout - TimeSpan.FromTicks(1)); + } + + private async Task AssertNullSidecarAfterExpiryAsync() + { + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + await Assert.That(_scenario.ReadSidecar()!.ExpiresAt) + .IsEqualTo(_scenario.Clock.GetUtcNow().ToUnixTimeMilliseconds() + 30_000d); + } + + /// A shutdown seam that records its call and answers only when its token is cancelled. + private sealed class BoundOutlivingShutdown : IServicePtyShutdown + { + public int Calls { get; private set; } + + public ServiceRegistration? Received { get; private set; } + + public bool EndedByItsBound { get; private set; } + + public async Task ShutdownAsync(ServiceRegistration registration, CancellationToken cancellationToken) + { + Calls++; + Received = registration; + var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using (cancellationToken.Register(() => held.TrySetCanceled(cancellationToken))) + { + try + { + _ = await held.Task.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + EndedByItsBound = true; + throw; + } + } + } + } + + /// An answer the server sends only after . + private static LoopbackHttpResponse Hold(HttpStatusCode status, string body) => + new() { StatusCode = status, ContentType = "application/json", Body = body, KeepOpen = true }; +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffScenario.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffScenario.cs index 9a76f13c..3af6dbe6 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffScenario.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffScenario.cs @@ -1,5 +1,6 @@ using System.Net; using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; using OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; using OpenCode.Sdk.Tests.Support; using Testably.Abstractions.Testing; @@ -13,9 +14,21 @@ internal sealed class ServicePtyHandoffScenario public const string Version = "2.0.3"; public const string Password = "s3cr3t-p455w0rd"; public const string HandoffPath = "/api/experimental/persistent-pty/handoff"; + public const string ShutdownPath = "/api/experimental/persistent-pty/shutdown"; + public const string FixedUrl = "http://127.0.0.1:49374"; public const long NowMilliseconds = 1_700_000_000_000; private static readonly DateTimeOffset Now = DateTimeOffset.FromUnixTimeMilliseconds(NowMilliseconds); + public static readonly FixtureLoader Fixtures = new(); + + /// + /// Bounds a wait for an event; it decides no verdict. A ticket request's arrival is awaited under it + /// too: the preparation's own bound runs on the scenario's manual clock, which these tests never + /// advance, so only this guard ends a wait for a request that never arrives, and the arrival + /// assertion after it names the miss. + /// + public static readonly TimeSpan PreparationHangGuard = TimeSpan.FromSeconds(10); + /// /// The request bound every preparation test hands the product, far past any loopback exchange a /// loaded runner still completes: the daemon double's answer, a recorded request, or the caller's @@ -31,6 +44,25 @@ internal sealed class ServicePtyHandoffScenario public static ServiceRegistration Registration(Uri endpoint) => new(SourceId, Version, endpoint.ToString(), endpoint, RegisteredPid, Password); + public static ServiceRegistration FixedRegistration() => + new(SourceId, Version, FixedUrl, new Uri(FixedUrl), RegisteredPid, Password); + + public Task PrepareAsync(Uri endpoint) => PrepareAsync(Registration(endpoint)); + + public async Task PrepareAsync(ServiceRegistration registration) => + await Handoff().PrepareAsync(RegistrationPath(), registration, RequestTimeout, CancellationToken.None); + + public ServicePtyHandoff Handoff() => new(new TestablyServiceFileSystem(FileSystem), Clock, new ServicePtyShutdown()); + + public async Task AssertNullSidecarAsync() + { + var sidecar = ReadSidecar(); + await Assert.That(sidecar).IsNotNull(); + await Assert.That(sidecar!.Handoff).IsNull(); + await Assert.That(sidecar.ExpiresAt).IsEqualTo(NowMilliseconds + 30_000d); + return sidecar; + } + public static LoopbackHttpResponse Pending(TaskCompletionSource arrived) { _ = arrived.TrySetResult(true); @@ -46,6 +78,8 @@ public static LoopbackHttpResponse Pending(TaskCompletionSource arrived) public static LoopbackHttpResponse Json(HttpStatusCode status, string body) => new() { StatusCode = status, ContentType = "application/json", Body = body }; + public static LoopbackHttpResponse NoContent() => new() { StatusCode = HttpStatusCode.NoContent }; + public string RegistrationPath() => FileSystem.Path.Combine(FileSystem.Path.GetTempPath(), "service-handoff", "service.json"); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs index 70453f0a..64e862b9 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs @@ -16,97 +16,18 @@ namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Handoff; /// /// The pinned client's sidecar orchestration (pty-handoff.ts) over the Testably /// filesystem double and a real loopback HTTP daemon double: publication through a temporary plus -/// rename, the skip-when-current fast path, the best-effort shutdown fallback that every failed or -/// refused ticket takes, the concurrent-prepare recheck, the environment adoption matrix, +/// rename, the skip-when-current fast path, the null-sidecar fallback for an unusable ticket, +/// the concurrent-prepare recheck, the environment adoption matrix, /// completion by source, and the idempotent clear. /// public sealed class ServicePtyHandoffTests { - private const string FixedUrl = "http://127.0.0.1:49374"; - private const string ShutdownPath = "/api/experimental/persistent-pty/shutdown"; private const long TicketExpiry = 1700000060000; - private static readonly FixtureLoader Fixtures = new(); private static readonly JsonElement Ticket = LoadTicket(); private readonly ServicePtyHandoffScenario _scenario = new(); - /// - /// Bounds a wait for an event; it decides no verdict. A ticket request's arrival is awaited under it - /// too: the preparation's own bound runs on the scenario's manual clock, which these tests never - /// advance, so only this guard ends a wait for a request that never arrives, and the arrival - /// assertion after it names the miss. - /// - private static readonly TimeSpan HangGuard = TimeSpan.FromSeconds(10); - - [Test] - public async Task PrepareAsync_Should_Expire_The_Ticket_On_The_Injected_Clock() - { - _scenario.EnsureSidecarDirectory(); - var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - await using var server = LoopbackHttpServer.Start(_ => Pending(entered)); - var shutdown = Substitute.For(); - shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); - using var caller = new CancellationTokenSource(); - var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown) - .PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, caller.Token); - try - { - await entered.Task.WaitAsync(HangGuard); - await AdvanceToJustBeforeRequestTimeoutAsync(); - await Assert.That(pending.IsCompleted).IsFalse(); - _ = shutdown.DidNotReceiveWithAnyArgs().ShutdownAsync(default!, default); - _scenario.Clock.Advance(TimeSpan.FromTicks(1)); - await pending.WaitAsync(HangGuard); - - _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any()); - await AssertNullSidecarAfterExpiryAsync(); - } - finally - { - await caller.CancelOnWorkerAsync(); - server.ReleaseResponses(); - } - } - - [Test] - public async Task PrepareAsync_Should_Expire_The_Fallback_On_The_Injected_Clock() - { - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); - var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var shutdown = Substitute.For(); - CancellationToken received = default; - shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(async call => - { - received = call.Arg(); - var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using var cancellation = received.Register(() => held.TrySetCanceled(received)); - entered.TrySetResult(); - await held.Task; - }); - using var caller = new CancellationTokenSource(); - var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown) - .PrepareAsync(_scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token); - try - { - await entered.Task.WaitAsync(HangGuard); - await AdvanceToJustBeforeRequestTimeoutAsync(); - await Assert.That(received.IsCancellationRequested).IsFalse(); - await Assert.That(pending.IsCompleted).IsFalse(); - _scenario.Clock.Advance(TimeSpan.FromTicks(1)); - await pending.WaitAsync(HangGuard); - - await Assert.That(received.IsCancellationRequested).IsTrue(); - await AssertNullSidecarAfterExpiryAsync(); - } - finally - { - await caller.CancelOnWorkerAsync(); - } - } - [Test] public async Task PrepareAsync_Should_Publish_A_Sidecar_From_The_Handoff_Ticket() { @@ -115,7 +36,7 @@ public async Task PrepareAsync_Should_Publish_A_Sidecar_From_The_Handoff_Ticket( Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - await PrepareAsync(registration); + await _scenario.PrepareAsync(registration); await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath], CollectionOrdering.Matching); var sidecar = _scenario.ReadSidecar(); @@ -136,7 +57,7 @@ public async Task PrepareAsync_Should_Reuse_A_Fresh_Matching_Sidecar_Without_Con var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); Seed(_scenario.SidecarPath(), Sidecar(registration, handoff: null, NowMilliseconds + 60_000).ToUtf8Json()); - await PrepareAsync(registration); + await _scenario.PrepareAsync(registration); await Assert.That(server.Requests).IsEmpty(); await Assert.That(_scenario.ReadSidecar()).IsNotNull(); @@ -151,9 +72,9 @@ public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Si : Json(HttpStatusCode.NotFound, "{}")); var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - await PrepareAsync(registration); + await _scenario.PrepareAsync(registration); - _ = await AssertNullSidecarAsync(); + _ = await _scenario.AssertNullSidecarAsync(); await Assert.That(server.RequestPaths).Contains(ShutdownPath); } @@ -168,7 +89,7 @@ public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Si _scenario.EnsureSidecarDirectory(); await using var server = StartShutdownFallbackServer(fixture); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); await AssertShutdownFallbackAsync(server); } @@ -181,7 +102,7 @@ public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_For_A_Ticket_Wi _scenario.EnsureSidecarDirectory(); await using var server = StartShutdownFallbackServer(fixture); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); await AssertShutdownFallbackAsync(server); await Assert.That(_scenario.TemporaryFiles()).IsEmpty(); @@ -189,7 +110,7 @@ public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_For_A_Ticket_Wi private async Task AssertShutdownFallbackAsync(LoopbackHttpServer server) { - _ = await AssertNullSidecarAsync(); + _ = await _scenario.AssertNullSidecarAsync(); await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath, ShutdownPath], CollectionOrdering.Matching); } @@ -201,7 +122,7 @@ public async Task PrepareAsync_Should_Admit_Trailing_Whitespace_And_Publish_The_ using var expected = JsonDocument.Parse(body); await using var server = LoopbackHttpServer.Start(_ => Json(HttpStatusCode.OK, body)); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); var sidecar = _scenario.ReadSidecar(); await Assert.That(sidecar).IsNotNull(); @@ -209,20 +130,6 @@ public async Task PrepareAsync_Should_Admit_Trailing_Whitespace_And_Publish_The_ await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath], CollectionOrdering.Matching); } - [Test] - public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Sidecar_When_The_Daemon_Answers_An_Error() - { - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static path => path == ShutdownPath - ? NoContent() - : Json(HttpStatusCode.InternalServerError, "{}")); - - await PrepareAsync(server.Endpoint); - - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath, ShutdownPath], CollectionOrdering.Matching); - } - [Test] [Arguments("http://127.0.0.1:49374?query=1")] [Arguments("http://127.0.0.1:49374#fragment")] @@ -242,85 +149,11 @@ public async Task PrepareAsync_Should_Fall_Back_When_The_Registered_Endpoint_Is_ .PrepareAsync(_scenario.RegistrationPath(), registration!, RequestTimeout, CancellationToken.None); _ = shutdown.Received(1).ShutdownAsync(registration!, Arg.Any()); - var sidecar = await AssertNullSidecarAsync(); + var sidecar = await _scenario.AssertNullSidecarAsync(); await Assert.That(sidecar.SourceUrl).IsEqualTo(registration!.Url); await Assert.That(_scenario.TemporaryFiles()).IsEmpty(); } - [Test] - [Arguments("options")] - [Arguments(null)] - [Arguments("io")] - public async Task PrepareAsync_Should_Swallow_A_Failed_Shutdown_Fallback(string? parameterName) - { - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); - Exception failure = parameterName == "io" - ? new IOException("The shutdown failed.") - : new ArgumentException("The shutdown implementation rejected another parameter.", parameterName); - var shutdown = Substitute.For(); - shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.FromException(failure)); - var handoff = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown); - - await Assert.That(async () => await handoff.PrepareAsync( - _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing(); - - _ = await AssertNullSidecarAsync(); - } - - [Test] - public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_When_The_Ticket_Request_Fails_With_An_IO_Error() - { - _scenario.EnsureSidecarDirectory(); - var files = new TestablyServiceFileSystem(_scenario.FileSystem); - var fileSystem = Substitute.For(); - fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()) - .Returns(call => files.TryReadAllBytesAsync(call.Arg(), call.Arg())); - fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) - .Returns(call => files.TryCreateExclusiveAsync(call.Arg(), call.Arg>(), call.Arg())); - fileSystem.When(static system => system.Rename(Arg.Any(), Arg.Any())) - .Do(call => files.Rename(call.ArgAt(0), call.ArgAt(1))); - var time = Substitute.For(); - time.GetUtcNow().Returns(_scenario.Clock.GetUtcNow()); - // Fail the ticket request's bound once, before transport can wrap the IOException; - // the shutdown fallback gets a working bound from the same clock seam. - time.CreateTimer(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(_ => throw new IOException("The ticket request's timer could not be created."), - call => _scenario.Clock.CreateTimer(call.Arg(), call.Arg(), call.ArgAt(2), call.ArgAt(3))); - var shutdown = Substitute.For(); - shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); - var registration = FixedRegistration(); - - await Assert.That(async () => await new ServicePtyHandoff(fileSystem, time, shutdown).PrepareAsync( - _scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None)).ThrowsNothing(); - - _ = fileSystem.Received(2).TryReadAllBytesAsync(_scenario.SidecarPath(), CancellationToken.None); - _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any()); - _ = await AssertNullSidecarAsync(); - } - - [Test] - [Arguments("io")] - [Arguments("argument")] - public async Task PrepareAsync_Should_Complete_Without_A_Sidecar_When_The_Publish_Fails(string failureKind) - { - await using var server = LoopbackHttpServer.Start(static _ => - Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); - var fileSystem = Substitute.For(); - fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); - Exception failure = failureKind == "io" - ? new IOException("The sidecar directory vanished.") - : new ArgumentException("The sidecar write was refused.", nameof(failureKind)); - fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) - .ThrowsAsync(failure); - - await Assert.That(async () => await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( - _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing(); - - _ = fileSystem.Received(1).TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()); - fileSystem.DidNotReceiveWithAnyArgs().Rename(default!, default!); - } - /// /// The concurrent caller's sidecar lands once the ticket request has reached the daemon double and /// before its failed answer is released, so the recheck finds it: the preparation returns without @@ -351,10 +184,10 @@ public async Task PrepareAsync_Should_Return_When_A_Concurrent_Caller_Published_ respondingServer = server; registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - var pending = Handoff().PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None); + var pending = _scenario.Handoff().PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None); await AssertTicketRequestArrivedAsync(arrived, pending); - await pending.WaitAsync(HangGuard); + await pending.WaitAsync(PreparationHangGuard); await Assert.That(server.RequestPaths).DoesNotContain(ShutdownPath); await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNotNull(); @@ -462,7 +295,7 @@ public async Task CompleteAsync_Should_Clear_A_Foreign_Source_Sidecar() SeedFreshSidecar(Ticket); var winner = new ServiceRegistration(SourceId, ServicePtyHandoffScenario.Version, FixedUrl, new Uri(FixedUrl), RegisteredPid + 1, Password); - await Handoff().CompleteAsync(_scenario.RegistrationPath(), winner, CancellationToken.None); + await _scenario.Handoff().CompleteAsync(_scenario.RegistrationPath(), winner, CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNull(); } @@ -472,7 +305,7 @@ public async Task CompleteAsync_Should_Keep_A_Same_Source_Sidecar_Even_When_Stal { Seed(_scenario.SidecarPath(), Sidecar(FixedRegistration(), Ticket, NowMilliseconds - 1).ToUtf8Json()); - await Handoff().CompleteAsync(_scenario.RegistrationPath(), FixedRegistration(), CancellationToken.None); + await _scenario.Handoff().CompleteAsync(_scenario.RegistrationPath(), FixedRegistration(), CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNotNull(); } @@ -480,7 +313,7 @@ public async Task CompleteAsync_Should_Keep_A_Same_Source_Sidecar_Even_When_Stal [Test] public async Task CompleteAsync_Should_Do_Nothing_When_The_Sidecar_Is_Absent() { - await Handoff().CompleteAsync(_scenario.RegistrationPath(), FixedRegistration(), CancellationToken.None); + await _scenario.Handoff().CompleteAsync(_scenario.RegistrationPath(), FixedRegistration(), CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNull(); } @@ -490,10 +323,10 @@ public async Task ClearAsync_Should_Remove_The_Sidecar_And_Be_Idempotent() { SeedFreshSidecar(handoff: null); - await Handoff().ClearAsync(_scenario.RegistrationPath(), CancellationToken.None); + await _scenario.Handoff().ClearAsync(_scenario.RegistrationPath(), CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNull(); - await Handoff().ClearAsync(_scenario.RegistrationPath(), CancellationToken.None); + await _scenario.Handoff().ClearAsync(_scenario.RegistrationPath(), CancellationToken.None); } [Test] @@ -515,7 +348,7 @@ public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation() var cancelled = new CancellationToken(canceled: true); _ = await Assert - .That(async () => await Handoff().PrepareAsync(_scenario.RegistrationPath(), FixedRegistration(), RequestTimeout, cancelled)) + .That(async () => await _scenario.Handoff().PrepareAsync(_scenario.RegistrationPath(), FixedRegistration(), RequestTimeout, cancelled)) .Throws(); } @@ -531,7 +364,7 @@ public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation_During_The_Tic await using var server = LoopbackHttpServer.Start(path => path == ShutdownPath ? NoContent() : Pending(arrived)); using var caller = new CancellationTokenSource(); - var pending = Handoff().PrepareAsync(_scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token); + var pending = _scenario.Handoff().PrepareAsync(_scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token); await AssertTicketRequestArrivedAsync(arrived, pending); await caller.CancelOnWorkerAsync(); @@ -550,28 +383,6 @@ public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation_During_The_Tic server.ReleaseResponses(); } - [Test] - public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation_During_The_Publish() - { - await using var server = LoopbackHttpServer.Start(static _ => - Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); - using var caller = new CancellationTokenSource(); - var fileSystem = Substitute.For(); - fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); - fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) - .Returns(async call => - { - await caller.CancelOnWorkerAsync(); - return await Task.FromCanceled(call.Arg()); - }); - - var exception = await Assert.That(async () => await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( - _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token)).Throws(); - - await Assert.That(exception!.CancellationToken).IsEqualTo(caller.Token); - fileSystem.DidNotReceiveWithAnyArgs().Rename(default!, default!); - } - /// The pinned client's environment reads a JSON-null ticket as no ticket and removes the variable. [Test] public async Task EnvironmentAsync_Should_Remove_The_Variable_For_A_Fresh_Matching_Sidecar_Without_A_Ticket() @@ -585,28 +396,6 @@ public async Task EnvironmentAsync_Should_Remove_The_Variable_For_A_Fresh_Matchi await Assert.That(overlay["KEEP"]).IsEqualTo("1"); } - [Test] - public async Task PrepareAsync_Should_Take_The_Fallback_When_The_Request_Bound_Expires() - { - // The ticket request and the shutdown both outlive their bound; neither expiry is the - // caller's cancellation, so both are failures the best-effort path absorbs. The shutdown - // seam records the call and holds it until its own bound cancels it, so the proof rests on - // the two timers alone, not on how fast a loaded host delivers a request. - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static _ => Hold(HttpStatusCode.OK, "{}")); - var shutdown = new BoundOutlivingShutdown(); - var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - - await new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), TimeProvider.System, shutdown).PrepareAsync( - _scenario.RegistrationPath(), registration, TimeSpan.FromMilliseconds(200), CancellationToken.None); - - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - await Assert.That(shutdown.Calls).IsEqualTo(1); - await Assert.That(shutdown.Received).IsSameReferenceAs(registration); - await Assert.That(shutdown.EndedByItsBound).IsTrue(); - server.ReleaseResponses(); - } - [Test] public async Task PrepareAsync_Should_Publish_The_Ticket_Exactly_As_The_Route_Answered_It() { @@ -616,7 +405,7 @@ public async Task PrepareAsync_Should_Publish_The_Ticket_Exactly_As_The_Route_An _scenario.EnsureSidecarDirectory(); await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.OK, "{\"handoff\":" + ticket + "}")); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); // The exchange first, so a recorded shutdown identifies the null-sidecar fallback. await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath], CollectionOrdering.Matching); @@ -630,9 +419,9 @@ public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Route_Answ await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-null.json"))); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); - _ = await AssertNullSidecarAsync(); + _ = await _scenario.AssertNullSidecarAsync(); } [Test] @@ -642,37 +431,12 @@ public async Task PrepareAsync_Should_Send_The_Registration_Credential() await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); await Assert.That(server.Requests.Single().Headers["Authorization"]) .IsEqualTo("Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("opencode:" + Password))); } - [Test] - public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Shutdown_Fails() - { - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static path => path == ShutdownPath - ? Json(HttpStatusCode.InternalServerError, "{}") - : Json(HttpStatusCode.NotFound, "{}")); - - await PrepareAsync(server.Endpoint); - - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - await Assert.That(server.RequestPaths).Contains(ShutdownPath); - } - - [Test] - public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Shutdown_Route_Is_Absent_Too() - { - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); - - await PrepareAsync(server.Endpoint); - - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - } - [Test] public async Task PrepareAsync_Should_Recheck_For_A_Concurrent_Sidecar_Before_Shutting_The_Daemon_Down() { @@ -692,7 +456,7 @@ public async Task PrepareAsync_Should_Recheck_For_A_Concurrent_Sidecar_Before_Sh }); registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - await PrepareAsync(registration); + await _scenario.PrepareAsync(registration); await Assert.That(server.RequestPaths).DoesNotContain(ShutdownPath); await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNotNull(); @@ -706,7 +470,7 @@ public async Task CompleteAsync_Should_Clear_A_Sidecar_Whose_Source_Differs_In_O SeedFreshSidecar(Ticket); var winner = new ServiceRegistration(id, ServicePtyHandoffScenario.Version, address, new Uri(address), RegisteredPid, Password); - await Handoff().CompleteAsync(_scenario.RegistrationPath(), winner, CancellationToken.None); + await _scenario.Handoff().CompleteAsync(_scenario.RegistrationPath(), winner, CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNull(); } @@ -728,58 +492,26 @@ public async Task EnvironmentAsync_Should_Adopt_When_The_Registration_Cannot_Be_ private static async Task AssertTicketRequestArrivedAsync(TaskCompletionSource arrived, Task pending) { Task[] arrival = [arrived.Task, pending]; - _ = await BoundedWait.CompletesWithinAsync(Task.WhenAny(arrival), HangGuard, TimeProvider.System); + _ = await BoundedWait.CompletesWithinAsync(Task.WhenAny(arrival), PreparationHangGuard, TimeProvider.System); await Assert.That(arrived.Task.IsCompleted).IsTrue(); } - private async Task AdvanceToJustBeforeRequestTimeoutAsync() - { - await _scenario.Clock.WaitForArmedAsync(RequestTimeout, HangGuard); - _scenario.Clock.Advance(RequestTimeout - TimeSpan.FromTicks(1)); - } - - private async Task AssertNullSidecarAfterExpiryAsync() - { - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - await Assert.That(_scenario.ReadSidecar()!.ExpiresAt) - .IsEqualTo(_scenario.Clock.GetUtcNow().ToUnixTimeMilliseconds() + 30_000d); - } - private static JsonElement LoadTicket() { using var document = JsonDocument.Parse(Fixtures.LoadJson("BackgroundService.pty-handoff-valid.json")); return document.RootElement.GetProperty("handoff").Clone(); } - private Task PrepareAsync(Uri endpoint) => PrepareAsync(ServicePtyHandoffScenario.Registration(endpoint)); - - private async Task PrepareAsync(ServiceRegistration registration) => - await Handoff().PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None); - private static LoopbackHttpServer StartShutdownFallbackServer(string fixture) => LoopbackHttpServer.Start(path => path == ShutdownPath ? NoContent() : Json(HttpStatusCode.OK, Fixtures.LoadJson(fixture))); - private async Task AssertNullSidecarAsync() - { - var sidecar = _scenario.ReadSidecar(); - await Assert.That(sidecar).IsNotNull(); - await Assert.That(sidecar!.Handoff).IsNull(); - await Assert.That(sidecar.ExpiresAt).IsEqualTo(NowMilliseconds + 30_000d); - return sidecar; - } - private void SeedFreshSidecar(JsonElement? handoff) => Seed(_scenario.SidecarPath(), Sidecar(FixedRegistration(), handoff, NowMilliseconds + 60_000).ToUtf8Json()); private Task> EnvironmentAsync(IReadOnlyDictionary? caller) => - Handoff().EnvironmentAsync(_scenario.RegistrationPath(), caller, CancellationToken.None); - - private ServicePtyHandoff Handoff() => new(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, new ServicePtyShutdown()); - - private static ServiceRegistration FixedRegistration() => - new(SourceId, ServicePtyHandoffScenario.Version, FixedUrl, new Uri(FixedUrl), RegisteredPid, Password); + _scenario.Handoff().EnvironmentAsync(_scenario.RegistrationPath(), caller, CancellationToken.None); private static PtyHandoffSidecar Sidecar(ServiceRegistration registration, JsonElement? handoff, double expiresAt) => new() @@ -799,41 +531,6 @@ private static string FractionalSourceSidecar() => private static Dictionary Caller() => new(StringComparer.Ordinal) { ["KEEP"] = "1" }; - /// A shutdown seam that records its call and answers only when its token is cancelled. - private sealed class BoundOutlivingShutdown : IServicePtyShutdown - { - public int Calls { get; private set; } - - public ServiceRegistration? Received { get; private set; } - - public bool EndedByItsBound { get; private set; } - - public async Task ShutdownAsync(ServiceRegistration registration, CancellationToken cancellationToken) - { - Calls++; - Received = registration; - var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using (cancellationToken.Register(() => held.TrySetCanceled(cancellationToken))) - { - try - { - _ = await held.Task.ConfigureAwait(false); - } - catch (OperationCanceledException) - { - EndedByItsBound = true; - throw; - } - } - } - } - - /// An answer the server sends only after . - private static LoopbackHttpResponse Hold(HttpStatusCode status, string body) => - new() { StatusCode = status, ContentType = "application/json", Body = body, KeepOpen = true }; - - private static LoopbackHttpResponse NoContent() => new() { StatusCode = HttpStatusCode.NoContent }; - private void Seed(string path, string content) => Seed(path, Encoding.UTF8.GetBytes(content)); private void Seed(string path, byte[] bytes) From b1c32308a33e85c6105c72230dc34594217c3f17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Sun, 15 Nov 2026 20:35:23 +0300 Subject: [PATCH 4/4] fix(hosting): address inner handoff review findings (#895) --- CHANGELOG.md | 2 +- .../BackgroundService/Internal/Handoff/ServicePtyHandoff.cs | 3 ++- .../Handoff/ServicePtyHandoffBestEffortTests.cs | 6 ++++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc3bac0a..4279747d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +31,7 @@ The next SDK version is **2.0.0**, on the same opencode **2.3.0** pin already re ### 🔧 Changes - `StopAsync` and the `EnsureAsync` version-mismatch replacement treat a failed persistent-terminal handoff or clear as best-effort, whatever the exception type, as opencode's CLI does. Before: a failure other than an `OpenCodeServerException` ended `StopAsync` before it terminated the old service, and ended `EnsureAsync` at once. After: `StopAsync` terminates the old service; `EnsureAsync` keeps polling, and the last replacement failure becomes the inner exception of its timeout. The caller's cancellation still ends both. (#871) -- A failed persistent-terminal ticket request, terminal-shutdown fallback or sidecar publish, whatever its exception type, no longer ends the handoff preparation: the replacement then starts without the terminals, as with opencode's CLI. The caller's cancellation still ends the preparation. (#895) +- `StopAsync` with `Pty = Handoff` and the `EnsureAsync` replacement treat every persistent-terminal ticket-request, shutdown fallback or sidecar-publish failure as best-effort, as opencode's CLI does. Before: a failure other than an `OpenCodeException` could end the handoff preparation before terminal shutdown or empty-ticket publication completed. After: a failed ticket request still takes the terminal-shutdown fallback and publishes the empty handoff ticket; a failed shutdown no longer skips publication, and a failed publish no longer ends the preparation. The caller's cancellation still ends it. (#895) - The packages' .NET dependency floors move from `10.0.13` to the `10.0.15` servicing release: on `net472` and `netstandard2.0`, `System.Text.Json`, `System.Threading.Channels`, `System.Collections.Immutable`, `Microsoft.Bcl.AsyncInterfaces`, `Microsoft.Bcl.Memory` and `Microsoft.Bcl.TimeProvider`; in `OpenCodeDotNet.Sdk.Extensions`, on every target, `Microsoft.Extensions.DependencyInjection.Abstractions` and `Microsoft.Extensions.Options.ConfigurationExtensions`. No security advisory of the .NET 10.0.14 or 10.0.15 release lists these packages. - Event Types are copied and validated at the call and selected locally; physical attempts send no Types query. The whole bus is decoded once, so malformed unselected traffic reconnects every subscriber. Event and metadata instances are shared references, not deep-frozen graphs; consumers treat them as read-only. Queue bounds count events, not bytes, and subscriber count remains unbounded. - Event subscriptions accept but no longer forward per-call Location. Every shared attempt sends only the client's ambient header snapshot; other operations retain their existing override behavior. diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs index 632256f7..f38850f1 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs @@ -64,6 +64,7 @@ public async Task PrepareAsync( } catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { + // The SDK drops request failures where upstream warns (prepare in pty-handoff.ts); it has no warning channel here. // Another caller may already have prepared and stopped this server; otherwise the // daemon's terminals are shut down and the replacement starts without a handoff. if (await IsFreshMatchAsync(sidecarPath, registration, cancellationToken).ConfigureAwait(false)) @@ -190,7 +191,7 @@ private PtyHandoffSidecar Parse(ServiceHandoffTicketResponse answer, ServiceRegi /// [SlopwatchSuppress( "SW003", - "The pinned client's prepare catches every shutdown fallback failure (prepare in pty-handoff.ts); the SDK has no warning channel here, so request failures are dropped where upstream warns and shutdown failures are dropped as upstream does. Only the caller's cancellation propagates, so the replacement starts without the terminals.")] + "The pinned client's prepare drops every shutdown fallback failure with .catch(() => {}) (prepare in pty-handoff.ts); the SDK drops it silently as upstream does. Only the caller's cancellation propagates, and a null sidecar is published next.")] private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan timeout, CancellationToken cancellationToken) { using var deadline = TimedCancellation.Create(timeout, time); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs index 7c603d8b..f1cf0fa5 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs @@ -98,7 +98,6 @@ public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Si [Test] [Arguments("options")] - [Arguments(null)] [Arguments("io")] public async Task PrepareAsync_Should_Swallow_A_Failed_Shutdown_Fallback(string? parameterName) { @@ -114,6 +113,7 @@ public async Task PrepareAsync_Should_Swallow_A_Failed_Shutdown_Fallback(string? await Assert.That(async () => await handoff.PrepareAsync( _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing(); + _ = shutdown.Received(1).ShutdownAsync(Arg.Any(), Arg.Any()); _ = await _scenario.AssertNullSidecarAsync(); } @@ -121,6 +121,7 @@ await Assert.That(async () => await handoff.PrepareAsync( public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_When_The_Ticket_Request_Fails_With_An_IO_Error() { _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); var files = new TestablyServiceFileSystem(_scenario.FileSystem); var fileSystem = Substitute.For(); fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()) @@ -138,11 +139,12 @@ public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_When_The_Ticket call => _scenario.Clock.CreateTimer(call.Arg(), call.Arg(), call.ArgAt(2), call.ArgAt(3))); var shutdown = Substitute.For(); shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); - var registration = FixedRegistration(); + var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); await Assert.That(async () => await new ServicePtyHandoff(fileSystem, time, shutdown).PrepareAsync( _scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None)).ThrowsNothing(); + await Assert.That(server.Requests).IsEmpty(); _ = fileSystem.Received(2).TryReadAllBytesAsync(_scenario.SidecarPath(), CancellationToken.None); _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any()); _ = await _scenario.AssertNullSidecarAsync();