Heimdall/src/index.ts

136 lines
5.5 KiB
TypeScript
Raw Normal View History

import path from "node:path";
Honour the Idunn process write lease, and stop claiming active while warming During a deployment two Heimdall processes exist at once under distinct UIDs and namespaces, and both are configured with the same CultCache store path. Exactly one may write it. Idunn decides which by publishing a lease record naming an incarnation; nothing in Heimdall read it, so both generations would have written heimdall.service.cc. src/process-write-lease.ts answers one question -- may this process write state right now -- by reading the lease and the runtime bundle's expected.cc, and comparing incarnation identity. It grants nothing and throws nothing outward: every failure is a decision of mayWrite:false with a reason, because for a warming candidate "not yet my turn" is the expected condition and crashing would turn it into a failed deployment. Records are decoded as the canonical positional MessagePack Idunn writes (14 fields for the lease, schema-checked), and the tests build the same envelope bytes rather than convenient objects. publishHeimdallVerseState is the single writer, so that is the only place gated. Outside Idunn no lease path is configured and writes proceed unconditionally, which keeps developer runs and the current plain unit working. Second defect found while wiring it: health publication hardcoded state "active". A candidate would have claimed active from its first pulse, which is both untrue and structurally broken -- Idunn must observe `warming` presence before it fences the incumbent, so a candidate that never reports warming cannot be promoted. State is now derived from the lease: warming until held, active after, with the reason carried in the detail string. 49 tests across 11 files; tsc clean under exactOptionalPropertyTypes. The recipe's status banner now records the contract as implemented, with the honest caveat that none of it has been through a live `idunn up` -- the daemon on yggdrasil is still the previous generation, so the first deployment remains the real verification. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 02:25:38 +02:00
import { resolveWriteLease, WriteLeaseNotHeldError } from "./process-write-lease.js";
2026-04-26 12:25:11 +01:00
import { buildApp } from "./app.js";
import { loadConfig } from "./config.js";
import { publishIdunnRudpHealth } from "./idunn-rudp-health.js";
import { publishHeimdallOdinState } from "./odin-publication.js";
import { startHeimdallPrivateCommandPlane } from "./private-command-plane.js";
import type { CultNetOperationServer } from "cultnet-ts";
import { createHeimdallRuntimePulse, buildHeimdallHealthDetail, publishHeimdallVerseState } from "./verse-state.js";
import {
buildPresenceStatement,
nextPublisherSequence,
readRuntimeBundleFacts,
type RuntimeBundleFacts,
} from "./runtime-presence.js";
2026-04-26 12:25:11 +01:00
const config = loadConfig();
const app = await buildApp({ config });
const versePulseIntervalMs = 60_000;
const healthPulseIntervalMs = 10_000;
let privateCommands: CultNetOperationServer | undefined;
2026-04-26 12:25:11 +01:00
try {
privateCommands = await startHeimdallPrivateCommandPlane(app, config);
app.addHook("onClose", async () => privateCommands?.close());
2026-04-26 12:25:11 +01:00
await app.listen({ host: config.host, port: config.port });
app.log.info(`Heimdall listening on ${config.host}:${config.port}`);
app.log.info(`Heimdall private CultNet commands listening at ${privateCommands.endpoint}`);
await publishVerseState().catch((error) => {
console.error("Heimdall verse publication failed on startup:", error);
});
await publishHealthState().catch((error) => {
console.error("Heimdall signed health publication failed on startup:", error);
});
const verseTimer = setInterval(() => {
void publishVerseState().catch((error) => {
console.error("Heimdall verse publication failed on interval:", error);
});
}, versePulseIntervalMs);
void runHealthPulseLoop();
verseTimer.unref?.();
2026-04-26 12:25:11 +01:00
} catch (error) {
await privateCommands?.close().catch(() => undefined);
// Write to stderr directly as well as through the logger. Pino buffers, and
// setting exitCode lets the process exit before that buffer flushes, so a
// startup failure logged only through app.log disappears entirely. Under a
// supervisor that is the worst possible failure: the unit dies, the journal
// holds nothing, and the operator is told only that it is not running.
console.error("Heimdall failed to start:", error);
2026-04-26 12:25:11 +01:00
app.log.error(error);
process.exitCode = 1;
}
async function publishVerseState(): Promise<void> {
const pulse = createHeimdallRuntimePulse(config);
Honour the Idunn process write lease, and stop claiming active while warming During a deployment two Heimdall processes exist at once under distinct UIDs and namespaces, and both are configured with the same CultCache store path. Exactly one may write it. Idunn decides which by publishing a lease record naming an incarnation; nothing in Heimdall read it, so both generations would have written heimdall.service.cc. src/process-write-lease.ts answers one question -- may this process write state right now -- by reading the lease and the runtime bundle's expected.cc, and comparing incarnation identity. It grants nothing and throws nothing outward: every failure is a decision of mayWrite:false with a reason, because for a warming candidate "not yet my turn" is the expected condition and crashing would turn it into a failed deployment. Records are decoded as the canonical positional MessagePack Idunn writes (14 fields for the lease, schema-checked), and the tests build the same envelope bytes rather than convenient objects. publishHeimdallVerseState is the single writer, so that is the only place gated. Outside Idunn no lease path is configured and writes proceed unconditionally, which keeps developer runs and the current plain unit working. Second defect found while wiring it: health publication hardcoded state "active". A candidate would have claimed active from its first pulse, which is both untrue and structurally broken -- Idunn must observe `warming` presence before it fences the incumbent, so a candidate that never reports warming cannot be promoted. State is now derived from the lease: warming until held, active after, with the reason carried in the detail string. 49 tests across 11 files; tsc clean under exactOptionalPropertyTypes. The recipe's status banner now records the contract as implemented, with the honest caveat that none of it has been through a live `idunn up` -- the daemon on yggdrasil is still the previous generation, so the first deployment remains the real verification. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 02:25:38 +02:00
try {
await publishHeimdallVerseState(config, pulse);
} catch (error) {
// A warming candidate does not hold the write lease, and will not until
// Idunn fences the incumbent. That is the expected state for most of a
// deployment, not a fault: decline the write, say so once per pulse at
// info, and keep serving. Health publication continues either way, which
// is what lets Idunn observe the candidate and promote it.
if (error instanceof WriteLeaseNotHeldError) {
app.log.info(error.message);
return;
}
throw error;
}
await publishHeimdallOdinState(config, pulse);
}
/**
* Read once and keep: the bundle is Idunn's immutable record of this launch and
* cannot change while the process lives, so re-reading it every pulse would be
* work that can only ever return the same answer or fail.
*/
let runtimeBundleFacts: RuntimeBundleFacts | undefined;
async function publishHealthState(): Promise<void> {
const pulse = createHeimdallRuntimePulse(config);
Honour the Idunn process write lease, and stop claiming active while warming During a deployment two Heimdall processes exist at once under distinct UIDs and namespaces, and both are configured with the same CultCache store path. Exactly one may write it. Idunn decides which by publishing a lease record naming an incarnation; nothing in Heimdall read it, so both generations would have written heimdall.service.cc. src/process-write-lease.ts answers one question -- may this process write state right now -- by reading the lease and the runtime bundle's expected.cc, and comparing incarnation identity. It grants nothing and throws nothing outward: every failure is a decision of mayWrite:false with a reason, because for a warming candidate "not yet my turn" is the expected condition and crashing would turn it into a failed deployment. Records are decoded as the canonical positional MessagePack Idunn writes (14 fields for the lease, schema-checked), and the tests build the same envelope bytes rather than convenient objects. publishHeimdallVerseState is the single writer, so that is the only place gated. Outside Idunn no lease path is configured and writes proceed unconditionally, which keeps developer runs and the current plain unit working. Second defect found while wiring it: health publication hardcoded state "active". A candidate would have claimed active from its first pulse, which is both untrue and structurally broken -- Idunn must observe `warming` presence before it fences the incumbent, so a candidate that never reports warming cannot be promoted. State is now derived from the lease: warming until held, active after, with the reason carried in the detail string. 49 tests across 11 files; tsc clean under exactOptionalPropertyTypes. The recipe's status banner now records the contract as implemented, with the honest caveat that none of it has been through a live `idunn up` -- the daemon on yggdrasil is still the previous generation, so the first deployment remains the real verification. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 02:25:38 +02:00
// "active" is a claim about owning the target's state, not about having
// started. A candidate that has not been granted the write lease is serving
// but is not the owner, and Idunn must observe `warming` before it fences the
// incumbent — a candidate that reports active from its first pulse cannot be
// promoted correctly, because the warming evidence the transaction needs
// never appears.
const lease = await resolveWriteLease({
leasePath: config.idunnWriteLeasePath,
runtimeBundlePath: config.idunnRuntimeBundlePath,
});
const detail = lease.mayWrite
? buildHeimdallHealthDetail(config, pulse)
: `Heimdall candidate warming; ${lease.reason}`;
if (!config.idunnRuntimeBundlePath) {
// Outside Idunn there is no launch to attest and nothing that admits the
// statement; publishing is simply not part of that world.
return;
}
runtimeBundleFacts ??= await readRuntimeBundleFacts(config.idunnRuntimeBundlePath);
const observedAtUnixMillis = Date.parse(pulse.updatedAt);
const presence = await buildPresenceStatement({
bundle: runtimeBundleFacts,
state: lease.mayWrite ? "active" : "warming",
detail,
boundEndpoint: `http://${config.host}:${config.port}`,
// A warming candidate holds no lease and must not claim one; the contract
// refuses the pair, and Idunn needs the warming statement to promote it.
writeLeaseSha256: null,
observedAtUnixMillis,
publisherSequence: await nextPublisherSequence(
path.join(config.dataRoot, "runtime-presence-sequence"),
),
providerHealthIdentityPath: config.providerHealthIdentityPath,
});
await publishIdunnRudpHealth(config, {
daemonId: config.daemonId,
Honour the Idunn process write lease, and stop claiming active while warming During a deployment two Heimdall processes exist at once under distinct UIDs and namespaces, and both are configured with the same CultCache store path. Exactly one may write it. Idunn decides which by publishing a lease record naming an incarnation; nothing in Heimdall read it, so both generations would have written heimdall.service.cc. src/process-write-lease.ts answers one question -- may this process write state right now -- by reading the lease and the runtime bundle's expected.cc, and comparing incarnation identity. It grants nothing and throws nothing outward: every failure is a decision of mayWrite:false with a reason, because for a warming candidate "not yet my turn" is the expected condition and crashing would turn it into a failed deployment. Records are decoded as the canonical positional MessagePack Idunn writes (14 fields for the lease, schema-checked), and the tests build the same envelope bytes rather than convenient objects. publishHeimdallVerseState is the single writer, so that is the only place gated. Outside Idunn no lease path is configured and writes proceed unconditionally, which keeps developer runs and the current plain unit working. Second defect found while wiring it: health publication hardcoded state "active". A candidate would have claimed active from its first pulse, which is both untrue and structurally broken -- Idunn must observe `warming` presence before it fences the incumbent, so a candidate that never reports warming cannot be promoted. State is now derived from the lease: warming until held, active after, with the reason carried in the detail string. 49 tests across 11 files; tsc clean under exactOptionalPropertyTypes. The recipe's status banner now records the contract as implemented, with the honest caveat that none of it has been through a live `idunn up` -- the daemon on yggdrasil is still the previous generation, so the first deployment remains the real verification. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 02:25:38 +02:00
state: lease.mayWrite ? "active" : "warming",
detail,
observedAt: pulse.updatedAt,
presence,
});
}
async function runHealthPulseLoop(): Promise<void> {
for (;;) {
await new Promise((resolve) => setTimeout(resolve, healthPulseIntervalMs));
await publishHealthState().catch((error) => {
console.error("Heimdall signed health publication failed on interval:", error);
});
}
}