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>
This commit is contained in:
Meta Vens 2026-09-06 02:25:38 +02:00
commit 726dd56e7d
6 changed files with 410 additions and 15 deletions

View file

@ -1,17 +1,23 @@
# NOT YET DEPLOYABLE, but closer. Status 2026-09-06:
# The runtime contract below is implemented as of 2026-09-06.
#
# done GAMECULT_IDUNN_CANDIDATE_BIND -- src/config.ts takes the candidate
# socket over HOST/PORT, requires loopback and a usable port, and
# refuses to start unless GC_ACCESS_BASE_URL is set explicitly, so
# an ephemeral candidate port can never become the provider-
# registered OAuth callback.
# pending GAMECULT_IDUNN_PROCESS_WRITE_LEASE -- declared here because the
# state slot below is process-bound-single-writer, and unread by the
# service. Two generations could both open heimdall.service.cc.
# pending GAMECULT_IDUNN_RUNTIME_BUNDLE -- declared and unread.
# GAMECULT_IDUNN_CANDIDATE_BIND src/config.ts takes the candidate socket
# over HOST/PORT, requires loopback and a
# usable port, and refuses to start unless
# GC_ACCESS_BASE_URL is set, so an
# ephemeral port can never become the
# provider-registered OAuth callback.
# GAMECULT_IDUNN_PROCESS_WRITE_LEASE src/process-write-lease.ts. The single
# writer of heimdall.service.cc declines
# unless the lease names this incarnation.
# GAMECULT_IDUNN_RUNTIME_BUNDLE read for expected.cc, which is how the
# process learns which incarnation it is.
#
# Do not `idunn up heimdall` until the write lease is honoured. Health
# publication already exists in src/idunn-rudp-health.ts.
# Health reports `warming` until the lease is held and `active` after, because
# Idunn must observe warming presence before it fences the incumbent.
#
# Still untested against a live Idunn: nothing here has been through an actual
# `idunn up heimdall`, and the daemon on yggdrasil is still the previous
# generation. Treat the first deployment as the real verification.
schema = "gamecult.idunn.target_declaration.v1"
target = "heimdall"

View file

@ -22,6 +22,8 @@ export interface HeimdallConfig {
workspaceRoot: string;
dataRoot: string;
cultCachePath: string;
idunnWriteLeasePath?: string | undefined;
idunnRuntimeBundlePath?: string | undefined;
publicBaseUrl: string;
issuer: string;
daemonId: string;
@ -200,6 +202,8 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
privateCommandPort: readInt(env.GC_ACCESS_PRIVATE_COMMAND_PORT, 4101),
workspaceRoot,
dataRoot,
idunnWriteLeasePath: env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE,
idunnRuntimeBundlePath: env.GAMECULT_IDUNN_RUNTIME_BUNDLE,
cultCachePath: env.GC_ACCESS_CULTCACHE_PATH ?? path.join(dataRoot, "cultcache", "heimdall.service.cc"),
publicBaseUrl,
issuer,

View file

@ -1,3 +1,4 @@
import { resolveWriteLease, WriteLeaseNotHeldError } from "./process-write-lease.js";
import { buildApp } from "./app.js";
import { loadConfig } from "./config.js";
import { publishIdunnRudpHealth } from "./idunn-rudp-health.js";
@ -39,16 +40,44 @@ try {
async function publishVerseState(): Promise<void> {
const pulse = createHeimdallRuntimePulse(config);
await publishHeimdallVerseState(config, pulse);
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);
}
async function publishHealthState(): Promise<void> {
const pulse = createHeimdallRuntimePulse(config);
// "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}`;
await publishIdunnRudpHealth(config, {
daemonId: config.daemonId,
state: "active",
detail: buildHeimdallHealthDetail(config, pulse),
state: lease.mayWrite ? "active" : "warming",
detail,
observedAt: pulse.updatedAt,
});
}

192
src/process-write-lease.ts Normal file
View file

@ -0,0 +1,192 @@
/**
* Idunn process write lease.
*
* During a deployment Idunn runs a candidate incarnation alongside the
* incumbent, under a distinct UID and distinct PID/mount namespaces, so for a
* while two Heimdall processes exist at once. Exactly one of them may write the
* CultCache service store. Idunn decides which, by publishing a lease record
* naming an incarnation; a process that is not that incarnation must not write.
*
* This module answers one question — may this process write state right now —
* and answers it by reading, never by asserting. It grants nothing. Absence of
* a lease is a "no", not an error: a warming candidate legitimately has not been
* granted one yet and is expected to keep asking.
*
* Outside Idunn (developer runs, the plain systemd unit) no lease path is
* configured and the answer is an unconditional yes, because there is no second
* generation to collide with.
*/
import { readFile } from "node:fs/promises";
import path from "node:path";
import { decode } from "@msgpack/msgpack";
const WRITE_LEASE_SCHEMA = "idunn.process_write_lease.v1";
const EXPECTED_INCARNATION_SCHEMA = "idunn.expected_incarnation.v2";
/** Positional field indexes in the canonical contracts. */
const LEASE_SCHEMA_VERSION = 0;
const LEASE_TARGET = 1;
const LEASE_INCARNATION_ID = 4;
const LEASE_RUNTIME_INSTANCE_ID = 10;
const LEASE_EPOCH = 12;
const LEASE_FIELD_COUNT = 14;
const EXPECTED_SCHEMA_VERSION = 0;
const EXPECTED_TARGET = 1;
const EXPECTED_INCARNATION_ID = 3;
export interface WriteLeaseInputs {
/** GAMECULT_IDUNN_PROCESS_WRITE_LEASE — path to the lease record. */
leasePath?: string | undefined;
/** GAMECULT_IDUNN_RUNTIME_BUNDLE — directory holding expected.cc. */
runtimeBundlePath?: string | undefined;
}
/**
* Thrown when a state write is declined for want of the lease. Distinct from an
* ordinary failure on purpose: for a warming candidate this is the expected
* condition, not an incident, and callers should log it accordingly rather than
* reporting a broken daemon every pulse.
*/
export class WriteLeaseNotHeldError extends Error {
constructor(reason: string) {
super(`Idunn process write lease not held: ${reason}`);
this.name = "WriteLeaseNotHeldError";
}
}
export type WriteLeaseDecision =
| { mayWrite: true; reason: "not-under-idunn" }
| { mayWrite: true; reason: "held"; incarnationId: string; leaseEpoch: number }
| { mayWrite: false; reason: string };
function positionalFields(payload: Uint8Array, label: string): unknown[] {
const decoded = decode(payload);
if (!Array.isArray(decoded)) {
throw new Error(`${label} is not positional MessagePack`);
}
return decoded;
}
function stringField(fields: unknown[], index: number, label: string): string {
const value = fields[index];
if (typeof value !== "string" || value.length === 0) {
throw new Error(`${label} field ${index} is not a non-empty string`);
}
return value;
}
/**
* Envelopes are `{ key, type, payload, storedAt }`; only the payload carries
* the positional record. Read the file directly rather than through the store
* helper: this must work on a store owned by another UID, and it must never
* create the file it is inspecting.
*/
async function readEnvelopePayload(file: string, label: string): Promise<Uint8Array> {
const bytes = await readFile(file);
const entries = decode(bytes);
const envelopes = Array.isArray(entries) ? entries : [entries];
const last = envelopes[envelopes.length - 1];
if (!last || typeof last !== "object") {
throw new Error(`${label} holds no CultCache envelope`);
}
const payload = (last as Record<string, unknown>).payload;
if (!(payload instanceof Uint8Array)) {
throw new Error(`${label} envelope has no binary payload`);
}
return payload;
}
/**
* Resolve whether this process holds the write lease.
*
* Every failure path returns `mayWrite: false` with a reason rather than
* throwing. A candidate that cannot prove it holds the lease must decline to
* write, and it must keep running so it can publish warming health and be
* promoted — crashing would turn "not yet my turn" into a failed deployment.
*/
export async function resolveWriteLease(inputs: WriteLeaseInputs): Promise<WriteLeaseDecision> {
if (!inputs.leasePath) {
return { mayWrite: true, reason: "not-under-idunn" };
}
if (!inputs.runtimeBundlePath) {
return {
mayWrite: false,
reason:
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE is set without GAMECULT_IDUNN_RUNTIME_BUNDLE, " +
"so this process cannot identify which incarnation it is",
};
}
let expectedTarget: string;
let expectedIncarnationId: string;
try {
const payload = await readEnvelopePayload(
path.join(inputs.runtimeBundlePath, "expected.cc"),
"expected incarnation"
);
const fields = positionalFields(payload, "expected incarnation");
const schema = stringField(fields, EXPECTED_SCHEMA_VERSION, "expected incarnation");
if (schema !== EXPECTED_INCARNATION_SCHEMA) {
return { mayWrite: false, reason: `expected incarnation schema is ${schema}` };
}
expectedTarget = stringField(fields, EXPECTED_TARGET, "expected incarnation");
expectedIncarnationId = stringField(fields, EXPECTED_INCARNATION_ID, "expected incarnation");
} catch (error) {
return { mayWrite: false, reason: `unreadable runtime bundle: ${String(error)}` };
}
let fields: unknown[];
try {
fields = positionalFields(
await readEnvelopePayload(inputs.leasePath, "process write lease"),
"process write lease"
);
} catch (error) {
// No lease yet is the ordinary state of a warming candidate.
return { mayWrite: false, reason: `no readable write lease: ${String(error)}` };
}
if (fields.length !== LEASE_FIELD_COUNT) {
return {
mayWrite: false,
reason: `write lease is not the ${LEASE_FIELD_COUNT}-field positional contract`,
};
}
try {
const schema = stringField(fields, LEASE_SCHEMA_VERSION, "process write lease");
if (schema !== WRITE_LEASE_SCHEMA) {
return { mayWrite: false, reason: `write lease schema is ${schema}` };
}
const target = stringField(fields, LEASE_TARGET, "process write lease");
if (target !== expectedTarget) {
return { mayWrite: false, reason: `write lease belongs to target ${target}` };
}
const incarnationId = stringField(fields, LEASE_INCARNATION_ID, "process write lease");
if (incarnationId !== expectedIncarnationId) {
return {
mayWrite: false,
reason: `write lease is held by incarnation ${incarnationId}, not this one`,
};
}
stringField(fields, LEASE_RUNTIME_INSTANCE_ID, "process write lease");
const leaseEpoch = fields[LEASE_EPOCH];
if (typeof leaseEpoch !== "number" || !Number.isInteger(leaseEpoch) || leaseEpoch < 0) {
return { mayWrite: false, reason: "write lease has no usable epoch" };
}
return { mayWrite: true, reason: "held", incarnationId, leaseEpoch };
} catch (error) {
return { mayWrite: false, reason: `malformed write lease: ${String(error)}` };
}
}

View file

@ -1,3 +1,4 @@
import { resolveWriteLease, WriteLeaseNotHeldError } from "./process-write-lease.js";
import { mkdir, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { encode } from "@msgpack/msgpack";
@ -39,6 +40,19 @@ export function createHeimdallRuntimePulse(config: HeimdallConfig, updatedAt = n
}
export async function publishHeimdallVerseState(config: HeimdallConfig, pulse: HeimdallRuntimePulse): Promise<void> {
// Under Idunn a warming candidate shares this store's path with the running
// incumbent. Writing without the lease would let two generations overwrite
// one another's snapshot, so a candidate stays quiet until it is granted the
// lease — which is also the state it is in for most of its warming window.
const lease = await resolveWriteLease({
leasePath: config.idunnWriteLeasePath,
runtimeBundlePath: config.idunnRuntimeBundlePath,
});
if (!lease.mayWrite) {
throw new WriteLeaseNotHeldError(lease.reason);
}
const records: CultCacheRecord[] = [
...buildHeimdallVerseRecords(config, pulse),
{

View file

@ -0,0 +1,150 @@
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { encode } from "@msgpack/msgpack";
import { describe, expect, it } from "vitest";
import { resolveWriteLease } from "../src/process-write-lease.js";
/**
* Idunn writes CultCache envelopes whose payload is the canonical positional
* MessagePack encoding of the record. These helpers reproduce that shape, so
* the tests exercise the same bytes the daemon will actually be handed rather
* than a convenient object.
*/
function envelope(key: string, type: string, payload: Uint8Array): Uint8Array {
return encode([{ key, type, payload, storedAt: "2026-09-06T00:00:00.000Z" }]);
}
function expectedIncarnation(target: string, incarnationId: string): Uint8Array {
const fields = new Array(12).fill("x");
fields[0] = "idunn.expected_incarnation.v2";
fields[1] = target;
fields[3] = incarnationId;
return encode(fields);
}
function writeLease(target: string, incarnationId: string, epoch = 3): Uint8Array {
const fields: unknown[] = new Array(14).fill("x");
fields[0] = "idunn.process_write_lease.v1";
fields[1] = target;
fields[4] = incarnationId;
fields[10] = "runtime-instance-1";
fields[12] = epoch;
fields[13] = 1757116800000;
return encode(fields);
}
async function bundleWith(
expectedBytes: Uint8Array | undefined,
leaseBytes: Uint8Array | undefined
): Promise<{ bundle: string; lease: string }> {
const root = await mkdtemp(path.join(os.tmpdir(), "heimdall-lease-"));
const bundle = path.join(root, "runtime-instance-1");
await mkdir(bundle, { recursive: true });
if (expectedBytes) {
await writeFile(
path.join(bundle, "expected.cc"),
envelope("heimdall", "idunn.expected_incarnation", expectedBytes)
);
}
const lease = path.join(root, "process-write-lease.cc");
if (leaseBytes) {
await writeFile(lease, envelope("heimdall", "idunn.process_write_lease", leaseBytes));
}
return { bundle, lease };
}
describe("Idunn process write lease", () => {
it("permits writes when not launched by Idunn", async () => {
// A developer run and the current plain systemd unit have no second
// generation to collide with.
await expect(resolveWriteLease({})).resolves.toMatchObject({
mayWrite: true,
reason: "not-under-idunn",
});
});
it("permits writes when the lease names this incarnation", async () => {
const { bundle, lease } = await bundleWith(
expectedIncarnation("heimdall", "incarnation-a"),
writeLease("heimdall", "incarnation-a", 7)
);
await expect(
resolveWriteLease({ leasePath: lease, runtimeBundlePath: bundle })
).resolves.toMatchObject({ mayWrite: true, reason: "held", incarnationId: "incarnation-a", leaseEpoch: 7 });
});
it("refuses writes when the lease names the other generation", async () => {
// The case the lease exists for: a warming candidate while the incumbent
// still holds the store.
const { bundle, lease } = await bundleWith(
expectedIncarnation("heimdall", "incarnation-candidate"),
writeLease("heimdall", "incarnation-incumbent")
);
const decision = await resolveWriteLease({ leasePath: lease, runtimeBundlePath: bundle });
expect(decision.mayWrite).toBe(false);
expect(decision.reason).toContain("incarnation-incumbent");
});
it("refuses writes when no lease has been granted yet", async () => {
const { bundle, lease } = await bundleWith(
expectedIncarnation("heimdall", "incarnation-a"),
undefined
);
const decision = await resolveWriteLease({ leasePath: lease, runtimeBundlePath: bundle });
expect(decision.mayWrite).toBe(false);
expect(decision.reason).toContain("no readable write lease");
});
it("refuses writes when the lease belongs to another target", async () => {
const { bundle, lease } = await bundleWith(
expectedIncarnation("heimdall", "incarnation-a"),
writeLease("ghostlight", "incarnation-a")
);
const decision = await resolveWriteLease({ leasePath: lease, runtimeBundlePath: bundle });
expect(decision.mayWrite).toBe(false);
expect(decision.reason).toContain("ghostlight");
});
it("refuses writes on a wrong-length or wrong-schema lease", async () => {
const short = encode(new Array(9).fill("x"));
const wrongSchema = encode(
Object.assign(new Array(14).fill("x"), { 0: "idunn.process_write_lease.v0", 12: 1 })
);
for (const bytes of [short, wrongSchema]) {
const { bundle, lease } = await bundleWith(
expectedIncarnation("heimdall", "incarnation-a"),
bytes
);
const decision = await resolveWriteLease({ leasePath: lease, runtimeBundlePath: bundle });
expect(decision.mayWrite).toBe(false);
}
});
it("refuses writes when a lease path is set without a runtime bundle", async () => {
// Launch inputs are incoherent; declining is the safe reading.
const decision = await resolveWriteLease({ leasePath: "/nonexistent/lease.cc" });
expect(decision.mayWrite).toBe(false);
expect(decision.reason).toContain("GAMECULT_IDUNN_RUNTIME_BUNDLE");
});
it("refuses writes when the runtime bundle is unreadable", async () => {
const { lease } = await bundleWith(undefined, writeLease("heimdall", "incarnation-a"));
const decision = await resolveWriteLease({
leasePath: lease,
runtimeBundlePath: "/nonexistent/bundle",
});
expect(decision.mayWrite).toBe(false);
expect(decision.reason).toContain("unreadable runtime bundle");
});
});