From 76ecbaed85c88de542e07b739179360232d37c22 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 6 Sep 2026 14:20:54 +0200 Subject: [PATCH] lab: a scheduled container fires on its cadence without gating (ADR 0053) The bed that proves the scheduled-container primitive end to end. schedtest is the thinnest carrier of ADR 0053: one container marked schedule: "* * * * *" that appends a timestamp to a mounted data dir each time the host fires it -- no service, no listener, no provisioner, no runtime, no tools, no events. The three claims it proves, from the ADR's "How each claim is checked": installing the schedule leaves the node current WITHOUT a run (baseline captured right after settled, the deliberate inversion of run-once); the container fires on its cadence (a line beyond the baseline within ~150s); and it recurs (a second line on the next minute -- cadence, not a one-shot). schedtest serves and consumes nothing and carries no runtime, so it is not issued a broker account: module add -> assign -> one push is the whole sequence, no module issue. The tick image is a bare alpine served by the scenario's registry by digest. Claude-Session: https://claude.ai/code/session_01LrgweAeERJYBg88c5cKDzF --- scenarios/schedule-tick.yml | 49 ++++ .../assigned-schedule-tick.test.ts | 259 ++++++++++++++++++ 2 files changed, 308 insertions(+) create mode 100644 scenarios/schedule-tick.yml create mode 100644 test/integration/assigned-schedule-tick.test.ts diff --git a/scenarios/schedule-tick.yml b/scenarios/schedule-tick.yml new file mode 100644 index 0000000..e8edfeb --- /dev/null +++ b/scenarios/schedule-tick.yml @@ -0,0 +1,49 @@ +# One machine that becomes a mesh and is then assigned schedtest — the bed that proves the +# scheduled-container primitive (novox/hq ADR 0053) end to end. +# +# schedtest is the thinnest possible carrier of the ADR's claim: no service, no listener, no +# provisioner, no runtime, no tools, no events — just a `container` marked `schedule: "* * * * *"` +# that appends a timestamp line to a file in a mounted data directory each time the host fires it. +# It is the recurring twin of the run-once bed (catalogue-mqtt), with the gating rule deliberately +# reversed: installing the schedule must NOT run the container and must NOT gate convergence — the +# node reports current as soon as the schedule is state that is present, and the clock (not the +# apply) fires the runs thereafter. +# +# The sharp points this bed proves, straight from ADR 0053 "How each claim is checked": +# - installing it does not run it, and the node is current WITHOUT a run; +# - the container fires when the cron is due (top of the next minute); +# - it fires AGAIN on the following minute — recurrence, not a one-shot. +# +# MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_MODULES=.../mesh-control/examples/modules +# alpine:latest must be in the local daemon; the scenario stocks it into its own registry and +# serves it by digest, which is what the scheduled container declares (via pinned("alpine")). +# There is no runtime image: schedtest carries no code of its own — the scheduled container is a +# bare alpine that runs `date >> /data/runs.log` and exits. +scenario: schedule-tick + +segments: + hosting: + kind: public + cidr: [192.0.2.0/24] + +machines: + anchor: + at: { segment: hosting, address: [192.0.2.10] } + inbound: allow + memory: 3GiB + cpus: 2 + +images: + # The first-node substrate: store, broker, control. + - postgres:17-alpine + - cloudamqp/lavinmq:latest + - mesh-control:development + # The tick container's image. schedtest has no runtime of its own — its scheduled container is a + # bare alpine that appends a timestamp and exits. alpine:latest must be in the local daemon; the + # scenario stocks it and serves it by digest, which is what the manifest pins via pinned("alpine"). + - alpine:latest + +place: + # Only the host — schedtest has no mesh-runtime to place. The tick image is served by the + # scenario's registry and pulled by the host, not placed inside the machine. + all: [host] diff --git a/test/integration/assigned-schedule-tick.test.ts b/test/integration/assigned-schedule-tick.test.ts new file mode 100644 index 0000000..dfceb1e --- /dev/null +++ b/test/integration/assigned-schedule-tick.test.ts @@ -0,0 +1,259 @@ +/** + * The mesh assigns schedtest — the thinnest possible carrier of the scheduled-container primitive + * (novox/hq ADR 0053) — and its scheduled container fires on its cadence WITHOUT the install having + * run it or gated convergence. + * + * schedtest declares one `container` marked `schedule: "* * * * *"` — a bare alpine that appends a + * timestamp line to /data/runs.log (a mounted data directory) each time the host fires it. It is the + * recurring twin of the run-once bed (catalogue-mqtt), with the gating rule deliberately reversed. + * The three claims this bed proves, straight from ADR 0053's "How each claim is checked": + * + * - **Installing it does not run it, and the node is current WITHOUT a run.** Right after the push + * converges (settled → the node reports applied+current), the run log is captured as a baseline; + * the schedule is state that is present, not a step that gated. Cron "* * * * *" fires at the top + * of the next minute, so the baseline is normally empty/absent — but a fire could race the minute + * boundary, so the baseline is a line-count, not an assertion of strict zero. + * - **It fires on its cadence.** Polled for ~150s, the run log gains at least one line beyond the + * baseline — the host's Scheduler fired the container off the clock. + * - **It recurs.** Polled ~150s more, the run log gains a SECOND line — it fired again on the next + * minute, proving recurrence rather than a one-shot. + * + * schedtest neither serves tools nor consumes a provision nor emits/consumes events, and carries no + * runtime of its own, so it is NOT issued a broker account: `module add` → `assign` → ONE `push` is + * the whole sequence, with no `module issue` (a serve/consume-less module needs none — `assign`'s own + * plan resolves without any own-secret). The tick image is a bare alpine served by the scenario's + * registry by digest; the host pulls and runs it on the cadence. + * + * MESH_LAB_HOST_BINARY=.../mesh-host (feat/apply-schedule — the scheduler that fires the step) + * MESH_LAB_BUNDLE=.../examples/substrate-first-node.lock + * MESH_LAB_MODULES=.../mesh-control/examples/modules (feat/schedule-container — the parser that + * carries `schedule` through). scenarios/schedule-tick.yml stocks alpine:latest (which must be in + * the local daemon) and serves it by digest; there is no runtime image — schedtest is a bare tick. + */ + +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 = "schedule-tick"; +const MACHINE = "anchor"; + +let instanceId = ""; +/** What the scenario's registry serves, by digest. */ +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; +} + +/** The control plane, a container on the node. */ +async function mesh(command: string, timeoutMs?: number): Promise { + return must(`docker exec mesh-control /mesh-control ${command}`, timeoutMs); +} + +/** The pinned reference for one of the scenario's images, by repository. */ +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; +} + +/** The substrate bundle, its image references pointed at this scenario's own registry. */ +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; +} + +/** + * How many lines the tick has written so far — tolerant of the run log not existing yet. + * + * The scheduled container appends one line per fire with `date >> /data/runs.log`, and the data + * directory is mounted from /var/lib/schedtest on the machine, so counting newlines there counts + * fires. `wc -l` on an absent file is an error, so a missing file reads as 0 rather than throwing — + * which is exactly the pre-first-fire state. + */ +async function tickLines(): Promise { + const { out } = await on(`wc -l < /var/lib/schedtest/runs.log 2>/dev/null || echo 0`); + const n = Number.parseInt(out.trim(), 10); + return Number.isFinite(n) ? n : 0; +} + +async function settled(withinMs = 600_000): Promise { + const until = Date.now() + withinMs; + let last = ""; + while (Date.now() < until) { + const asked = await on(`docker exec mesh-control /mesh-control 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}`); +} + +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; + + // Raise the substrate — store, broker, control — from the bundle. + 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}`); + } + + // The node joins its own mesh, so it is a node the mesh can assign to, and start the host so it + // applies what it is pushed AND fires scheduled steps off its clock (the daemon holds one + // Scheduler for the life of the process — novox/hq ADR 0053). + 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("the mesh assigns schedtest: installing the schedule does not run it, and the container fires on its cadence, again and again", { + skip, timeout: 1_500_000, +}, async () => { + // A single scheduled container: a bare alpine that appends a timestamp to /data/runs.log each time + // the host fires it, mounted from /var/lib/schedtest on the machine. `schedule: "* * * * *"` makes + // it the recurring twin of a run-once step — installed as present state, fired by the clock, never + // by the apply (ADR 0053). No own-secrets, no broker account: it serves and consumes nothing. The + // image is pinned to what this scenario serves by digest. + const manifest = JSON.stringify({ + module: "schedtest", + version: "1", + resources: [ + { id: "mesh-state", type: "directory", path: "/var/lib/mesh/schedtest", mode: "0700" }, + { id: "data", type: "directory", path: "/var/lib/schedtest", mode: "0700" }, + { + id: "tick", type: "container", name: "schedtest-tick", + image: pinned("alpine"), network: "none", + schedule: "* * * * *", + volumes: ["/var/lib/schedtest:/data"], + args: ["sh", "-c", "date -u +%FT%TZ >> /data/runs.log"], + }, + ], + }); + + await must(`printf %s ${quote(manifest)} > /tmp/schedtest.json && docker cp /tmp/schedtest.json mesh-control:/schedtest.json`); + await mesh("module add /schedtest.json"); + // No `module issue`: schedtest serves/consumes nothing and carries no runtime, so it needs no + // broker account. `assign` resolves its plan (no own-secret to fill) and ONE push converges it. + await mesh(`assign ${MACHINE} schedtest`); + await mesh(`push ${MACHINE}`); + await settled(); + + // --- non-gating: the node is current with the schedule installed, WITHOUT a run having gated ----- + // settled() only returns once the node reports applied+current, so reaching here already proves the + // schedule converged as present state rather than gating on a run (the inversion of run-once). The + // status is re-read to make that an explicit assertion, and the run log is captured as a baseline: + // cron "* * * * *" fires at the top of the next minute, so it is normally empty/absent now, but a + // fire could race the minute boundary — so the baseline is a line-count, not a strict zero. + const status = JSON.parse(await mesh(`status --json`)) as { + reported: { node: string; outcome: string; current: boolean }[]; + }; + const word = status.reported.find((r) => r.node === MACHINE); + assert.ok(word?.outcome === "applied" && word.current, + `installing the schedule should leave ${MACHINE} current without a run gating it:\n${JSON.stringify(status)}`); + const baseline = await tickLines(); + console.log(`schedule-tick: baseline run-log lines right after convergence = ${baseline}`); + + // --- fires on cadence: the host's Scheduler runs the container off the clock ----------------------- + // Poll up to ~150s (the tick fires at the top of the next minute; the daemon evaluates its + // schedules on a minute ticker), asserting the run log gains at least one line beyond the baseline. + let fired = baseline; + const untilFired = Date.now() + 150_000; + while (Date.now() < untilFired) { + fired = await tickLines(); + if (fired > baseline) break; + await new Promise((r) => setTimeout(r, 5000)); + } + assert.ok(fired > baseline, + `the scheduled container never fired: run-log lines stayed at the baseline ${baseline} for ~150s ` + + `after convergence.\n---host log---\n${(await on(`tail -60 /var/log/mesh-host.log`)).out}`); + + // --- recurs: it fires AGAIN on the next minute — recurrence, not a one-shot ------------------------ + // Continue polling up to ~150s more for a SECOND line beyond the baseline. One fire could be a + // run-once by another name; a second fire on the following minute is the proof of cadence. + let again = fired; + const untilAgain = Date.now() + 150_000; + while (Date.now() < untilAgain) { + again = await tickLines(); + if (again > fired) break; + await new Promise((r) => setTimeout(r, 5000)); + } + assert.ok(again > fired, + `the scheduled container fired once (${fired} lines) but did not recur within ~150s — a schedule ` + + `must fire again on its next occurrence, not run once.\n` + + `---host log---\n${(await on(`tail -60 /var/log/mesh-host.log`)).out}`); + assert.ok(again - baseline >= 2, + `expected at least two fires beyond the baseline ${baseline}, saw ${again} total lines`); +}); -- 2.54.0