Skip to content

Commit d3c1b43

Browse files
committed
fix(local-ai): fail closed when route proof is lost
Co-authored-by: Copilot App <[email protected]> Copilot-Session: 7ef70da5-e94c-4bcf-9cb6-a0acee52c9c4
1 parent a9fcdcd commit d3c1b43

2 files changed

Lines changed: 303 additions & 18 deletions

File tree

‎src/OpenClaw.Connection/LocalAi/LlamaServerRuntimeService.cs‎

Lines changed: 105 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -334,11 +334,40 @@ private async Task<LocalAiRuntimeSnapshot> RefreshCoreAsync(CancellationToken ca
334334
LocalAiResolvedInstall install = _install!;
335335
EndpointOwnershipObservation ownership = DiscoverOwnedEndpoint(install, _managedProcess);
336336
if (!ownership.IsComplete)
337-
return Publish(LocalAiRuntimeState.Conflict, LocalAiOwnership.None, "TCP listener ownership could not be determined.");
337+
{
338+
LocalAiRuntimeSnapshot? failure = await QuiesceOrStopAsync(
339+
install,
340+
cancellationToken)
341+
.ConfigureAwait(false);
342+
return failure ?? Publish(
343+
LocalAiRuntimeState.Conflict,
344+
LocalAiOwnership.None,
345+
"TCP listener ownership could not be determined.");
346+
}
338347
if (ownership.ConflictDetail is not null)
339-
return Publish(LocalAiRuntimeState.Conflict, LocalAiOwnership.None, ownership.ConflictDetail);
348+
{
349+
LocalAiRuntimeSnapshot? failure = await QuiesceOrStopAsync(
350+
install,
351+
cancellationToken)
352+
.ConfigureAwait(false);
353+
return failure ?? Publish(
354+
LocalAiRuntimeState.Conflict,
355+
LocalAiOwnership.None,
356+
ownership.ConflictDetail);
357+
}
340358
if (ownership.Endpoint is null)
341-
return Publish(LocalAiRuntimeState.Starting, LocalAiOwnership.CompanionManaged, "The local AI router has not opened its endpoint yet.", _managedProcess.ProcessId, _managedProcess.StartedAtUtc);
359+
{
360+
LocalAiRuntimeSnapshot? failure = await QuiesceOrStopAsync(
361+
install,
362+
cancellationToken)
363+
.ConfigureAwait(false);
364+
return failure ?? Publish(
365+
LocalAiRuntimeState.Starting,
366+
LocalAiOwnership.CompanionManaged,
367+
"The local AI router has not opened its endpoint yet.",
368+
_managedProcess.ProcessId,
369+
_managedProcess.StartedAtUtc);
370+
}
342371

343372
LlamaServerRouterProbeResult probe = await _client.ProbeManagedModelAsync(
344373
ownership.Endpoint,
@@ -348,8 +377,24 @@ private async Task<LocalAiRuntimeSnapshot> RefreshCoreAsync(CancellationToken ca
348377
.ConfigureAwait(false);
349378
if (probe.IsReadyForManagedModel(install.ModelPath))
350379
{
351-
if (_snapshot.State != LocalAiRuntimeState.Healthy)
380+
bool endpointChanged = install.Endpoint != ownership.Endpoint;
381+
if (_snapshot.State != LocalAiRuntimeState.Healthy || endpointChanged)
352382
{
383+
if (endpointChanged && _snapshot.State == LocalAiRuntimeState.Healthy)
384+
{
385+
LocalAiRuntimeSnapshot? failure = await QuiesceOrStopAsync(
386+
install,
387+
cancellationToken)
388+
.ConfigureAwait(false);
389+
if (failure is not null)
390+
return failure;
391+
}
392+
393+
install = await BindVerifiedEndpointAsync(
394+
install,
395+
ownership.Endpoint,
396+
cancellationToken)
397+
.ConfigureAwait(false);
353398
LocalAiEndpointLifecycleResult published = await _options.EndpointLifecycle
354399
.PublishAsync(install, cancellationToken)
355400
.ConfigureAwait(false);
@@ -367,18 +412,12 @@ private async Task<LocalAiRuntimeSnapshot> RefreshCoreAsync(CancellationToken ca
367412
return PublishHealthy(probe);
368413
}
369414

370-
LocalAiEndpointLifecycleResult quiesced = await _options.EndpointLifecycle
371-
.QuiesceAsync(install, cancellationToken)
415+
LocalAiRuntimeSnapshot? quiesceFailure = await QuiesceOrStopAsync(
416+
install,
417+
cancellationToken)
372418
.ConfigureAwait(false);
373-
if (!quiesced.Success)
374-
{
375-
return Publish(
376-
LocalAiRuntimeState.Failed,
377-
LocalAiOwnership.CompanionManaged,
378-
quiesced.Detail ?? "The Local AI gateway provider could not be safely disabled.",
379-
_managedProcess.ProcessId,
380-
_managedProcess.StartedAtUtc);
381-
}
419+
if (quiesceFailure is not null)
420+
return quiesceFailure;
382421

383422
return Publish(
384423
LocalAiRuntimeState.Starting,
@@ -388,6 +427,57 @@ private async Task<LocalAiRuntimeSnapshot> RefreshCoreAsync(CancellationToken ca
388427
_managedProcess.StartedAtUtc);
389428
}
390429

430+
private async Task<LocalAiRuntimeSnapshot?> QuiesceOrStopAsync(
431+
LocalAiResolvedInstall install,
432+
CancellationToken cancellationToken)
433+
{
434+
LocalAiEndpointLifecycleResult? quiesced = null;
435+
try
436+
{
437+
quiesced = await _options.EndpointLifecycle
438+
.QuiesceAsync(install, cancellationToken)
439+
.ConfigureAwait(false);
440+
}
441+
finally
442+
{
443+
if (quiesced is null)
444+
{
445+
++_generation;
446+
await DisposeManagedProcessAsync(CancellationToken.None).ConfigureAwait(false);
447+
Publish(
448+
LocalAiRuntimeState.Failed,
449+
LocalAiOwnership.None,
450+
"The Local AI gateway provider withdrawal did not complete.");
451+
}
452+
}
453+
if (quiesced.Success)
454+
return null;
455+
456+
++_generation;
457+
await DisposeManagedProcessAsync(CancellationToken.None).ConfigureAwait(false);
458+
return Publish(
459+
LocalAiRuntimeState.Failed,
460+
LocalAiOwnership.None,
461+
quiesced.Detail ?? "The Local AI gateway provider could not be safely disabled.");
462+
}
463+
464+
private async Task<LocalAiResolvedInstall> BindVerifiedEndpointAsync(
465+
LocalAiResolvedInstall install,
466+
Uri endpoint,
467+
CancellationToken cancellationToken)
468+
{
469+
if (install.Endpoint == endpoint)
470+
return install;
471+
472+
LocalAiInstallManifest verifiedManifest = install.Manifest with
473+
{
474+
Endpoint = endpoint.AbsoluteUri,
475+
};
476+
await _manifestStore.SaveAsync(verifiedManifest, cancellationToken).ConfigureAwait(false);
477+
_install = _manifestStore.ResolveAndValidate(verifiedManifest);
478+
return _install;
479+
}
480+
391481
private async Task<bool> TryLoadInstallAsync(CancellationToken cancellationToken)
392482
{
393483
try

‎tests/OpenClaw.Connection.Tests/LocalAiPortLifecycleTests.cs‎

Lines changed: 198 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,181 @@ public async Task Refresh_UpdatesPublicationWhenManagedModelReadinessChanges()
225225
Assert.Equal(["probe:28773", "publish:28773"], events);
226226
}
227227

228+
[Theory]
229+
[InlineData(RefreshOwnershipLoss.Incomplete, LocalAiRuntimeState.Conflict)]
230+
[InlineData(RefreshOwnershipLoss.Conflict, LocalAiRuntimeState.Conflict)]
231+
[InlineData(RefreshOwnershipLoss.MissingEndpoint, LocalAiRuntimeState.Starting)]
232+
public async Task Refresh_QuiescesPublishedRouteWhenEndpointOwnershipIsLost(
233+
RefreshOwnershipLoss ownershipLoss,
234+
LocalAiRuntimeState expectedState)
235+
{
236+
using var temp = new TempDirectory("local-ai-port-");
237+
LocalAiPaths paths = await PrepareInstallAsync(temp);
238+
var events = new List<string>();
239+
var platform = new FakePlatform();
240+
var host = new FakeProcessHost(platform, events, selectedPort: 28_775);
241+
await using var runtime = CreateRuntime(
242+
paths,
243+
host,
244+
platform,
245+
new FakeClient(events),
246+
new FakeLifecycle(events));
247+
LocalAiRuntimeSnapshot started = await runtime.EnsureStartedAsync();
248+
Assert.Equal(LocalAiRuntimeState.Healthy, started.State);
249+
events.Clear();
250+
251+
switch (ownershipLoss)
252+
{
253+
case RefreshOwnershipLoss.Incomplete:
254+
platform.Ipv4Complete = false;
255+
break;
256+
case RefreshOwnershipLoss.Conflict:
257+
platform.Listeners[0] = platform.Listeners[0] with { Address = IPAddress.Any };
258+
break;
259+
case RefreshOwnershipLoss.MissingEndpoint:
260+
platform.Listeners.Clear();
261+
break;
262+
default:
263+
throw new InvalidOperationException("Unknown ownership-loss case.");
264+
}
265+
266+
LocalAiRuntimeSnapshot refreshed = await runtime.RefreshAsync();
267+
268+
Assert.Equal(expectedState, refreshed.State);
269+
Assert.Equal(["quiesce"], events);
270+
Assert.False(host.Process!.HasExited);
271+
}
272+
273+
[Fact]
274+
public async Task Refresh_QuiesceFailureStopsUnverifiedManagedProcess()
275+
{
276+
using var temp = new TempDirectory("local-ai-port-");
277+
LocalAiPaths paths = await PrepareInstallAsync(temp);
278+
var events = new List<string>();
279+
var platform = new FakePlatform();
280+
var host = new FakeProcessHost(platform, events, selectedPort: 28_776);
281+
var client = new FakeClient(events, (expectedModelPath, probeNumber) => probeNumber == 1
282+
? ReadyProbe(expectedModelPath)
283+
: new(
284+
false,
285+
LocalAiModelAvailabilityState.Unknown,
286+
null,
287+
"The managed model is not ready."));
288+
var lifecycle = new FakeLifecycle(events);
289+
await using var runtime = CreateRuntime(paths, host, platform, client, lifecycle);
290+
LocalAiRuntimeSnapshot started = await runtime.EnsureStartedAsync();
291+
Assert.Equal(LocalAiRuntimeState.Healthy, started.State);
292+
events.Clear();
293+
lifecycle.FailQuiesce = true;
294+
295+
LocalAiRuntimeSnapshot refreshed = await runtime.RefreshAsync();
296+
297+
Assert.Equal(LocalAiRuntimeState.Failed, refreshed.State);
298+
Assert.Equal(LocalAiOwnership.None, refreshed.Ownership);
299+
Assert.Null(refreshed.ProcessId);
300+
Assert.True(host.Process!.HasExited);
301+
Assert.Equal(["probe:28776", "quiesce", "stop"], events);
302+
}
303+
304+
[Fact]
305+
public async Task Refresh_QuiesceExceptionStopsManagedProcessBeforePropagating()
306+
{
307+
using var temp = new TempDirectory("local-ai-port-");
308+
LocalAiPaths paths = await PrepareInstallAsync(temp);
309+
var events = new List<string>();
310+
var platform = new FakePlatform();
311+
var host = new FakeProcessHost(platform, events, selectedPort: 28_779);
312+
var lifecycle = new FakeLifecycle(events);
313+
await using var runtime = CreateRuntime(
314+
paths,
315+
host,
316+
platform,
317+
new FakeClient(events),
318+
lifecycle);
319+
LocalAiRuntimeSnapshot started = await runtime.EnsureStartedAsync();
320+
Assert.Equal(LocalAiRuntimeState.Healthy, started.State);
321+
events.Clear();
322+
platform.Listeners.Clear();
323+
lifecycle.QuiesceException = new IOException("route withdrawal failed");
324+
325+
IOException error = await Assert.ThrowsAsync<IOException>(() => runtime.RefreshAsync());
326+
327+
Assert.Equal("route withdrawal failed", error.Message);
328+
Assert.Equal(LocalAiRuntimeState.Failed, runtime.Snapshot.State);
329+
Assert.Equal(LocalAiOwnership.None, runtime.Snapshot.Ownership);
330+
Assert.Null(runtime.Snapshot.ProcessId);
331+
Assert.True(host.Process!.HasExited);
332+
Assert.Equal(["quiesce", "stop"], events);
333+
}
334+
335+
[Fact]
336+
public async Task Refresh_RecoveryRebindsFreshlyVerifiedEndpointBeforePublishing()
337+
{
338+
using var temp = new TempDirectory("local-ai-port-");
339+
LocalAiPaths paths = await PrepareInstallAsync(temp);
340+
var events = new List<string>();
341+
var platform = new FakePlatform();
342+
var host = new FakeProcessHost(platform, events, selectedPort: 28_777);
343+
var client = new FakeClient(events, (expectedModelPath, probeNumber) => probeNumber == 2
344+
? new(
345+
false,
346+
LocalAiModelAvailabilityState.Unknown,
347+
null,
348+
"The managed model is not ready.")
349+
: ReadyProbe(expectedModelPath));
350+
var lifecycle = new FakeLifecycle(events);
351+
await using var runtime = CreateRuntime(paths, host, platform, client, lifecycle);
352+
LocalAiRuntimeSnapshot started = await runtime.EnsureStartedAsync();
353+
Assert.Equal(LocalAiRuntimeState.Healthy, started.State);
354+
LocalAiRuntimeSnapshot unavailable = await runtime.RefreshAsync();
355+
Assert.Equal(LocalAiRuntimeState.Starting, unavailable.State);
356+
357+
var store = new LocalAiManifestStore(paths);
358+
LocalAiResolvedInstall install = (await store.LoadAsync())!;
359+
await store.SaveAsync(install.Manifest with { Endpoint = "http://127.0.0.1:29999/v1" });
360+
events.Clear();
361+
362+
LocalAiRuntimeSnapshot recovered = await runtime.RefreshAsync();
363+
364+
Assert.Equal(LocalAiRuntimeState.Healthy, recovered.State);
365+
Assert.Equal(28_777, recovered.Endpoint.Port);
366+
Assert.Equal(["probe:28777", "publish:28777"], events);
367+
LocalAiResolvedInstall rebound = (await store.LoadAsync())!;
368+
Assert.Equal(28_777, rebound.Endpoint!.Port);
369+
}
370+
371+
[Fact]
372+
public async Task Refresh_RecoveryPublishFailureRemainsFailedAndQuiesced()
373+
{
374+
using var temp = new TempDirectory("local-ai-port-");
375+
LocalAiPaths paths = await PrepareInstallAsync(temp);
376+
var events = new List<string>();
377+
var platform = new FakePlatform();
378+
var host = new FakeProcessHost(platform, events, selectedPort: 28_778);
379+
var client = new FakeClient(events, (expectedModelPath, probeNumber) => probeNumber == 2
380+
? new(
381+
false,
382+
LocalAiModelAvailabilityState.Unknown,
383+
null,
384+
"The managed model is not ready.")
385+
: ReadyProbe(expectedModelPath));
386+
var lifecycle = new FakeLifecycle(events);
387+
await using var runtime = CreateRuntime(paths, host, platform, client, lifecycle);
388+
LocalAiRuntimeSnapshot started = await runtime.EnsureStartedAsync();
389+
Assert.Equal(LocalAiRuntimeState.Healthy, started.State);
390+
LocalAiRuntimeSnapshot unavailable = await runtime.RefreshAsync();
391+
Assert.Equal(LocalAiRuntimeState.Starting, unavailable.State);
392+
events.Clear();
393+
lifecycle.FailPublish = true;
394+
395+
LocalAiRuntimeSnapshot failed = await runtime.RefreshAsync();
396+
397+
Assert.Equal(LocalAiRuntimeState.Failed, failed.State);
398+
Assert.Equal(LocalAiOwnership.CompanionManaged, failed.Ownership);
399+
Assert.False(host.Process!.HasExited);
400+
Assert.Equal(["probe:28778", "publish:28778"], events);
401+
}
402+
228403
[Fact]
229404
public async Task AutomaticPort_NeverProbesListenerWithoutMatchingProcessStartTime()
230405
{
@@ -442,6 +617,12 @@ private static string ArgumentAfter(IReadOnlyList<string> arguments, string name
442617
return arguments[index + 1];
443618
}
444619

620+
private static LlamaServerRouterProbeResult ReadyProbe(string expectedModelPath) => new(
621+
true,
622+
LocalAiModelAvailabilityState.Verified,
623+
expectedModelPath,
624+
"The managed model is ready.");
625+
445626
private static LocalAiInstallManifest ValidManifest()
446627
{
447628
LlamaRuntimeVariant runtime = LlamaRuntimeCatalog.Find(
@@ -485,9 +666,10 @@ private sealed class FakePlatform : ILlamaServerRuntimePlatform
485666
{
486667
public DateTimeOffset UtcNow { get; private set; } = DateTimeOffset.Parse("2026-08-18T12:00:00Z");
487668
public List<WindowsTcpListenerInfo> Listeners { get; } = [];
669+
public bool Ipv4Complete { get; set; } = true;
488670

489671
public WindowsTcpListenerSnapshotResult CaptureListeners() =>
490-
new([.. Listeners], Ipv4Complete: true, Ipv6Complete: true);
672+
new([.. Listeners], Ipv4Complete, Ipv6Complete: true);
491673

492674
public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken)
493675
{
@@ -581,14 +763,20 @@ public void Dispose() { }
581763

582764
private sealed class FakeLifecycle(List<string> events) : ILocalAiEndpointLifecycle
583765
{
584-
public bool FailPublish { get; init; }
766+
public bool FailPublish { get; set; }
767+
public bool FailQuiesce { get; set; }
768+
public Exception? QuiesceException { get; set; }
585769

586770
public Task<LocalAiEndpointLifecycleResult> QuiesceAsync(
587771
LocalAiResolvedInstall install,
588772
CancellationToken cancellationToken = default)
589773
{
590774
events.Add("quiesce");
591-
return Task.FromResult(LocalAiEndpointLifecycleResult.Ok());
775+
if (QuiesceException is not null)
776+
return Task.FromException<LocalAiEndpointLifecycleResult>(QuiesceException);
777+
return Task.FromResult(FailQuiesce
778+
? LocalAiEndpointLifecycleResult.Failed("quiesce failed")
779+
: LocalAiEndpointLifecycleResult.Ok());
592780
}
593781

594782
public Task<LocalAiEndpointLifecycleResult> PublishAsync(
@@ -601,4 +789,11 @@ public Task<LocalAiEndpointLifecycleResult> PublishAsync(
601789
: LocalAiEndpointLifecycleResult.Ok());
602790
}
603791
}
792+
793+
public enum RefreshOwnershipLoss
794+
{
795+
Incomplete,
796+
Conflict,
797+
MissingEndpoint,
798+
}
604799
}

0 commit comments

Comments
 (0)