Files
mesh-lab/test/integration/assigned-schedule-tick.test.ts
T
jschoubben 76ecbaed85 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
2026-09-06 14:20:54 +02:00

260 lines
13 KiB
TypeScript

/**
* 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<string> {
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<string> {
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<number> {
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<void> {
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`);
});