From cf26b19b965c0ff8f0592cdcff693ec9e83f69e2 Mon Sep 17 00:00:00 2001 From: jochen Date: Mon, 7 Sep 2026 05:25:21 +0200 Subject: [PATCH] local-model bed: prove model-access answered by a node (ADR 0055) A single-node VM bed: an ollama provider and a local-model consumer are assigned; the resolver answers the consumer's model-access with the local node (no licence demanded), the consumer's openai.env is templated with the served endpoint, and a request to it reaches the running model server. Proves the node-answer of model-access end to end (ollama on host network, keyless). Claude-Session: https://claude.ai/code/session_01LrgweAeERJYBg88c5cKDzF --- scenarios/local-model-bed.yml | 43 +++++ test/integration/local-model-bed.test.ts | 236 +++++++++++++++++++++++ 2 files changed, 279 insertions(+) create mode 100644 scenarios/local-model-bed.yml create mode 100644 test/integration/local-model-bed.test.ts diff --git a/scenarios/local-model-bed.yml b/scenarios/local-model-bed.yml new file mode 100644 index 0000000..f13a9c3 --- /dev/null +++ b/scenarios/local-model-bed.yml @@ -0,0 +1,43 @@ +# One machine that becomes a mesh, then proves model-access answered by a NODE (novox/hq ADR 0055): +# a local model server (Ollama) on the node ANSWERS the model-access provision, and a consumer that +# requires model-access is handed the server's ENDPOINT — base URL + model — instead of a vendor +# credential. No licence, no key: the consumer points an OpenAI-compatible client at the mesh's own +# model. +# +# The flow the test drives: +# the ollama provider is assigned (it `provides: [model-access]` at node scope, `serves` its port and +# model) -> the local-model consumer requires model-access and is answered by the local node -> +# 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://:/v1. The test asserts that URL and that a +# request to it reaches the running model server. +# +# MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/substrate-first-node.lock +# Both modules are pure declaration (a server container + a templated file) — no module runtime image +# is built; the bed only stocks the substrate and the ollama server image. +scenario: local-model-bed + +segments: + hosting: + kind: public + cidr: [192.0.2.0/24] + +machines: + anchor: + at: { segment: hosting, address: [192.0.2.10] } + inbound: allow + memory: 4GiB + cpus: 4 + disk: 40GiB + +images: + # The first-node substrate: store, broker, control. + - postgres:17-alpine + - cloudamqp/lavinmq:latest + - mesh-control:development + # The local model server the ollama provider runs. Pulled by raise() and stocked into the scenario's + # own registry, which is where the host pulls it from. No model is pulled into it — the bed proves the + # mesh routes a consumer to the server's endpoint, not that the server generates tokens. + - ollama/ollama:latest + +place: + all: [host, runtime] diff --git a/test/integration/local-model-bed.test.ts b/test/integration/local-model-bed.test.ts new file mode 100644 index 0000000..4dfc3e7 --- /dev/null +++ b/test/integration/local-model-bed.test.ts @@ -0,0 +1,236 @@ +/** + * 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://:/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/substrate-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 } from "./harness.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 substrate bundle (mesh-host examples/)" + : false; + +const SCENARIO = "local-model-bed"; +const MACHINE = "anchor"; + +let instanceId = ""; +let stocked: string[] = []; + +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 { + 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 { + return must(`docker exec mesh-control /mesh-control ${command}`, timeoutMs); +} + +async function meshTry(command: string): Promise<{ out: string; ok: boolean }> { + return on(`docker exec mesh-control /mesh-control ${command}`); +} + +function pinned(repository: string): string { + const found = stocked.find((r) => r.slice(r.indexOf("/") + 1, r.indexOf("@")) === repository); + assert.ok(found, `the scenario stocks no ${repository}; it serves ${stocked.join(", ")}`); + return found; +} + +function bundleFor(images: string[]): string { + let text = readFileSync(bundle, "utf8"); + for (const ref of images) { + const repository = ref.slice(ref.indexOf("/") + 1, ref.indexOf("@")); + const escaped = repository.replaceAll("/", "\\/").replaceAll(".", "\\."); + text = text.replaceAll(new RegExp(`[A-Za-z0-9_.:-]+\\/${escaped}@sha256:[0-9a-f]+`, "g"), ref); + } + return text; +} + +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 { + 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 { + await must(`printf %s ${quote(manifest)} > /tmp/${name}.json && docker cp /tmp/${name}.json mesh-control:/${name}.json`); + await mesh(`module add /${name}.json`); + await mesh(`module issue ${name} --node ${MACHINE}`); + 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; + stocked = raised.images; + + await must(`cat > /tmp/substrate.lock <<'MESHBUNDLE'\n${bundleFor(raised.images)}\nMESHBUNDLE`); + await must(`${HOST_PATH} apply /tmp/substrate.lock`, 600_000); + const up = await must(`docker ps --format '{{.Names}}'`); + for (const c of ["mesh-store", "mesh-broker", "mesh-control"]) { + assert.match(up, new RegExp(c), `the substrate 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 () => { + const ollamaImage = pinned("ollama/ollama"); + + // 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. + const ollamaManifest = JSON.stringify({ + module: "ollama", + version: "1", + capabilities: ["container-runtime"], + provides: [{ name: "model-access", scope: "node" }], + listens: [{ port: 11434, protocol: "tcp", from: "machine", why: "local consumers reaching the model server" }], + serves: { "model-access": { port: 11434, model: "llama3.2" } }, + resources: [ + { id: "state", type: "directory", path: "/services/ollama", mode: "0700" }, + { + id: "server", type: "container", name: "ollama", + image: ollamaImage, network: "host", env: { OLLAMA_HOST: "0.0.0.0:11434" }, + volumes: ["/services/ollama:/root/.ollama"], + }, + ], + }); + + // The consumer: it 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 consumerManifest = JSON.stringify({ + module: "local-model-consumer", + version: "1", + slug: "local", + requires: ["model-access"], + binds: { "model-access": "/var/lib/local-model-consumer/model.json" }, + resources: [ + { id: "state", type: "directory", path: "/var/lib/local-model-consumer", mode: "0700" }, + { id: "config", type: "directory", path: "/var/lib/local-model-consumer/config", mode: "0700" }, + { + id: "openai-env", type: "file", path: "/var/lib/local-model-consumer/config/openai.env", mode: "0600", + content: + "OPENAI_BASE_URL=http://${bound:model-access:at}:${bound:model-access:port}/v1\n" + + "OPENAI_MODEL=${bound:model-access:model}\nOPENAI_API_KEY=local\n", + }, + ], + }); + + 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`); +}); -- 2.54.0