Files
mesh-lab/test/integration/local-model-bed.test.ts

198 lines
9.1 KiB
TypeScript

/**
* The mesh proves model-access answered by a NODE, end to end (novox/hq ADR 0055). Where the Anthropic
* and OpenAI beds answer model-access with a licence (a vendor), this answers it with the mesh's OWN
* model: an Ollama server on the node `provides: ["model-access"]` at node scope and serves its
* endpoint, and a consumer requiring model-access is handed that endpoint — base URL + model — with no
* licence and no key.
*
* the ollama provider is assigned (provides model-access at node scope, serves { port, model }) ->
* the local-model consumer requires model-access and is answered by the local node (the resolver
* prefers a local model over a licence) -> the mesh fills the consumer's bound facts with ollama's
* at/port/model -> the consumer's templated openai.env carries OPENAI_BASE_URL=http://<at>:<port>/v1.
*
* The property proven: the consumer is delivered a reachable local endpoint through the same
* model-access provision it would use for a vendor — no adapter, no credential, no licence. The bed
* asserts the templated URL and that a request to it reaches the running server (ollama answers
* /v1/models even with no model pulled — the wiring is what is proven, not a model's output).
*
* MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock
* No module runtime image is built — both modules are pure declaration.
*/
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { existsSync, readFileSync } from "node:fs";
import { loadScenario } from "../../src/declaration/parse.ts";
import { raise } from "../../src/lifecycle/raise.ts";
import { destroy, exec } from "../../src/lifecycle/operate.ts";
import { hostBinaryPath, HOST_PATH } from "../../src/lifecycle/place.ts";
import { labIsUsable, destroyAll, foundationBundle, onTheMachine, catalogueModule, catalogueIsPresent } from "./harness.ts";
import type { HeldImage } from "../../src/pinning.ts";
const capability = await labIsUsable();
const binary = hostBinaryPath();
const bundle = process.env["MESH_LAB_BUNDLE"] ?? "";
const skip = !capability.usable
? `lab not usable: ${capability.why}`
: !binary || !existsSync(binary)
? "MESH_LAB_HOST_BINARY is not set to a built mesh-host"
: !bundle || !existsSync(bundle)
? "MESH_LAB_BUNDLE is not set to a foundation bundle (mesh-host examples/)"
: catalogueIsPresent();
const SCENARIO = "local-model-bed";
const MACHINE = "anchor";
let instanceId = "";
let held: HeldImage[] = [];
function quote(s: string): string {
return `'${s.replaceAll("'", `'\\''`)}'`;
}
async function on(command: string, timeoutMs?: number): Promise<{ out: string; ok: boolean }> {
const { stdout } = await exec(instanceId, MACHINE, [
"sh", "-c", `exec 2>&1\n${command}\necho "__exit=$?"`,
], timeoutMs);
const marker = stdout.lastIndexOf("__exit=");
if (marker < 0) return { out: stdout, ok: false };
return { out: stdout.slice(0, marker), ok: stdout.slice(marker + 7).trim() === "0" };
}
async function must(command: string, timeoutMs?: number): Promise<string> {
const { out, ok } = await on(command, timeoutMs);
if (!ok) throw new Error(`${MACHINE}: ${command}\n${out}`);
return out;
}
async function mesh(command: string, timeoutMs?: number): Promise<string> {
return must(`docker exec mesh-controller /mesh-controller ${command}`, timeoutMs);
}
async function meshTry(command: string): Promise<{ out: string; ok: boolean }> {
return on(`docker exec mesh-controller /mesh-controller ${command}`);
}
/** What a manifest's image reference becomes on the machine — ours by ID, everything else as written. */
function pinned(reference: string): string {
return onTheMachine(reference, held);
}
function bundleFor(images: HeldImage[]): string {
return foundationBundle(bundle, images);
}
function tokenFrom(said: string): string {
const found = said.split("\n").map((l) => l.trim()).find((l) => l.length > 100 && !l.includes(" "));
assert.ok(found, `no token in:\n${said}`);
return found;
}
async function settled(withinMs = 600_000): Promise<void> {
const until = Date.now() + withinMs;
let last = "";
while (Date.now() < until) {
const asked = await meshTry(`status --json`);
if (asked.ok) {
try {
const state = JSON.parse(asked.out) as {
wrong: { node: string; outcome: string }[];
waiting: { node: string }[];
reported: { node: string; outcome: string; current: boolean }[];
};
const bad = state.wrong.find((w) => w.node === MACHINE);
if (bad) throw new Error(`${MACHINE} did not apply what it was sent: ${bad.outcome}\n${asked.out}`);
const word = state.reported.find((r) => r.node === MACHINE);
if (!state.waiting.some((w) => w.node === MACHINE) && word?.outcome === "applied" && word.current) return;
last = asked.out;
} catch (err) {
if (err instanceof Error && err.message.includes("did not apply")) throw err;
last = asked.out;
}
}
await new Promise((r) => setTimeout(r, 5000));
}
throw new Error(`${MACHINE} never caught up within ${Math.round(withinMs / 1000)}s. Last:\n${last}`);
}
async function addAssign(name: string, manifest: string): Promise<void> {
await must(`printf %s ${quote(manifest)} > /tmp/${name}.json && docker cp /tmp/${name}.json mesh-controller:/${name}.json`);
await mesh(`module add /${name}.json`);
// No `module issue`: neither module speaks on the bus, and issuing a module with no broker
// secret to deliver into is refused (novox/hq issue 078).
await mesh(`assign ${MACHINE} ${name}`);
}
before(async () => {
if (skip) return;
const raised = await raise(loadScenario(`scenarios/${SCENARIO}.yml`), {
onProgress: (m) => console.log(`raise: ${m}`),
});
instanceId = raised.instanceId;
held = raised.images;
await must(`cat > /tmp/foundation.lock <<'MESHBUNDLE'\n${bundleFor(raised.images)}\nMESHBUNDLE`);
await must(`${HOST_PATH} apply /tmp/foundation.lock`, 600_000);
const up = await must(`docker ps --format '{{.Names}}'`);
for (const c of ["mesh-store", "mesh-broker", "mesh-controller"]) {
assert.match(up, new RegExp(c), `the foundation did not raise ${c}:\n${up}`);
}
await mesh(`node add ${MACHINE}`);
const token = tokenFrom(await mesh(`token issue --node ${MACHINE}`));
await must(`${HOST_PATH} enrol --token ${quote(token)}`);
await must(`nohup ${HOST_PATH} run > /var/log/mesh-host.log 2>&1 & sleep 3`);
}, { timeout: 1_800_000 });
after(async () => {
if (instanceId) await destroy(instanceId);
await destroyAll(`${SCENARIO}-`);
}, { timeout: 600_000 });
test("a node hosting a model answers model-access, and the consumer is handed its endpoint", {
skip, timeout: 1_500_000,
}, async () => {
// Both manifests are the catalogue's own (novox/hq 04-ISSUES/073). The provider: ollama runs the
// model server and `provides: ["model-access"]` at node scope, serving its port and model. It mints
// nothing — provides/serves are declaration the mesh reads, so there is no runtime container, only
// the server. The consumer requires model-access and is answered by the local node: no secret (the
// local server is keyless), only the bound endpoint facts, templated into an openai.env the mesh writes.
const ollamaManifest = catalogueModule("ollama", held);
const consumerManifest = catalogueModule("local-model-consumer", held);
await addAssign("ollama", ollamaManifest);
await addAssign("local-model-consumer", consumerManifest);
await mesh(`push ${MACHINE}`);
await settled();
// The ollama server is running, and the consumer's endpoint file was written from its served facts.
const up = await must(`docker ps --format '{{.Names}}'`);
assert.match(up, /(^|\n)ollama(\n|$)/, `the ollama server is not running:\n${up}`);
// Wait for the templated endpoint file, then read the base URL the mesh filled in.
let env = "";
for (let i = 0; i < 20; i++) {
const got = await on(`cat /var/lib/local-model-consumer/config/openai.env`);
if (got.ok && got.out.includes("OPENAI_BASE_URL=http")) { env = got.out; break; }
await new Promise((r) => setTimeout(r, 3000));
}
assert.match(env, /OPENAI_BASE_URL=http:\/\/[^\s:]+:\d+\/v1/, `the base URL was not templated from the served endpoint:\n${env}`);
assert.match(env, /OPENAI_MODEL=llama3\.2/, `the served model fact did not reach the consumer:\n${env}`);
const baseUrl = (env.match(/OPENAI_BASE_URL=(\S+)/) ?? [])[1] ?? "";
assert.ok(baseUrl, `no OPENAI_BASE_URL in:\n${env}`);
// The endpoint the consumer was handed is reachable — a request to the local model server's
// OpenAI-compatible API succeeds (ollama answers /v1/models even with no model pulled). This is the
// wiring proven: the mesh routed the consumer to the model the mesh runs itself.
let reached = "";
for (let i = 0; i < 20; i++) {
const got = await on(`curl -sS -m 5 ${quote(`${baseUrl}/models`)}`);
if (got.ok && (got.out.includes("\"data\"") || got.out.includes("\"object\""))) { reached = got.out; break; }
await new Promise((r) => setTimeout(r, 3000));
}
assert.ok(reached, `the consumer's endpoint ${baseUrl}/models was never reachable`);
});