Skip to content

Commit fff65f0

Browse files
karkarlCopilot
andcommitted
Require verified local AI model evidence
Co-authored-by: Copilot App <[email protected]>
1 parent ccd64bb commit fff65f0

4 files changed

Lines changed: 199 additions & 8 deletions

File tree

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

Lines changed: 13 additions & 5 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+
public bool HasVerifiedManagedModel =>
12+
ModelState is LocalAiModelAvailabilityState.Verified or LocalAiModelAvailabilityState.Loaded &&
13+
!string.IsNullOrWhiteSpace(ReportedModelPath);
14+
15+
public bool IsReady => IsHealthy && HasVerifiedManagedModel;
16+
}
1017

1118
public sealed record LlamaServerModelStatusEvidence(
1219
LocalAiModelAvailabilityState State,
@@ -191,11 +198,11 @@ public async Task<LlamaServerRouterProbeResult> ProbeRouterAsync(
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

@@ -249,9 +256,10 @@ private async Task<LlamaServerRouterProbeResult> ProbeModelAsync(
249256
modelAlias,
250257
expectedModelPath);
251258
if (evidence is null)
252-
return new(true, LocalAiModelAvailabilityState.NotInstalled, null, "The configured model is not registered.");
259+
return new(false, LocalAiModelAvailabilityState.NotInstalled, null, "The configured model is not registered.");
260+
bool hasVerifiedManagedModel = evidence.State is LocalAiModelAvailabilityState.Verified or LocalAiModelAvailabilityState.Loaded;
253261
return new(
254-
true,
262+
hasVerifiedManagedModel,
255263
evidence.State,
256264
evidence.ModelPath,
257265
$"llama-server reports the model as {evidence.ServerStatus}.");

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

Lines changed: 2 additions & 2 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.IsReady)
250250
{
251251
LocalAiInstallManifest verifiedManifest = install.Manifest with
252252
{
@@ -346,7 +346,7 @@ private async Task<LocalAiRuntimeSnapshot> RefreshCoreAsync(CancellationToken ca
346346
install.ModelPath,
347347
cancellationToken)
348348
.ConfigureAwait(false);
349-
return probe.IsHealthy
349+
return probe.IsReady
350350
? PublishHealthy(probe)
351351
: Publish(
352352
LocalAiRuntimeState.Starting,
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
using OpenClaw.Connection.LocalAi;
2+
using System.Net;
3+
using System.Text;
4+
5+
namespace OpenClaw.Connection.Tests;
6+
7+
public sealed class LlamaServerClientTests
8+
{
9+
private const string Alias = "qwen3.6-35b-a3b-mtp-q4-k-m";
10+
private static readonly Uri Endpoint = new("http://127.0.0.1:28765/v1");
11+
12+
[Fact]
13+
public async Task ProbeRouterAsync_ModelStatusTimeout_ReturnsNotHealthy()
14+
{
15+
using var client = new LlamaServerClient(new StubHandler(request =>
16+
request.RequestUri!.AbsolutePath == "/models"
17+
? throw new OperationCanceledException()
18+
: JsonResponse("""{"status":"ok"}""")));
19+
20+
LlamaServerRouterProbeResult result = await client.ProbeRouterAsync(
21+
Endpoint,
22+
Alias,
23+
ManagedModelPath());
24+
25+
Assert.False(result.IsHealthy);
26+
Assert.False(result.IsReady);
27+
Assert.Equal(LocalAiModelAvailabilityState.Unknown, result.ModelState);
28+
}
29+
30+
[Fact]
31+
public async Task ProbeRouterAsync_MissingConfiguredAlias_ReturnsNotHealthy()
32+
{
33+
using var client = new LlamaServerClient(new StubHandler(request =>
34+
request.RequestUri!.AbsolutePath == "/models"
35+
? JsonResponse(ModelListJson("other-model", "unloaded", ManagedModelPath()))
36+
: JsonResponse("""{"status":"ok"}""")));
37+
38+
LlamaServerRouterProbeResult result = await client.ProbeRouterAsync(
39+
Endpoint,
40+
Alias,
41+
ManagedModelPath());
42+
43+
Assert.False(result.IsHealthy);
44+
Assert.False(result.IsReady);
45+
Assert.Equal(LocalAiModelAvailabilityState.NotInstalled, result.ModelState);
46+
}
47+
48+
[Fact]
49+
public async Task ProbeRouterAsync_InvalidModelsResponse_ReturnsNotHealthy()
50+
{
51+
using var client = new LlamaServerClient(new StubHandler(request =>
52+
request.RequestUri!.AbsolutePath == "/models"
53+
? JsonResponse("""{"data":{}}""")
54+
: JsonResponse("""{"status":"ok"}""")));
55+
56+
LlamaServerRouterProbeResult result = await client.ProbeRouterAsync(
57+
Endpoint,
58+
Alias,
59+
ManagedModelPath());
60+
61+
Assert.False(result.IsHealthy);
62+
Assert.False(result.IsReady);
63+
Assert.Equal(LocalAiModelAvailabilityState.Unknown, result.ModelState);
64+
}
65+
66+
[Fact]
67+
public async Task ProbeRouterAsync_UnknownModelState_ReturnsNotHealthy()
68+
{
69+
using var client = new LlamaServerClient(new StubHandler(request =>
70+
request.RequestUri!.AbsolutePath == "/models"
71+
? JsonResponse(ModelListJson(Alias, "error", ManagedModelPath()))
72+
: JsonResponse("""{"status":"ok"}""")));
73+
74+
LlamaServerRouterProbeResult result = await client.ProbeRouterAsync(
75+
Endpoint,
76+
Alias,
77+
ManagedModelPath());
78+
79+
Assert.False(result.IsHealthy);
80+
Assert.False(result.IsReady);
81+
Assert.Equal(LocalAiModelAvailabilityState.Unknown, result.ModelState);
82+
Assert.Equal(ManagedModelPath(), result.ReportedModelPath);
83+
}
84+
85+
[Fact]
86+
public async Task ProbeRouterAsync_WrongModelPath_ReturnsNotHealthy()
87+
{
88+
using var client = new LlamaServerClient(new StubHandler(request =>
89+
request.RequestUri!.AbsolutePath == "/models"
90+
? JsonResponse(ModelListJson(Alias, "unloaded", ManagedModelPath("wrong.gguf")))
91+
: JsonResponse("""{"status":"ok"}""")));
92+
93+
LlamaServerRouterProbeResult result = await client.ProbeRouterAsync(
94+
Endpoint,
95+
Alias,
96+
ManagedModelPath());
97+
98+
Assert.False(result.IsHealthy);
99+
Assert.False(result.IsReady);
100+
Assert.Equal(LocalAiModelAvailabilityState.Unknown, result.ModelState);
101+
}
102+
103+
[Theory]
104+
[InlineData("unloaded", LocalAiModelAvailabilityState.Verified)]
105+
[InlineData("loaded", LocalAiModelAvailabilityState.Loaded)]
106+
public async Task ProbeRouterAsync_VerifiedManagedModel_ReturnsHealthy(string serverStatus, LocalAiModelAvailabilityState expectedState)
107+
{
108+
using var client = new LlamaServerClient(new StubHandler(request =>
109+
request.RequestUri!.AbsolutePath == "/models"
110+
? JsonResponse(ModelListJson(Alias, serverStatus, ManagedModelPath()))
111+
: JsonResponse("""{"status":"ok"}""")));
112+
113+
LlamaServerRouterProbeResult result = await client.ProbeRouterAsync(
114+
Endpoint,
115+
Alias,
116+
ManagedModelPath());
117+
118+
Assert.True(result.IsHealthy);
119+
Assert.True(result.IsReady);
120+
Assert.Equal(expectedState, result.ModelState);
121+
Assert.Equal(ManagedModelPath(), result.ReportedModelPath);
122+
}
123+
124+
private static string ModelListJson(string alias, string status, string modelPath) =>
125+
$$"""
126+
{
127+
"data": [
128+
{
129+
"id": "{{alias}}",
130+
"status": {
131+
"value": "{{status}}",
132+
"args": ["--model", "{{JsonEscape(modelPath)}}"]
133+
}
134+
}
135+
]
136+
}
137+
""";
138+
139+
private static HttpResponseMessage JsonResponse(string json) =>
140+
new(HttpStatusCode.OK)
141+
{
142+
Content = new StringContent(json, Encoding.UTF8, "application/json"),
143+
};
144+
145+
private static string ManagedModelPath(string fileName = "Qwen3.6-35B-A3B-UD-Q4_K_M.gguf") =>
146+
Path.Combine("C:\\", "OpenClaw", "models", fileName);
147+
148+
private static string JsonEscape(string value) =>
149+
value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal);
150+
151+
private sealed class StubHandler(Func<HttpRequestMessage, HttpResponseMessage> respond) : HttpMessageHandler
152+
{
153+
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
154+
Task.FromResult(respond(request));
155+
}
156+
}

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

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,32 @@ public async Task PublishFailure_StopsChildAndLeavesEndpointConsumerQuiesced()
287287
Assert.Equal(28_768, recovered.Endpoint.Port);
288288
}
289289

290+
[Fact]
291+
public async Task Startup_DoesNotPublishWhenModelEvidenceIsNotVerified()
292+
{
293+
using var temp = new TempDirectory("local-ai-port-");
294+
LocalAiPaths paths = await PrepareInstallAsync(temp);
295+
var events = new List<string>();
296+
var platform = new FakePlatform();
297+
var host = new FakeProcessHost(platform, events, selectedPort: 28_773);
298+
var client = new FakeClient(events)
299+
{
300+
Result = new LlamaServerRouterProbeResult(
301+
true,
302+
LocalAiModelAvailabilityState.NotInstalled,
303+
null,
304+
"The configured model is not registered."),
305+
};
306+
await using var runtime = CreateRuntime(paths, host, platform, client, new FakeLifecycle(events));
307+
308+
LocalAiRuntimeSnapshot snapshot = await runtime.EnsureStartedAsync();
309+
310+
Assert.Equal(LocalAiRuntimeState.Failed, snapshot.State);
311+
Assert.DoesNotContain("publish:28773", events);
312+
LocalAiResolvedInstall? saved = await new LocalAiManifestStore(paths).LoadAsync();
313+
Assert.Null(saved!.Endpoint);
314+
}
315+
290316
private static LlamaServerRuntimeService CreateRuntime(
291317
LocalAiPaths paths,
292318
FakeProcessHost host,
@@ -442,6 +468,7 @@ public Task StopAsync(TimeSpan timeout, CancellationToken cancellationToken)
442468
private sealed class FakeClient(List<string> events) : ILlamaServerClient
443469
{
444470
public List<int> ProbedPorts { get; } = [];
471+
public LlamaServerRouterProbeResult? Result { get; init; }
445472

446473
public Task<LlamaServerRouterProbeResult> ProbeRouterAsync(
447474
Uri endpoint,
@@ -452,7 +479,7 @@ public Task<LlamaServerRouterProbeResult> ProbeRouterAsync(
452479
cancellationToken.ThrowIfCancellationRequested();
453480
ProbedPorts.Add(endpoint.Port);
454481
events.Add($"probe:{endpoint.Port}");
455-
return Task.FromResult(new LlamaServerRouterProbeResult(
482+
return Task.FromResult(Result ?? new LlamaServerRouterProbeResult(
456483
true,
457484
LocalAiModelAvailabilityState.Verified,
458485
expectedModelPath,

0 commit comments

Comments
 (0)