Skip to content

Commit 1955282

Browse files
joelagnelkarkarl
andauthored
fix(local-ai): prevent routing to an unverified managed model (#1212)
* fix(local-ai): require managed model readiness * fix(local-ai): fail closed when route proof is lost Co-authored-by: Copilot App <[email protected]> Copilot-Session: 7ef70da5-e94c-4bcf-9cb6-a0acee52c9c4 --------- Co-authored-by: Karen Lai <[email protected]> Copilot-Session: 7ef70da5-e94c-4bcf-9cb6-a0acee52c9c4
1 parent f2a96a5 commit 1955282

4 files changed

Lines changed: 526 additions & 25 deletions

File tree

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

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ public sealed record LlamaServerRouterProbeResult(
66
bool IsHealthy,
77
LocalAiModelAvailabilityState ModelState,
88
string? ReportedModelPath,
9-
string? Detail);
9+
string? Detail)
10+
{
11+
internal bool IsReadyForManagedModel(string expectedModelPath) =>
12+
IsHealthy &&
13+
ModelState is LocalAiModelAvailabilityState.Verified or LocalAiModelAvailabilityState.Loaded &&
14+
!string.IsNullOrWhiteSpace(ReportedModelPath) &&
15+
LlamaServerModelStatusParser.PathsEqual(ReportedModelPath, expectedModelPath);
16+
}
1017

1118
public sealed record LlamaServerModelStatusEvidence(
1219
LocalAiModelAvailabilityState State,
@@ -119,7 +126,7 @@ public static class LlamaServerModelStatusParser
119126
return modelPath;
120127
}
121128

122-
private static bool PathsEqual(string left, string right)
129+
internal static bool PathsEqual(string left, string right)
123130
{
124131
try
125132
{
@@ -191,11 +198,11 @@ public async Task<LlamaServerRouterProbeResult> ProbeManagedModelAsync(
191198
}
192199
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
193200
{
194-
return new(true, LocalAiModelAvailabilityState.Unknown, null, "The model status check timed out.");
201+
return new(false, LocalAiModelAvailabilityState.Unknown, null, "The model status check timed out.");
195202
}
196203
catch (Exception ex) when (ex is HttpRequestException or IOException or JsonException or InvalidDataException)
197204
{
198-
return new(true, LocalAiModelAvailabilityState.Unknown, null, "The model status response was invalid.");
205+
return new(false, LocalAiModelAvailabilityState.Unknown, null, "The model status response was invalid.");
199206
}
200207
}
201208

@@ -257,9 +264,9 @@ private async Task<LlamaServerRouterProbeResult> ProbeModelAsync(
257264
modelAlias,
258265
expectedModelPath);
259266
if (evidence is null)
260-
return new(true, LocalAiModelAvailabilityState.NotInstalled, null, "The configured model is not registered.");
267+
return new(false, LocalAiModelAvailabilityState.NotInstalled, null, "The configured model is not registered.");
261268
return new(
262-
true,
269+
evidence.State is LocalAiModelAvailabilityState.Verified or LocalAiModelAvailabilityState.Loaded,
263270
evidence.State,
264271
evidence.ModelPath,
265272
$"llama-server reports the model as {evidence.ServerStatus}.");

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

Lines changed: 134 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ private async Task<LocalAiRuntimeSnapshot> EnsureStartedCoreAsync(CancellationTo
246246
install.ModelPath,
247247
cancellationToken)
248248
.ConfigureAwait(false);
249-
if (probe.IsHealthy)
249+
if (probe.IsReadyForManagedModel(install.ModelPath))
250250
{
251251
LocalAiInstallManifest verifiedManifest = install.Manifest with
252252
{
@@ -334,26 +334,148 @@ 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,
345374
install.Manifest.ModelAlias,
346375
install.ModelPath,
347376
cancellationToken)
348377
.ConfigureAwait(false);
349-
return probe.IsHealthy
350-
? PublishHealthy(probe)
351-
: Publish(
352-
LocalAiRuntimeState.Starting,
353-
LocalAiOwnership.CompanionManaged,
354-
"The local AI router is not healthy yet.",
355-
_managedProcess.ProcessId,
356-
_managedProcess.StartedAtUtc);
378+
if (probe.IsReadyForManagedModel(install.ModelPath))
379+
{
380+
bool endpointChanged = install.Endpoint != ownership.Endpoint;
381+
if (_snapshot.State != LocalAiRuntimeState.Healthy || endpointChanged)
382+
{
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);
398+
LocalAiEndpointLifecycleResult published = await _options.EndpointLifecycle
399+
.PublishAsync(install, cancellationToken)
400+
.ConfigureAwait(false);
401+
if (!published.Success)
402+
{
403+
return Publish(
404+
LocalAiRuntimeState.Failed,
405+
LocalAiOwnership.CompanionManaged,
406+
published.Detail ?? "The verified Local AI endpoint could not be republished.",
407+
_managedProcess.ProcessId,
408+
_managedProcess.StartedAtUtc);
409+
}
410+
}
411+
412+
return PublishHealthy(probe);
413+
}
414+
415+
LocalAiRuntimeSnapshot? quiesceFailure = await QuiesceOrStopAsync(
416+
install,
417+
cancellationToken)
418+
.ConfigureAwait(false);
419+
if (quiesceFailure is not null)
420+
return quiesceFailure;
421+
422+
return Publish(
423+
LocalAiRuntimeState.Starting,
424+
LocalAiOwnership.CompanionManaged,
425+
probe.Detail ?? "The local AI router has not verified the managed model yet.",
426+
_managedProcess.ProcessId,
427+
_managedProcess.StartedAtUtc);
428+
}
429+
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;
357479
}
358480

359481
private async Task<bool> TryLoadInstallAsync(CancellationToken cancellationToken)
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
using OpenClaw.Connection.LocalAi;
2+
using System.Net;
3+
using System.Text;
4+
using System.Text.Json;
5+
6+
namespace OpenClaw.Connection.Tests;
7+
8+
public sealed class LlamaServerClientTests
9+
{
10+
private const string ModelAlias = "managed-model";
11+
private static readonly Uri s_endpoint = new("http://127.0.0.1:18803/v1");
12+
private static readonly string s_modelPath = Path.GetFullPath("managed-model.gguf");
13+
14+
[Theory]
15+
[InlineData(ProbeCase.Timeout, LocalAiModelAvailabilityState.Unknown, false)]
16+
[InlineData(ProbeCase.InvalidResponse, LocalAiModelAvailabilityState.Unknown, false)]
17+
[InlineData(ProbeCase.MissingAlias, LocalAiModelAvailabilityState.NotInstalled, false)]
18+
[InlineData(ProbeCase.UnknownState, LocalAiModelAvailabilityState.Unknown, false)]
19+
[InlineData(ProbeCase.MissingPath, LocalAiModelAvailabilityState.Unknown, false)]
20+
[InlineData(ProbeCase.WrongPath, LocalAiModelAvailabilityState.Unknown, false)]
21+
[InlineData(ProbeCase.Verified, LocalAiModelAvailabilityState.Verified, true)]
22+
[InlineData(ProbeCase.Loaded, LocalAiModelAvailabilityState.Loaded, true)]
23+
public async Task ProbeManagedModelAsync_RequiresReadyModelEvidence(
24+
ProbeCase probeCase,
25+
LocalAiModelAvailabilityState expectedState,
26+
bool expectedReady)
27+
{
28+
using var client = new LlamaServerClient(new DelegateHandler((request, _) =>
29+
request.RequestUri?.AbsolutePath == "/health"
30+
? Task.FromResult(JsonResponse("{\"status\":\"ok\"}"))
31+
: ModelResponseAsync(probeCase)));
32+
33+
LlamaServerRouterProbeResult result = await client.ProbeManagedModelAsync(
34+
s_endpoint,
35+
ModelAlias,
36+
s_modelPath);
37+
38+
Assert.Equal(expectedReady, result.IsHealthy);
39+
Assert.Equal(expectedState, result.ModelState);
40+
Assert.Equal(expectedReady, result.IsReadyForManagedModel(s_modelPath));
41+
}
42+
43+
private static Task<HttpResponseMessage> ModelResponseAsync(ProbeCase probeCase) => probeCase switch
44+
{
45+
ProbeCase.Timeout => Task.FromException<HttpResponseMessage>(new OperationCanceledException()),
46+
ProbeCase.InvalidResponse => Task.FromResult(JsonResponse("{")),
47+
ProbeCase.MissingAlias => Task.FromResult(JsonResponse(ModelStatus("other-model", "unloaded", s_modelPath))),
48+
ProbeCase.UnknownState => Task.FromResult(JsonResponse(ModelStatus(ModelAlias, "unexpected", s_modelPath))),
49+
ProbeCase.MissingPath => Task.FromResult(JsonResponse(ModelStatus(ModelAlias, "unloaded", null))),
50+
ProbeCase.WrongPath => Task.FromResult(JsonResponse(ModelStatus(ModelAlias, "loaded", s_modelPath + ".other"))),
51+
ProbeCase.Verified => Task.FromResult(JsonResponse(ModelStatus(ModelAlias, "unloaded", s_modelPath))),
52+
ProbeCase.Loaded => Task.FromResult(JsonResponse(ModelStatus(ModelAlias, "loaded", s_modelPath))),
53+
_ => throw new InvalidOperationException("Unknown probe test case."),
54+
};
55+
56+
private static string ModelStatus(string alias, string status, string? path) => JsonSerializer.Serialize(new
57+
{
58+
data = new[]
59+
{
60+
new
61+
{
62+
id = alias,
63+
status = path is null
64+
? (object)new { value = status }
65+
: new { value = status, args = new[] { "--model", path } },
66+
},
67+
},
68+
});
69+
70+
private static HttpResponseMessage JsonResponse(string payload) => new(HttpStatusCode.OK)
71+
{
72+
Content = new StringContent(payload, Encoding.UTF8, "application/json"),
73+
};
74+
75+
public enum ProbeCase
76+
{
77+
Timeout,
78+
InvalidResponse,
79+
MissingAlias,
80+
UnknownState,
81+
MissingPath,
82+
WrongPath,
83+
Verified,
84+
Loaded,
85+
}
86+
87+
private sealed class DelegateHandler(
88+
Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler) : HttpMessageHandler
89+
{
90+
protected override Task<HttpResponseMessage> SendAsync(
91+
HttpRequestMessage request,
92+
CancellationToken cancellationToken) => handler(request, cancellationToken);
93+
}
94+
}

0 commit comments

Comments
 (0)